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

TensorFlow 2.0加载自定义图像数据集时出现Input is empty错误

解决TensorFlow加载自定义图像数据集的Input is empty错误

问题场景

我尝试用TensorFlow 2.0加载自定义图像数据集,目录结构如下:

/PetImage
├── Cat
│   ├── img1.jpg
│   ├── img2.jpg
│   └── ...
└── Dog
    ├── img1.jpg
    ├── img2.jpg
    └── ...

使用代码:

img_height = 64
img_width = 64

ds_train = tf.keras.preprocessing.image_dataset_from_directory(
"I:\Image\Data\kagglecatsanddogs_5340\PetImages",
labels="inferred",
label_mode="int",
color_mode="rgb",
image_size=(img_height, img_width),
shuffle=True,
seed=123,
validation_split=0.3,
subset="training",
interpolation="bicubic"
)

history = model.fit(ds_train, epochs=2)

运行后触发错误:

InvalidArgumentError: Graph execution error:

Input is empty.
[[{{node decode_image/DecodeImage}}]]
[[IteratorGetNext]] [Op:__inference_train_function_1704]

解决方案

1. 修复路径转义问题

Windows路径中的单反斜杠\会被Python解析为转义字符,导致路径识别错误。将路径改为以下两种格式之一:

  • 使用双反斜杠:"I:\\Image\\Data\\kagglecatsanddogs_5340\\PetImages"
  • 使用原始字符串(前缀加r):r"I:\Image\Data\kagglecatsanddogs_5340\PetImages"

2. 清理损坏/空图像文件

Kaggle猫狗数据集存在部分大小为0或损坏的图片,这类文件会导致解码失败。可以用脚本批量检查并删除:

import os

data_dir = r"I:\Image\Data\kagglecatsanddogs_5340\PetImages"
for class_dir in os.listdir(data_dir):
    class_path = os.path.join(data_dir, class_dir)
    if not os.path.isdir(class_path):
        continue
    for img_file in os.listdir(class_path):
        img_path = os.path.join(class_path, img_file)
        if os.path.getsize(img_path) == 0:
            print(f"删除空文件: {img_path}")
            os.remove(img_path)

3. 验证目录结构合法性

确保PetImages根目录下仅包含Cat和Dog两个类别子目录,无其他无关文件或文件夹。image_dataset_from_directory要求每个子目录对应一个类别,且目录内仅存放该类别的图像文件。

4. 检查图像格式兼容性

部分图片可能扩展名与实际格式不符,或非标准JPG格式:

  • 尝试将color_mode改为"grayscale",排除RGB解码问题
  • 手动打开可疑图片,确认能正常显示,必要时重新保存为标准JPG格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:02