为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

神不在的星期二 2022-08-25 14:06:29
我想以顺序方式训练模型。也就是说,我想首先使用简单的体系结构来训练模型,一旦训练完毕,我想添加几层并继续训练。在Keras中可以做到这一点吗?如果是这样,如何?我试图修改模型架构。但在我编译之前,这些更改是无效的。编译后,所有权重都会重新初始化,并且我丢失了所有经过训练的信息。我在Web和SO中发现的所有问题都是关于加载预训练模型并继续训练或修改预训练模型的架构,然后仅对其进行测试。我没有找到与我的问题相关的任何内容。任何指针也受到高度赞赏。PS:我在tensorflow 2.0包中使用Keras。
查看完整描述

1 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

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


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(...)

基本上,你训练你的初始模型,保存它。然后再次重新加载它,并使用 API 将其与其他层包装在一起。如果您不熟悉API,可以在此处查看Keras文档(afaik API对于Tensorflow.Keras 2.0保持不变)。ModelModel


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


查看完整回答
反对 回复 2022-08-25
  • 1 回答
  • 0 关注
  • 184 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号