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

使用CNN-VGG16调用fit_generator时遇ValueError错误求助

解决ValueError: Failed to find data adapter...问题

核心原因

  • validation_data为无效值:你的testdata变量未生成有效的数据迭代器,实际传入了None,和训练数据类型不匹配。
  • 使用废弃API:TensorFlow 2.x版本的Keras中,fit_generator已被弃用,直接用model.fit()即可兼容数据生成器。
  • 数据生成器未正确实例化:ImageDataGenerator只是数据增强配置类,必须调用flow()/flow_from_directory()等方法生成可迭代的数据对象,不能直接传入类本身。

具体修复步骤

1. 生成有效的训练/测试数据迭代器

如果你的数据是按文件夹分类存储,用flow_from_directory生成迭代器:

from keras.preprocessing.image import ImageDataGenerator

# 初始化数据增强配置
train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)

# 生成训练数据迭代器
traindata = train_datagen.flow_from_directory(
    "你的训练集文件夹路径",
    target_size=(224, 224),  # VGG16标准输入尺寸
    batch_size=32,
    class_mode="categorical"  # 多分类用categorical,二分类用binary
)

# 生成测试数据迭代器
testdata = test_datagen.flow_from_directory(
    "你的测试集文件夹路径",
    target_size=(224, 224),
    batch_size=32,
    class_mode="categorical"
)

如果是numpy数组格式的数据,用flow()方法:

traindata = train_datagen.flow(x_train, y_train, batch_size=32)
testdata = test_datagen.flow(x_test, y_test, batch_size=32)

2. 替换fit_generator为fit()

TensorFlow 2.x的fit()原生支持数据生成器,修改训练代码:

from keras.callbacks import ModelCheckpoint, EarlyStopping

checkpoint = ModelCheckpoint("vgg16_1.h5", monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=False, mode='auto')
early = EarlyStopping(monitor='val_accuracy', min_delta=0, patience=20, verbose=1, mode='auto')

# 使用fit替代废弃的fit_generator
hist = model.fit(
    traindata,
    steps_per_epoch=100,
    validation_data=testdata,
    validation_steps=10,
    epochs=100,
    callbacks=[checkpoint, early]
)

注意:新版本Keras中指标名称为val_accuracy,旧版本可保留val_acc,建议统一用val_accuracy避免兼容问题。

3. 检查变量有效性

确认testdata未被误赋值为None:比如测试集路径错误、文件夹结构不符合要求(如测试集文件夹下无对应类别的子文件夹),都会导致生成器返回无效对象,需核对路径和文件夹结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:27:25