修改训练有素的模型架构并继续训练Keras

时间:2020-03-09 01:18:24

标签: python tensorflow keras pre-trained-model

我想按顺序训练模型。那就是我想首先使用简单的体系结构来训练模型,并且一旦对其进行训练,我想添加几层并继续训练。在Keras可以这样做吗?如果是这样,怎么办?

我试图修改模型架构。但是直到我编译,这些更改才有效。编译后,所有权重都会重新初始化,并且丢失所有训练有素的信息。

我在Web和SO中发现的所有问题都与加载预训练模型并继续训练或修改预训练模型的体系结构有关,然后仅对其进行测试。我没有发现与我的问题有关的任何内容。任何指针也受到高度赞赏。

PS:我在tensorflow 2.0软件包中使用Keras。

1 个答案:

答案 0 :(得分:3)

在不了解模型详细信息的情况下,以下代码段可能会有所帮助:

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文档here(afaik该API与Tensorflow.Keras 2.0相同)。

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