python - 如何将 keras image_dataset_from_directory 与自定义结构一起使用?

标签 python keras tensorflow-datasets

Keras image_dataset_from_directory里面preprocessing模块采用路径作为参数,并在这些图像存储在单独的子文件夹中时自动推断类。然而,就我而言,我有一个文件夹,然后在 DataFrame 中指定图像类。

.
├── datasets
│   ├── sample_submit.csv
│   ├── test_images
│   │   ├── test_0000.jpg
│   │   ├── test_0001.jpg
│   │   ├── test_0002.jpg
│   │   └── ...
│   ├── test_images.csv
│   ├── train_images
│   │   ├── train_0000.jpg
│   │   ├── train_0001.jpg
│   │   ├── train_0002.jpg
│   │   └── ...
│   └── train_images.csv
└── model.py

Tensorflow 的 documentation指定当您不推断标签时,必须指定一个列表或元组,这是我从 DataFrame df 获得的。但是,当我指定图像文件夹时,TensorFlow 返回 ValueError因为它没有找到图像:

In [1]: df = pd.read_csv('datasets/train_images.csv')
   ...: tds = keras.preprocessing\
   ...:    .image_dataset_from_directory('datasets/train_images', list(df['class']),
   ...:                                  validation_split=0.2, subset='training',
   ...:                                  seed=123, image_size(180, 180))

ValueError: Expected the lengths of `labels` to match the number of files in the target directory. len(labels) is 1102 while we found 0 files in datasets/train_images.

为什么keras无法识别文件夹中的图像?我尝试使用 ./datasets/train_images 设置“完整”相对路径,添加斜杠 datasets/train_images/还有绝对路径,无济于事。这里缺少什么?或者,在这种情况下是否有更有效的方法,我仍然可以获得训练/测试拆分?


编辑: keras 似乎有一个限制,而这个 question最初是这样阐述的,但仍然过于模糊,无法触及问题的核心。

简单明了:keras 似乎总是会抓取 directory 的子文件夹。图像参数并构建数据集。 启用图像加载的解决方法是包装一个附加文件夹 ( outer_train ) 并将其传递给 directory .

但是,我仍然对这种方法有问题,因为现在 keras 似乎无法采用作为列表传递的自定义类并输出 Found 1102 files belonging to 1 classes. (在本例中,是 now 子文件夹的名称 train_images ),因此仍然感谢任何帮助。

最佳答案

keras seems to always scrape the subfolders of the directory argument for images and build the dataset. The workaround to enable the loading of images is to wrap an additional folder (outer_train) and pass it to directory.

问题是 image_dataset_from_directory 方法询问包含其他目录的目录,并开始从您在输入中提供的目录中获取目录内的图像。

However, I still have problems with this approach, because now keras seems unable to take the custom classes passed as a list and outputs.

我认为你无法阅读这样的图像。如果您希望该方法读取自定义类的图像,那么您必须将包含自定义图像类的文件夹放入您要读取的文件夹中,如下所示:

  • 要读取的目录/

    • class__1/

      • img1

      • img2

    • class__2/

      • img1

      • img2

    • 自定义类/

      • img1

      • img2

关于python - 如何将 keras image_dataset_from_directory 与自定义结构一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66298147/

相关文章:

tensorflow - 使用 ResNet50 进行二元分类的恒定验证准确性

deep-learning - Keras 中的 Convolutional2D Siamese 网络

python - 使用自定义估算器控制纪元

python - 请求正文为空

python - 声明一个 SymPy 符号非零

python - 如何在Python中将.h5文件(Keras)上传到Azure Blob存储而不将其保存在磁盘中

tensorflow - 混洗 tfrecords 文件

python - 如何为我的 tensorflow 模型提高此数据管道的性能

python - 使用 Pandas resample 然后填充原始数据框

python - 如何在 python 3.7 中加密和解密字符串?