Python 如何使用keras保存最终模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42763094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:08:01  来源:igfitidea点击:

How to save final model using keras?

pythonmachine-learningkeras

提问by yensheng

I use KerasClassifier to train the classifier.

我使用 KerasClassifier 来训练分类器。

The code is below:

代码如下:

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

But How to save the final model for future prediction?

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

I usually use below code to save model:

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

# 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")

But I don't know how to insert the saving model's code into KerasClassifier's code.

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

Thank you.

谢谢你。

回答by bogatron

The model has a savemethod, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

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

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

回答by MMK

you can save the model in jsonand weights in a hdf5file format.

您可以将模型保存为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")

files "model_num.h5" and "model_num.json" are created which contain our model and weights

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

To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

要使用相同的训练模型进行进一步测试,您只需加载 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')

To predict for different data you can use this

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

loaded_model.predict_classes("your_test_data here")

回答by prosti

You can use model.save(filepath)to save a Keras model into a single HDF5 file which will contain:

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

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.
  • 模型的架构,允许重新创建模型。
  • 模型的权重。
  • 训练配置(损失,优化器)
  • 优化器的状态,允许从您停止的地方恢复训练。

In your Python code probable the last line should be:

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

model.save("m.hdf5")

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model().

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

The model returned by load_model()is a compiled model ready to be used (unless the saved model was never compiled in the first place).

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

model.save()arguments:

model.save()论据:

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer's state together.
  • filepath:字符串,保存权重的文件路径。
  • 覆盖:是否静默覆盖目标位置的任何现有文件,或向用户提供手动提示。
  • include_optimizer:如果为True,则一起保存优化器的状态。

回答by TRINADH NAGUBADI

you can save the model and load in this way.

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

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)

回答by Aashish Mamgain

Generally, we save model and weights in same file by calling save() function.

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

For Saving,

为了节省,

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 save!!!")

For Loading the model,

对于加载模型,

from keras.models import load_model

model = load_model('my_model.h5')
model.summary()

In this case, we can simply save and load the model without re-compiling our model again. Note - This is the preferred way for saving and loading your Keras model.

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