• 如何保存Keras模型


    我们不推荐使用pickle或cPickle来保存Keras模型

    你可以使用model.save(filepath)将Keras模型和权重保存在一个HDF5文件中,该文件将包含:

    • 模型的结构,以便重构该模型
    • 模型的权重
    • 训练配置(损失函数,优化器等)
    • 优化器的状态,以便于从上次训练中断的地方开始

    使用keras.models.load_model(filepath)来重新实例化你的模型,如果文件中存储了训练配置的话,该函数还会同时完成模型的编译

    例子:

    from keras.models import load_model
    
    model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
    del model  # deletes the existing model
    
    # returns a compiled model
    # identical to the previous one
    model = load_model('my_model.h5')
    

    如果你只是希望保存模型的结构,而不包含其权重或配置信息,可以使用:

    # save as JSON
    json_string = model.to_json()
    
    # save as YAML
    yaml_string = model.to_yaml()
    

    这项操作将把模型序列化为json或yaml文件,这些文件对人而言也是友好的,如果需要的话你甚至可以手动打开这些文件并进行编辑。

    当然,你也可以从保存好的json文件或yaml文件中载入模型:

    # model reconstruction from JSON:
    from keras.models import model_from_json
    model = model_from_json(json_string)
    
    # model reconstruction from YAML
    model = model_from_yaml(yaml_string)
    

    如果需要保存模型的权重,可通过下面的代码利用HDF5进行保存。注意,在使用前需要确保你已安装了HDF5和其Python库h5py

    model.save_weights('my_model_weights.h5')
    

    如果你需要在代码中初始化一个完全相同的模型,请使用:

    model.load_weights('my_model_weights.h5')
    

    如果你需要加载权重到不同的网络结构(有些层一样)中,例如fine-tune或transfer-learning,你可以通过层名字来加载模型:

    model.load_weights('my_model_weights.h5', by_name=True)
    

    例如:

    """
    假如原模型为:
        model = Sequential()
        model.add(Dense(2, input_dim=3, name="dense_1"))
        model.add(Dense(3, name="dense_2"))
        ...
        model.save_weights(fname)
    """
    # new model
    model = Sequential()
    model.add(Dense(2, input_dim=3, name="dense_1"))  # will be loaded
    model.add(Dense(10, name="new_dense"))  # will not be loaded
    
    # load weights from first model; will only affect the first layer, dense_1.
    model.load_weights(fname, by_name=True)
    
    
  • 相关阅读:
    java实现三角螺旋阵
    java实现人员排日程
    java实现人员排日程
    java实现人员排日程
    java实现人员排日程
    java实现人员排日程
    java实现人民币金额大写
    为什么使用剪切板时都用GlobalAlloc分配内存(历史遗留问题,其实没关系了)
    深入解析Windows窗口创建和消息分发(三个核心问题:怎么将不同的窗口过程勾到一起,将不同的hwnd消息分发给对应的CWnd类去处理,CWnd如何简单有效的去处理消息,由浅入深,非常清楚) good
    Delphi中array of const应用
  • 原文地址:https://www.cnblogs.com/antflow/p/7306383.html
Copyright © 2020-2023  润新知