修改已训练模型的结构并继续使用Keras进行训练

7

我想以序列方式训练一个模型。也就是说,我想用简单的架构对模型进行初始训练,一旦训练完成,我想再添加几层并继续训练。在Keras中是否可能实现这一点?如果可以,怎么做呢?

我尝试修改了模型架构,但在编译之前更改不会生效。一旦我编译,所有权重都将重新初始化,我就会失去所有训练信息。

我在网络和SO上找到的所有问题要么是关于加载预训练模型并继续训练,要么是修改预训练模型的架构,然后只测试它。我没有找到任何与我的问题相关的内容。非常感谢任何提示。

PS:我正在使用tensorflow 2.0包中的Keras。

1个回答

4

如果不知道你的模型的详细信息,以下代码片段可能会有所帮助:

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input

# Train your initial model
def get_initial_model():
    ...
    return model

model = get_initial_model()
model.fit(...)
model.save_weights('initial_model_weights.h5')

# Use Model API to create another model, built on your initial model
initial_model = get_initial_model()
initial_model.load_weights('initial_model_weights.h5')

nn_input = Input(...)
x = initial_model(nn_input)
x = Dense(...)(x)  # This is the additional layer, connected to your initial model
nn_output = Dense(...)(x)

# Combine your model
full_model = Model(inputs=nn_input, outputs=nn_output)

# Compile and train as usual
full_model.compile(...)
full_model.fit(...)

基本上,您需要训练初始模型并保存它。然后重新加载它,并使用Model API将其与其他层包装在一起。如果您不熟悉Model API,则可以在这里查看Keras文档(据我所知,对于Tensorflow.Keras 2.0,API保持不变)。

请注意,您需要检查初始模型的最后一层输出形状是否与其他层兼容(例如,如果您只是进行特征提取,则可能需要从初始模型中删除最后的Dense层)。


谢谢。我会尝试这个。只有一个疑问。当我在最后调用编译时,它不会重新初始化所有层的权重吗? - Nagabhushan S N
1
不会的。这个线程回答了你对compile实际作用的疑问。 - Toukenize

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接