【问题标题】:How to save final model using keras?如何使用 keras 保存最终模型?
【发布时间】:2022-01-11 05:53:16
【问题描述】:

我使用 KerasClassifier 来训练分类器。

代码如下:

import numpy
from pandas import read_csv
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load dataset
dataframe = read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:4].astype(float)
Y = dataset[:,4]
# encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
#print("encoded_Y")
#print(encoded_Y)
# convert integers to dummy variables (i.e. one hot encoded)
dummy_y = np_utils.to_categorical(encoded_Y)
#print("dummy_y")
#print(dummy_y)
# define baseline model
def baseline_model():
    # create model
    model = Sequential()
    model.add(Dense(4, input_dim=4, init='normal', activation='relu'))
    #model.add(Dense(4, init='normal', activation='relu'))
    model.add(Dense(3, init='normal', activation='softmax'))
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

    return model

estimator = KerasClassifier(build_fn=baseline_model, nb_epoch=200, batch_size=5, verbose=0)
#global_model = baseline_model()
kfold = KFold(n_splits=10, shuffle=True, random_state=seed)
results = cross_val_score(estimator, X, dummy_y, cv=kfold)
print("Accuracy: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))

但是如何保存最终模型以供未来预测?

我通常使用下面的代码来保存模型:

# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")

但是我不知道如何将保存模型的代码插入到 KerasClassifier 的代码中。

谢谢。

【问题讨论】:

    标签: python machine-learning keras


    【解决方案1】:

    模型有一个save 方法,它保存了重构模型所需的所有细节。来自keras documentation 的示例:

    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')
    

    【讨论】:

    • 对不起,我是说cross_val_score的最终权重。
    • 您是否尝试过将您的KerasClassifiercallbacks 关键字设置为一个列表,其单个项目是一个keras ModelCheckpoint 的实例?
    • 不,我不知道 ModelCheckpoint。能否详细说明一下。谢谢
    • 点击我评论中的链接了解详情。 ModelCheckpoint 回调用于在每个训练 epoch 之后保存模型(仅当验证错误减少时可选)。它可以保存多个文件或单个(覆盖)文件。
    • 执行上述代码行但在 load_model() 时显示此错误:ValueError: Cannot create group in read only mode.
    【解决方案2】:

    您可以将模型保存为 json 并将权重保存为 hdf5 文件格式。

    # keras library import  for Saving and loading model and weights
    
    from keras.models import model_from_json
    from keras.models import load_model
    
    # serialize model to JSON
    #  the keras model which is trained is defined as 'model' in this example
    model_json = model.to_json()
    
    
    with open("model_num.json", "w") as json_file:
        json_file.write(model_json)
    
    # serialize weights to HDF5
    model.save_weights("model_num.h5")
    

    文件“model_num.h5”和“model_num.json”被创建,其中包含我们的模型和权重

    要使用相同的训练模型进行进一步测试,您只需加载 hdf5 文件并将其用于不同数据的预测。 这是从保存的文件中加载模型的方法。

    # load json and create model
    json_file = open('model_num.json', 'r')
    
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    
    # load weights into new model
    loaded_model.load_weights("model_num.h5")
    print("Loaded model from disk")
    
    loaded_model.save('model_num.hdf5')
    loaded_model=load_model('model_num.hdf5')
    

    要预测不同的数据,您可以使用它

    loaded_model.predict_classes("your_test_data here")
    

    【讨论】:

    • 我尝试使用您的代码保存了模型,但在加载时出现此错误:ValueError: Unknown initializer: GlorotUniform。你能建议如何解决这个问题吗?
    • 感谢MMK的回复。但是我找到了我在下面的答案中解释过的解决方案。
    【解决方案3】:

    您可以使用model.save(filepath) 将 Keras 模型保存到单个 HDF5 文件中,该文件将包含:

    • 模型的架构,允许重新创建模型。
    • 模型的权重。
    • 训练配置(损失、优化器)
    • 优化器的状态,允许在您停止的地方恢复训练。

    在您的 Python 代码中,最后一行可能应该是:

    model.save("m.hdf5")
    

    这允许您将模型的全部状态保存在单个文件中。 保存的模型可以通过keras.models.load_model()重新实例化。

    load_model() 返回的模型是可以使用的已编译模型(除非保存的模型一开始从未编译过)。

    model.save() 参数:

    • filepath:字符串,保存权重的文件路径。
    • 覆盖:是静默覆盖目标位置的任何现有文件,还是为用户提供手动提示。
    • include_optimizer:如果为 True,则将优化器的状态一起保存。

    【讨论】:

      【解决方案4】:

      您可以通过这种方式保存模型并加载。

      from keras.models import Sequential, load_model
      from keras_contrib.losses import import crf_loss
      from keras_contrib.metrics import crf_viterbi_accuracy
      
      # To save model
      model.save('my_model_01.hdf5')
      
      # To load the model
      custom_objects={'CRF': CRF,'crf_loss':crf_loss,'crf_viterbi_accuracy':crf_viterbi_accuracy}
      
      # To load a persisted model that uses the CRF layer 
      model1 = load_model("/home/abc/my_model_01.hdf5", custom_objects = custom_objects)
      

      【讨论】:

        【解决方案5】:

        一般情况下,我们通过调用save()函数将模型和权重保存在同一个文件中。

        为了节省,

        model.compile(optimizer='adam',
                      loss = 'categorical_crossentropy',
                      metrics = ["accuracy"])
        
        model.fit(X_train, Y_train,
                 batch_size = 32,
                 epochs= 10,
                 verbose = 2, 
                 validation_data=(X_test, Y_test))
        
        #here I have use filename as "my_model", you can choose whatever you want to.
        
        model.save("my_model.h5") #using h5 extension
        print("model saved!!!")
        

        为了加载模型,

        from keras.models import load_model
        
        model = load_model('my_model.h5')
        model.summary()
        

        在这种情况下,我们可以简单地保存和加载模型,而无需再次重新编译我们的模型。 注意 - 这是保存和加载 Keras 模型的首选方式。

        【讨论】:

          【解决方案6】:

          您可以使用keras.callbacks.ModelCheckpoint()保存最佳模型

          例子:

          model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
          model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
          history = model.fit(x_train,y_train,
                    epochs=10,
                    validation_data=(x_valid,y_valid),
                    callbacks=[model_checkpoint_callback])
          

          这会将最佳模型保存在您的工作目录中。

          【讨论】:

            【解决方案7】:

            保存 Keras 模型:

            model = ...  # Get model (Sequential, Functional Model, or Model subclass)
            model.save('path/to/location')
            

            重新加载模型:

            from tensorflow import keras
            model = keras.models.load_model('path/to/location')
            

            欲了解更多信息,请阅读Documentation

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2018-06-25
              • 2018-08-02
              • 2018-12-14
              • 2018-05-02
              • 1970-01-01
              • 2022-07-25
              相关资源
              最近更新 更多