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

运行TensorFlow fit函数时Jupyter Notebook内核持续崩溃如何解决

问题诱因
  • 废弃API兼容问题:TensorFlow 2.1及之后版本已经正式废弃fit_generator接口,虽然保留了兼容逻辑但存在大量已知稳定性问题,在2.6版本中调用很容易触发内核崩溃。
  • 回调指标不匹配:ReduceLROnPlateau回调监控val_acc,EarlyStopping回调监控val_categorical_accuracy,如果模型编译时metrics参数没有同时配置这两个指标,会出现指标找不到的底层报错,直接导致内核终止。
  • 资源溢出:batch_size设置过大、数据集生成器输出维度和模型输入不匹配,都会导致显存/内存瞬间占满,触发Jupyter内核强制重启。
  • 依赖版本不兼容:TensorFlow 2.6对依赖库的版本要求严格,若numpy、pandas等数值库版本超出适配范围,会触发底层运算库的冲突导致崩溃。
  • steps参数非法:如果train_batches.n或val_batches.n小于batch_size,整除得到的steps_per_epoch或validation_steps为0,接口接收到非法参数会直接崩溃。
解决方法
  • 替换废弃API,将fit_generator改为原生fit接口,TensorFlow 2.x的fit原生支持生成器输入,参数无需额外调整:
history = model.fit(generator = train_batches, steps_per_epoch = train_batches.n//batch_size, epochs=epochs, 
                    validation_data = val_batches, validation_steps = val_batches.n//batch_size, verbose = 0,
                    callbacks = [learning_rate_reduction, es])
  • 统一回调监控指标,和模型编译时的metrics配置保持一致。例如编译时设置metrics=['categorical_accuracy'],则两个回调都修改为监控val_categorical_accuracy:
learning_rate_reduction = ReduceLROnPlateau(monitor = 'val_categorical_accuracy', patience = 3, verbose = 1, factor = .5, min_lr = .00001)
  • 限制显存占用避免溢出,添加TensorFlow显存动态分配配置,同时将batch_size调小到8、16等小数值测试:
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
    try:
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)
    except RuntimeError as e:
        print(e)
  • 校准依赖版本,安装TensorFlow 2.6适配的依赖库版本:
pip install numpy==1.21.6 pandas==1.3.5
  • 校验steps参数合法性,先打印train_batches.n和batch_size的数值,确保整除结果大于0。如果数据集样本量过小,可删除steps_per_epoch和validation_steps参数,由TensorFlow自动计算步长。
  • 解决CPU运算库冲突,原有KMP配置基础上增加MKL禁用配置,避免Intel运算库和非Intel硬件的兼容问题:
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
os.environ['TF_DISABLE_MKL'] = '1'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:27:03