层之间的自定义连接Keras

时间:2017-11-13 13:25:22

标签: python neural-network keras keras-layer

我想使用带有Python的keras在层之间手动定义神经网络中的连接。默认情况下,连接在所有神经元对之间。我需要建立如下图所示的连接。

required architecture

如何在Keras完成?

1 个答案:

答案 0 :(得分:6)

您可以使用功能API模型并分隔四个不同的组:

from keras.models import Model
from keras.layers import Dense, Input, Concatenate, Lambda

inputTensor = Input((8,))

首先,我们可以使用lambda图层将此输入拆分为四个:

group1 = Lambda(lambda x: x[:,:2], output_shape=((2,)))(inputTensor)
group2 = Lambda(lambda x: x[:,2:4], output_shape=((2,)))(inputTensor)
group3 = Lambda(lambda x: x[:,4:6], output_shape=((2,)))(inputTensor)
group4 = Lambda(lambda x: x[:,6:], output_shape=((2,)))(inputTensor)

现在我们关注网络:

#second layer in your image
group1 = Dense(1)(group1)
group2 = Dense(1)(group2)
group3 = Dense(1)(group3)   
group4 = Dense(1)(group4)

在我们连接最后一层之前,我们连接上面的四个张量:

outputTensor = Concatenate()([group1,group2,group3,group4])

最后一层:

outputTensor = Dense(2)(outputTensor)

#create the model:
model = Model(inputTensor,outputTensor)

小心偏见。如果您希望这些图层中没有任何偏差,请使用use_bias=False

旧答案:向后

抱歉,我第一次回答时看到了你的图片。我保留这里只是因为它完成了......

from keras.models import Model
from keras.layers import Dense, Input, Concatenate

inputTensor = Input((2,))

#four groups of layers, all of them taking the same input tensor
group1 = Dense(1)(inputTensor)
group2 = Dense(1)(inputTensor)
group3 = Dense(1)(inputTensor)   
group4 = Dense(1)(inputTensor)

#the next layer in each group takes the output of the previous layers
group1 = Dense(2)(group1)
group2 = Dense(2)(group2)
group3 = Dense(2)(group3)
group4 = Dense(2)(group4)

#now we join the results in a single tensor again:
outputTensor = Concatenate()([group1,group2,group3,group4])

#create the model:
model = Model(inputTensor,outputTensor)