如何仅在验证准确率提高时保存/覆盖我的TensorFlow/Keras模型?

关于保存模型的资料已经有很多了,但我一直在努力弄清楚如何仅在我模型的val_accuracy有所提高时保存它。我的模型如下所示:

model = keras.Sequential([    keras.layers.Embedding(numberOfWords,                           embedding_vector_length, input_length=1000),    keras.layers.LSTM(128),    keras.layers.Dropout(0.3),    keras.layers.Dense(128, activation='relu'),    keras.layers.Dropout(0.3),    keras.layers.Dense(64, activation='relu'),    keras.layers.Dropout(0.3),    keras.layers.Dense(1, activation='sigmoid')])model.compile(optimizer=tf.keras.optimizers.Adam(lr=1e-3, decay=1e-5), loss='binary_crossentropy',              metrics=['accuracy'])model.fit(x_train, y_train, epochs=200, batch_size=32,          validation_data=(x_test, y_test))

在训练过程中,我希望在第一个epoch之后保存模型。然后,在每个epoch之后,如果val_accuracy有所提高,我希望用新的模型覆盖旧模型。

我该如何做到这一点?


回答:

你只需要定义一个回调列表,并将其输入到model.fit声明中:Keras_fit 在这个例子中,它只是保存最佳权重,所以实际上是覆盖旧的权重,并将其保存为hdf5格式。希望这能解决你的问题 🙂

from keras.callbacks import ModelCheckpointfilepath="weights.best.hdf5"checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1,save_best_only=True, mode='max')callbacks_list = [checkpoint]model.fit(x_train, y_train, epochs=200,,callbacks=callbacks_list, batch_size=32,          validation_data=(x_test, y_test))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注