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

Keras: How to feed input directly into other hidden layers of the neural net than the first?

我有一个关于使用 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))

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

假设你的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)

你没有向我展示你使用的是哪种模型,但我假设你将模型初始化为 Sequential。在 Sequential 模型中,您只能一层接一层地堆叠 - 因此添加“捷径”连接是不可能的。

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

查看文档 site 以查找更多详细信息。

答案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)