Keras:如何将输入直接输入神经网络的其他隐藏层而不是第一个?

时间:2016-02-21 07:18:17

标签: machine-learning neural-network keras theano conv-neural-network

我有一个关于使用Keras的问题,我很新。我使用卷积神经网络将其结果输入标准感知器层,生成我的输出。该CNN被馈送一系列图像。到目前为止,这是很正常的。

现在我想将一个简短的非图像输入向量直接传递到最后一个感知器层,而不是通过所有CNN层发送它。怎么能在Keras做到这一点?

我的代码如下所示:

# last CNN layer before perceptron layer
model.add(Convolution2D(200, 2, 2, border_mode='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Dropout(0.25))

# perceptron layer
model.add(Flatten())

# here I like to add to the input from the CNN an additional vector directly

model.add(Dense(1500, W_regularizer=l2(1e-3)))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))

非常感谢任何答案,谢谢!

3 个答案:

答案 0 :(得分:6)

您没有显示您正在使用哪种模型,但我假设您已将模型初始化为顺序模型。在顺序模型中,您只能堆叠一层又一层 - 因此无法添加“快捷方式”连接。

因此,Keras的作者添加了构建“图形”模型的选项。在这种情况下,您可以构建计算的图形(DAG)。它比设计一叠层更复杂,但仍然很容易。

查看文档站点以查找更多详细信息: http://keras.io/models/#using-the-graph-model

答案 1 :(得分:4)

如果您的Keras的后端是Theano,您可以执行以下操作:

import theano
import numpy as np

d = Dense(1500, W_regularizer=l2(1e-3), activation='relu') # I've joined activation and dense layers, based on assumption you might be interested in post-activation values
model.add(d)
model.add(Dropout(0.5))
model.add(Dense(1))

c = theano.function([d.get_input(train=False)], d.get_output(train=False))
layer_input_data = np.random.random((1,20000)).astype('float32') # refer to d.input_shape to get proper dimensions of layer's input, in my case it was (None, 20000)
o = c(layer_input_data)

答案 2 :(得分:0)

答案here的效果更高,也适用于tensorflow后端:

input_1 = Input(input_shape)
input_2 = Input(input_shape)

merge = merge([input_1, input_2], mode="concat")  # could also to "sum", "dot", etc.
hidden = Dense(hidden_dims)(merge)
classify = Dense(output_dims, activation="softmax")(hidden)

model = Model(input=[input_1, input_2], output=hidden)