【问题标题】:Keras: How to feed input directly into other hidden layers of the neural net than the first?Keras:如何将输入直接馈送到神经网络的其他隐藏层而不是第一个?
【发布时间】:2016-06-02 16:25:22
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

    • 哦,我明白了。是的,我真的使用了“顺序”设置。感谢您的帮助和链接!
    【解决方案2】:

    如果您的 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)
    

    【讨论】:

    • 感谢您的帮助,Serj。我想我现在理解了这个概念。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      相关资源
      最近更新 更多