Keras中model.fit()调用报错求助:索引越界与数据适配器问题
Keras模型训练报错问题解决
问题场景
运行以下Keras训练代码时出现错误,同时调用model_final.fit()也失败,出现两类错误:ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>和“Tuple index out of range”。
训练代码
history = model.fit( train_dir, steps_per_epoch = 100, epochs = 10, validation_data = test_dir, validation_steps = 100, verbose = 1, callbacks = [callbacks] )
报错信息
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-45-bbb0a6f8a6e5> in <module> ----> 1 history = model.fit() 2 1 frames /usr/local/lib/python3.8/dist-packages/keras/engine/data_adapter.py in select_data_adapter(x, y) 983 if not adapter_cls: 984 # TODO(scottzhu): This should be a less implementation-specific error. --> 985 raise ValueError( 986 "Failed to find data adapter that can handle " 987 "input: {}, {}".format( ValueError: Failed to find data adapter that can handle input: <class 'NoneType'>, <class 'NoneType'>
错误原因
- 空参数调用
fit():从报错栈可见,实际执行的是无参数的model.fit(),Keras无法获取训练数据(x和y均为None),直接触发数据适配器错误。 - 原始目录路径无法直接作为输入:Keras的
fit()方法不能直接接收字符串格式的文件夹路径,必须传入预处理后的数据集(如tf.data.Dataset或生成器),否则无法解析数据,进而引发元组索引越界的连锁错误。 - 回调参数存在风险:
callbacks = [callbacks]的写法可能引发变量名冲突或未初始化问题,如果callbacks变量未定义,会传入无效的回调列表干扰训练。
解决方法
- 确保调用
fit()时传入有效预处理数据:
以图像分类任务为例,用tf.keras.utils.image_dataset_from_directory加载文件夹数据:import tensorflow as tf # 加载训练和测试数据集 train_ds = tf.keras.utils.image_dataset_from_directory( train_dir, image_size=(224, 224), # 根据你的模型输入尺寸调整 batch_size=32) test_ds = tf.keras.utils.image_dataset_from_directory( test_dir, image_size=(224, 224), batch_size=32) # 调用fit训练模型 history = model.fit( train_ds, epochs=10, validation_data=test_ds, verbose=1, callbacks=[tf.keras.callbacks.EarlyStopping(patience=3)] # 示例回调,按需替换 ) - 检查执行代码:确认运行的是带完整参数的
model.fit()调用,而非无参数版本。 - 修正回调参数:避免
callbacks = [callbacks]的写法,提前定义好回调列表,比如:
再将my_callbacks = [ tf.keras.callbacks.EarlyStopping(patience=3), tf.keras.callbacks.ModelCheckpoint(filepath='model.h5') ]callbacks=my_callbacks传入fit()。 - 排查数据格式:确保数据集每个批次返回
(特征数据, 标签数据)的二元组,不符合格式会触发元组索引越界错误。
内容的提问来源于stack exchange,提问作者98 Yoga
相关产品推荐
相关产品推荐

