在keras中建立“非完全连接”(单连接?)神经网络

时间:2019-06-30 13:00:51

标签: keras neural-network deep-learning keras-layer

我不知道我要寻找的名称,但我想在keras中创建一个图层,其中每个输入都乘以其自己独立的权重和偏见。例如。如果有10个输入,则将有10个权重和10个偏差,并且每个输入都将乘以其权重并与其偏差相加,以获得10个输出。

例如,这是一个简单的密集网络:

from keras.layers import Input, Dense
from keras.models import Model
N = 10
input = Input((N,))
output = Dense(N)(input)
model = Model(input, output)
model.summary()

如您所见,该模型具有110个参数,因为它已完全连接:

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_2 (InputLayer)         (None, 10)                0         
_________________________________________________________________
dense_2 (Dense)              (None, 10)                110       
=================================================================
Total params: 110
Trainable params: 110
Non-trainable params: 0
_________________________________________________________________

我想用output = Dense(N)(input)之类的内容替换output = SinglyConnected()(input),以使该模型现在具有20个参数:10个权重和10个Bias。

1 个答案:

答案 0 :(得分:2)

创建自定义图层:

class SingleConnected(Layer):

    #creator
    def __init__(self, **kwargs):
        super(SingleConnected, self).__init__(**kwargs)

   #creates weights
   def build(self, input_shape):

       weight_shape = (1,) * (len(input_shape) - 1)
       weight_shape = weight_shape + (input_shape[-1]) #(....., input)

       self.kernel = self.add_weight(name='kernel', 
                                  shape=weight_shape,
                                  initializer='uniform',
                                  trainable=True)

       self.bias = self.add_weight(name='bias', 
                                   shape=weight_shape,
                                   initializer='zeros',
                                   trainable=True)

       self.built=True

   #operation:
   def call(self, inputs):
       return (inputs * self.kernel) + self.bias

   #output shape
   def compute_output_shape(self, input_shape):
       return input_shape

   #for saving the model - only necessary if you have parameters in __init__
   def get_config(self):
       config = super(SingleConnected, self).get_config()
       return config

使用图层:

model.add(SingleConnected())
相关问题