gpt4 book ai didi

python - fit_generator() 以最小的验证损失保存模型

转载 作者:行者123 更新时间:2023-11-28 21:02:35 26 4
gpt4 key购买 nike

我如何使用 keras 函数 fit_generator() 训练并同时保存具有最低验证损失的模型权重?

最佳答案

您可以在定义检查点时设置save_best_only=True:

from keras.callbacks import EarlyStopping, ModelCheckpoint

early_stop = EarlyStopping(
monitor='loss',
min_delta=0.001,
patience=3,
mode='min',
verbose=1
)
checkpoint = ModelCheckpoint(
'model_best_weights.h5',
monitor='loss',
verbose=1,
save_best_only=True,
mode='min',
period=1
)

现在拟合模型时只需包含参数 callbacks = [early_stop,checkpoint]。它将保存具有最低验证损失的权重。

model.fit_generator(X_train, Y_train, validation_data=(X_val, Y_val), 
callbacks = [early_stop,checkpoint])

保存模型架构

如果您也想保存模型架构,则需要将模型序列化为 JSON:

model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)

最后用架构和权重加载模型:

# 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_best_weights.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)

请引用:https://machinelearningmastery.com/save-load-keras-deep-learning-models/

关于python - fit_generator() 以最小的验证损失保存模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com