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

Mar*_*o K 8 machine-learning neural-network theano conv-neural-network keras

我有一个关于使用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))
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*jko 6

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

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

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


Ser*_*nko 5

假设您的 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)
Run Code Online (Sandbox Code Playgroud)