【问题标题】:How to use the last hidden layer weights from one pre-trained MLP as input to a new MLP (transfer learning) with Keras?如何使用来自预训练 MLP 的最后一个隐藏层权重作为 Keras 新 MLP(迁移学习)的输入?
【发布时间】:2019-01-05 17:52:27
【问题描述】:

我想用简单的 MLP 模型进行迁移学习。首先,我在大数据上训练一个隐藏层的前馈网络:

net = Sequential()
net.add(Dense(500, input_dim=2048, kernel_initializer='normal', activation='relu'))
net.add(Dense(1, kernel_initializer='normal'))
net.compile(loss='mean_absolute_error', optimizer='adam')
net.fit(x_transf, 
        y_transf,
        epochs=1000, 
        batch_size=8, 
        verbose=0)

然后我想将唯一的隐藏层作为输入传递给一个新网络,我想在其中添加第二层。重复使用的层不应该是可训练的。

idx = 1  # index of desired layer
input_shape = net.layers[idx].get_input_shape_at(0) # get the input shape of desired layer
input_layer = net.layers[idx]
input_layer.trainable = False

transf_model = Sequential()
transf_model.add(input_layer)
transf_model.add(Dense(input_shape[1], activation='relu'))
transf_model.compile(loss='mean_absolute_error', optimizer='adam')
transf_model.fit(x, 
                 y,
                 epochs=10, 
                 batch_size=8, 
                 verbose=0)

编辑: 以上代码返回:

ValueError: Error when checking target: expected dense_9 to have shape (None, 500) but got array with shape (436, 1)

实现这个功能的诀窍是什么?

【问题讨论】:

  • 您在第二个模型中使用的共享层需要 2D 输入,但您正在为模型提供 3D 输入?!
  • 拜托,有人吗?对于熟悉 Keras 的人来说,答案一定相当简单。
  • 你看我的评论了吗?
  • @today 阅读我的编辑。
  • 第二个模型中的最后一个Dense 层应该有1 个单位,而不是input_shape[0] 单位,对吧?我认为你让它有点复杂。有更好的方法来做到这一点。

标签: python machine-learning keras keras-layer transfer-learning


【解决方案1】:

我会简单地使用Functional API 来构建这样一个模型:

shared_layer = net.layers[0] # you want the first layer, so index = 0
shared_layer.trainable = False

inp = Input(the_shape_of_one_input_sample) # e.g. (2048,)
x = shared_layer(inp)
x = Dense(800, ...)(x)
out = Dense(1, ...)(x)

model = Model(inp, out)

# the rest is the same...

【讨论】:

  • 如果第一个网络有 2 个隐藏层,我想将它们都转移到新网络中怎么办?
  • @tevang 它是一样的:你得到层并将它们应用于张量(即先前层的输出)。例如,x = shared_layer1(inp),然后是 x = shared_layer2(x)
  • 是的,就是这样!非常感谢!
猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 2021-07-15
  • 2018-02-10
  • 2021-04-17
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
相关资源
最近更新 更多