【问题标题】:Modify trained model architecture and continue training Keras修改训练好的模型架构并继续训练 Keras
【发布时间】:2020-06-20 22:24:50
【问题描述】:

我想以顺序方式训练模型。那就是我想最初用一个简单的架构训练模型,一旦训练完成,我想添加几层并继续训练。可以在 Keras 中做到这一点吗?如果是这样,怎么做?

我尝试修改模型架构。但是在我编译之前,这些更改是无效的。编译后,所有权重都会重新初始化,并且会丢失所有经过训练的信息。

我在网络和 SO 中发现的所有问题要么是关于加载预训练模型并继续训练,要么是修改预训练模型的架构,然后仅对其进行测试。我没有找到与我的问题相关的任何内容。任何指针也非常感谢。

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

【问题讨论】:

    标签: python tensorflow keras pre-trained-model


    【解决方案1】:

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

    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 中保持不变)。

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

    【讨论】:

    • 谢谢。我会试试这个。只是一个疑问。最后调用compile时,不会重新初始化所有层的权重吗?
    • 不,不会。 thread 回答了您对 compile 实际作用的疑问。
    猜你喜欢
    • 2017-07-28
    • 2017-09-28
    • 2018-01-05
    • 1970-01-01
    • 2020-09-30
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多