我想以顺序的方式训练一个模型。也就是说,我希望最初使用简单的体系结构训练模型,一旦训练完成,我想添加几个层并继续训练。在Keras中可以做到这一点吗?如果是这样的话,是怎么做的?
我试图修改模型架构。但在我编译之前,这些更改是无效的。一旦我编译了,所有的权重都被重新初始化,并且我丢失了所有训练过的信息。
我发现,web上的所有问题要么是关于加载预训练模型并继续训练,要么是修改预训练模型的体系结构,然后只对其进行测试。我没有找到任何与我的问题相关的东西。任何指针也是高度赞赏的。
PS:我使用的是tensorflow 2.0包中的Keras。
发布于 2020-03-09 11:06:28
在不了解模型详细信息的情况下,以下代码片段可能会有所帮助:
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应用编程接口将其与您的附加层一起包装。如果您不熟悉Keras,可以查看Model文档here ( Tensorflow.Keras 2.0的API保持不变)。
请注意,您需要检查初始模型的最终层的输出形状是否与其他层兼容(例如,如果您只是在进行特征提取,则可能希望从初始模型中删除最终的致密层)。
https://stackoverflow.com/questions/60593624
复制相似问题