层之间的自定义连接Keras [英] Custom connections between layers Keras
问题描述
我想使用keras和Python在层之间的神经网络中手动定义连接.默认情况下,连接位于所有成对的神经元之间.我需要进行连接,如下图所示.
I would like to manually define connections in neural network between layers using keras with Python. By default connections are beween all pairs of neurons. I need to make connections as in picture below.
如何在Keras中完成工作?
How can I be done in Keras?
推荐答案
您可以使用功能性API模型并将四个不同的组分开:
You can use the functional API model and separate four distinct groups:
from keras.models import Model
from keras.layers import Dense, Input, Concatenate, Lambda
inputTensor = Input((8,))
首先,我们可以使用lambda层将此输入分为四个部分:
First, we can use lambda layers to split this input in four:
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)
在连接最后一层之前,我们将上面的四个张量连接起来:
Before we connect the last layer, we concatenate the four tensors above:
outputTensor = Concatenate()([group1,group2,group3,group4])
最后一层:
outputTensor = Dense(2)(outputTensor)
#create the model:
model = Model(inputTensor,outputTensor)
当心偏见.如果希望这些层中的任何一层都没有偏差,请使用use_bias=False
.
Beware of the biases. If you want any of those layers to have no bias, use use_bias=False
.
旧答案:向后
对不起,我第一次回答时就倒向看到了您的图片.我把它保留在这里只是因为它已经完成了...
Sorry, I saw your image backwards the first time I answered. I'm keeping this here just because it's done...
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)
这篇关于层之间的自定义连接Keras的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!