gpt4 book ai didi

python - 如何使用 Keras 预训练 MLP 的最后一个隐藏层权重作为新 MLP(迁移学习)的输入?

转载 作者:行者123 更新时间:2023-11-30 09:44:41 25 4
gpt4 key购买 nike

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

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)

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

最佳答案

我会简单地使用 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...

关于python - 如何使用 Keras 预训练 MLP 的最后一个隐藏层权重作为新 MLP(迁移学习)的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com