如何继续训练已保存然后加载的Keras模型?

时间:2017-07-31 20:25:06

标签: deep-learning keras

official keras documentation之后,我能够保存并加载模型。 Keras使用tensorflow作为后端。

但是,是否可以对此类已保存和加载的模型进行更多培训。

以下是从Link借来的代码。然后编辑。

在下面的代码中,模型训练了75个纪元并保存然后再次加载。

然而,当我尝试用更多75个时期进一步训练它时,似乎模型没有经过训练,我得到的结果没有任何修改。

# -*- coding: utf-8 -*-

from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
import numpy
import os
# fix random seed for reproducibility
numpy.random.seed(7)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.txt", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(8, kernel_initializer='uniform', activation='relu'))
model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X, Y, epochs=75, batch_size=10, verbose=0)
# evaluate the model
scores = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*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")

# later...

# load json and create model
json_file = open('model.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.h5")
print("Loaded model from disk")

# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))


model.fit(X, Y, epochs=75, batch_size=10, verbose=0)
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

1 个答案:

答案 0 :(得分:0)

从您的代码看起来您​​评估loaded_model两次,但您的额外培训仅在model完成。你可以尝试这样的东西,而不是复制和粘贴不同的变量名称...我发现它更容易跟踪。此外,在评论之间为代码添加一些空格,这将有助于保持清晰和有条理。

# Save a model you have trained
model.save('trained_model.h5')

# Delete the model
del model

# Load the model
model = load_model('trained_model.h5')

# Train more on the loaded model
model.fit(data, labels, epochs, batch_size)