You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow训练无法保存最优模型及fit_generator弃用问题咨询

问题解决方法

1. 无法保存最优模型的问题

警告提示“仅在val-accuracy可用时才能保存最优模型”,核心问题有两个:

  • 你在ModelCheckpoint中设置的监控指标是val-accuracy,但TensorFlow里验证准确率的标准指标名是val_accuracy(下划线连接),拼写错误导致找不到对应指标。
  • 训练日志中没有输出任何验证指标,说明要么模型编译时未指定metrics=['accuracy'],要么validation_steps参数设置错误,导致验证数据未被完整处理。

解决步骤:

  • 将ModelCheckpoint的monitor参数修正为val_accuracy。
  • 确保模型编译时明确添加准确率指标,示例:
    model.compile(optimizer='adam', loss='你的损失函数', metrics=['accuracy'])
    
  • 移除validation_steps参数:当validation_data传入的是numpy数组时,TensorFlow会自动计算验证步数,手动设置可能导致验证数据未被完整处理,无法生成验证指标。

2. fit_generator弃用的问题

直接将Model.fit_generator替换为Model.fit即可,新版TensorFlow的fit方法完全支持生成器输入,用法和原方法一致。

修改后的完整代码

epochs = 100
train_datagen = ImageDataGenerator(
        rotation_range=15,
        fill_mode="nearest",
        horizontal_flip=True,
        zoom_range=0.2)

# 修正监控指标名
checkpointer = ModelCheckpoint(filepath="CDX_Best.h5", monitor='val_accuracy', save_best_only=True, verbose=1)
start = time.time()

# 替换fit_generator为fit
history = Model.fit(
    train_datagen.flow(X_train, y_train, batch_size=bs),
    steps_per_epoch=len(X_train)//bs,
    validation_data=(X_valid, y_valid),
    epochs=epochs,
    callbacks=[checkpointer]
)

end = time.time()
duration = end - start
print(f'\n This Model took {duration:.2f} seconds ({duration/60:.1f} minutes) to train for {epochs} epochs')

内容的提问来源于stack exchange,提问作者Hassan Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:15:40