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

在Kaggle Notebook中使用ModelCheckpoint训练Keras模型时遇空日志错误

Keras多标签分类训练中ModelCheckpoint回调报错解决建议

核心代码

from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, BatchNormalization
from keras.callbacks import TensorBoard
from keras.callbacks import ModelCheckpoint
from keras.optimizers import AdamW

epochs = 4
loss = tf.keras.losses.BinaryCrossentropy(from_logits=False)
classifier_model.compile(optimizer='adam',
                         loss=loss,
                         metrics = 'roc-auc')

print(f'Training model with {tfhub_handle_encoder}')
checkpoint_filepath = '/kaggle/working/tmp_weights.h5'

model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_weights_only=True,
    monitor='val_loss',
    mode='min',
    save_best_only=True)

history = classifier_model.fit(x=train_ds,
                               validation_data=val_ds,
                               epochs=epochs,
                               callbacks = [model_checkpoint_callback])

报错信息

ValueError: Unexpected result of `train_function` (Empty logs). This could be due to issues in input pipeline that resulted in an empty dataset. Otherwise, please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

补充背景

  • 使用TensorFlow Hub编码器(tfhub_handle_encoder)实现文本嵌入
  • train_ds和val_ds为训练/验证数据集,格式为<_TakeDataset element_spec=(TensorSpec(shape=(None,), dtype=tf.string, name=None), TensorSpec(shape=(None, 6), dtype=tf.int64, name=None))>
  • 已验证数据加载与预处理步骤正确,数据集非空

解决建议

  • 启用Eager Execution排查细节:在模型编译时添加run_eagerly=True参数,强制模型逐行执行训练步骤,能捕捉到导致日志为空的具体错误(如张量形状不匹配、loss计算失败等)。修改后的编译代码:
    classifier_model.compile(optimizer='adam',
                             loss=loss,
                             metrics='roc-auc',
                             run_eagerly=True)
    
  • 验证模型输出与标签的形状匹配:多标签分类任务中,模型最后一层需使用sigmoid激活函数,输出形状需与标签的(None,6)对应。若模型输出维度错误,会导致loss计算中断,无日志返回。
  • 调整监控指标配置:确认roc-auc指标适配多标签场景,建议显式指定多标签兼容的AUC指标:
    metrics = [tf.keras.metrics.AUC(multi_label=True, name='roc-auc')]
    classifier_model.compile(optimizer='adam', loss=loss, metrics=metrics)
    
  • 检查验证数据集的批次有效性:即使数据集非空,若val_ds的batch_size设置过大,可能导致最后一批数据为空。可通过val_ds.take(1)打印验证集第一个批次的张量形状,确认数据是否正常输出。
  • 简化Checkpoint路径:尝试将checkpoint_filepath改为相对路径(如./best_weights.h5),排除Kaggle工作目录的权限或缓存问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:32:10