【发布时间】:2021-11-28 22:17:58
【问题描述】:
我正在使用 keras 构建用于图像分类的 CNN 模型。我无法使用 ModelCheckPoint 保存最佳模型,因为它会引发此警告:
警告:tensorflow:只能使用 val_accuracy 保存最佳模型 可用,跳过。
我已经针对所有相关问题研究了 stackoverflow,但到目前为止还没有任何效果。 [1][2][3][4]等等
这是我的代码:
model.compile(loss='categorical_crossentropy',metrics=['accuracy', Precision(), Recall()],optimizer='adam')
train_datagen = ImageDataGenerator(rescale = 1/255.,
rotation_range =40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range =0.2,
horizontal_flip=True,
fill_mode ='nearest')
test_datagen = ImageDataGenerator(rescale = 1/255.)
train_generator = train_datagen.flow_from_directory(r"./datasetcrop512/train", target_size=(512,512), batch_size=32, class_mode='categorical')
test_generator = test_datagen.flow_from_directory(r"./datasetcrop512/test", target_size=(512,512), batch_size=32, class_mode='categorical')
增强后,模型检查点
from keras.callbacks import ModelCheckpoint
filepath = 'weights_best_model3_6.hdf5'
checkpoint = ModelCheckpoint(filepath,monitor = 'val_accuracy',verbose = 1, save_best_only=True, mode='max')
拟合模型
history = model.fit(train_generator, steps_per_epoch = stepsPerEpoch,
epochs = 15, validation_data=test_generator, validation_steps = stepsPerEpoch,
callbacks = [ PlotLossesKeras(),checkpoint])
运行后,计算第 1 个 epoch 的验证准确度,但从第 2 个 epoch 开始,它开始给出上述警告并且不保存最佳模型。
【问题讨论】:
-
我记得之前看到过类似的问题,这是由于在验证数据不是
tf.data.Dataset类型时使用validation_steps,您可以尝试删除validation_steps参数并重试吗? -
@aim97 嘿,这确实有效:D 我会再测试 2-3 次,如果它一直有效,请告诉您。
-
@aim97 请将解决方案作为答案发布,以便 OP 可以接受并对其他人有用
标签: python tensorflow keras deep-learning conv-neural-network