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

Keras使用ImageDataGenerator生成验证集时报cannot identify image file错误

问题排查与解决方案

cannot identify image file <_io.BytesIO object at 0x7fd2278943b0> 报错是图像加载库PIL/Pillow在读取图片时,无法识别输入的文件为有效图像格式。你的代码本身逻辑没有明显语法错误,问题主要来源于数据集文件或参数适配,可按以下步骤逐一排查:

  • 排查损坏/无效的图片文件
    你设置的validation_split=0.2会从指定PATH目录下随机划分20%数据作为验证集,首先需要过滤PATH下所有异常文件,可运行以下简易脚本批量检测:
import os
from PIL import Image

img_extensions = ['.jpg', '.jpeg', '.png', '.bmp']
invalid_files = []

for root, dirs, files in os.walk(PATH):
    for file in files:
        ext = os.path.splitext(file)[-1].lower()
        if ext in img_extensions:
            try:
                img = Image.open(os.path.join(root, file))
                img.verify()
            except Exception as e:
                invalid_files.append(os.path.join(root, file))
        else:
            # 非图片后缀文件直接加入异常列表
            invalid_files.append(os.path.join(root, file))

print("异常文件列表:", invalid_files)

检测出的异常文件可直接移除,避免被加载。

  • 确认数据集目录结构符合要求
    flow_from_directory要求数据路径PATH下的结构必须为:每个类别对应一个独立子文件夹,所有图片直接存放在对应类别子目录中,禁止在类别目录下存放txt、压缩包、系统缓存文件(如Mac的.DS_Store)等非图片文件。
  • 适配训练方法的参数
    你使用的fit_generator、samples_per_epoch、nb_epoch都是Keras 2.2之前的旧版API,如果你使用的是TensorFlow 2.x配套的Keras版本,参数不兼容也可能触发数据加载异常,可修改为新版写法:
model.fit(
    train_dataset,
    steps_per_epoch=100,
    epochs=10,
    validation_data=validation_dataset
)
  • 单独验证验证集加载逻辑
    运行validation_dataset.next()手动触发一批验证集数据加载,如果该命令直接报错,即可完全确认问题出在验证集的文件本身,和模型训练逻辑无关。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:54:01