当准确度和召回率都更好时,如何保存keras模型



使用python 3.7tensorflow 2.1.0,我想知道如何在精度和召回率都更好的情况下保存最佳模型。

以下代码提供了一些元素,以便在只有精度更好的情况下保存最佳模型。

# some dependencies
from tensorflow.keras.metrics import Precision, Recall
# some coding instructions to define ImageDataGenerator flows.
metrics = {"precision":Precision(name="precision"), "recall":Recall(name="recall")}
checkpoints = {
"precision" : ModelCheckpoint(
"./models/best.h5",
mode="max",
monitor="val_precision",
save_freq="epoch",
save_weights_only=False,
save_best_only=True,
verbose=1
)
}
callbacks = list(checkpoints.values())
model = Sequential()
# neural network architecture ...
model.compile(
loss="binary_crossentropy",
optimizer='adam',
metrics=[metric for metric in metrics.values()]
)
model.fit_generator(train_generator,
validation_data = val_generator,
steps_per_epoch = train_generator.n//train_generator.batch_size,
validation_steps = val_generator.n//val_generator.batch_size,
class_weight={0:0.75, 1:1.5},
callbacks=callbacks,
epochs=300)

我不认为为召回添加回调将使我能够为这两个指标保存最佳模型。。。在我看来,如果回忆比上一个时期计算的回忆更好,即使精度越来越差,模型也会被保存。。。精度也是如此。我认为这种代码只会给我们一种";OR";逻辑而不是"逻辑";"与";思维方式

也许我错了。。。有人能帮我吗?如有任何帮助,我们将不胜感激。欢迎解释!

我想出了一个解决方案,希望它能帮助一些人。

class CustomCallback(tf.keras.callbacks.Callback):
def __init__(self, model, path, metrics):
self.model = model
self.path = path
self.metrics = metrics
self.history = []
def on_epoch_end(self, epoch, logs):
if self.history:
last_logs = self.history[-1]
last_metrics_values = {metric : last_logs[metric] for metric in self.metrics}
current_metrics_values = {metric : logs[metric] for metric in self.metrics}
checking = [last_metrics_values[metric] < current_metrics_values[metric] for metric in self.metrics]
decision = reduce(operator.and_, checking)
if decision:
print("nModel performs better at current epoch for all monitored metrics : ", self.metrics)
print("nSaving current model in ", self.path)
self.model.save(self.path)
else:
print("nSaving model at first epoch for initialization purpose")
self.model.save(self.path)
self.history.append(logs)

您可以更改代码,使其具有更复杂的逻辑来决定何时保存模型以及什么是最适合您的模型。使用CCD_ 3和CCD_。您必须具有以下依赖项:

from functools import reduce
import operator
import tensorflow as tf

最新更新