我使用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的代码中。
谢谢。
答案 0 :(得分:52)
该模型具有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')
答案 1 :(得分:14)
您可以将模型保存在 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")
答案 2 :(得分:6)
通常,我们通过调用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模型的首选方法。
答案 3 :(得分:4)
您可以使用model.save(filepath)
将Keras模型保存到单个HDF5文件中,该文件将包含:
在您的Python代码中,最后一行应该是:
model.save("m.hdf5")
这使您可以将模型的整个状态保存在单个文件中。
可以通过keras.models.load_model()
重新实例化保存的模型。
load_model()
返回的模型是已准备好可以使用的已编译模型(除非从不首先编译保存的模型)。
model.save()
参数:
答案 4 :(得分:2)
您可以通过这种方式保存模型并加载。
from keras.models import Sequential
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 :(得分:1)
保存 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
答案 6 :(得分:0)
您可以使用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])
这会将最佳模型保存在您的工作目录中。