首页 > 解决方案 > Keras flow_from_directory 自动编码器训练

问题描述

我正在尝试在 Keras 中训练一个自动编码器,我自己的数据集组织如下:

我已经了解了如何将 flow_from_directory 用于分类任务,其中数据集被组织在标签和子目录中。在这种情况下,所有图像都在同一个文件夹中,没有任何标签。执行代码时,出现以下错误:“找到属于 0 个类的 0 个图像。”

这是我的代码片段:

train_path = 'dataset/train/'
train_gen = train_data_gen.flow_from_directory(
    train_path,
    class_mode = 'Input',
    target_size = IMAGE_SIZE,
    color_mode = 'grayscale',
    batch_size = BS,
    seed = SEED,
    shuffle = 'Yes'
)

我该如何解决?

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


问题在于数据的结构。当您将 flow_from_directory 与目录作为 train_path = 'dataset/train/' 一起使用时,它会在该目录中查找将是您的类的子目录。从您显示的目录结构来看, dataset/train 中没有类子目录,因此生成器不返回文件和类。例如,假设您正在构建一个分类器来对狗和猫进行分类。在您的训练目录中,您将有两个子目录,一个用于保存猫的图像,另一个用于保存狗的图像。flow_from_directory 有一个参数 class_mode,描述如下

class_mode: One of "categorical", "binary", "sparse", "input", or None.
 Default: "categorical". Determines the type of label arrays that are
 returned: - "categorical" will be 2D one-hot encoded labels, - "binary" 
will be 1D binary labels, "sparse" will be 1D integer labels,
 - "input" will be images identical to input images (mainly used to 
work with autoencoders). - If None, no labels are returned 
(the generator will only yield batches of image data, 
which is useful to use with model.predict()). 
Please note that in case of class_mode None,
 the data still needs to reside in a subdirectory of directory for it to work correctly.

所以在 flow_from_directory 中设置 class_mode='input'。这样你就可以得到没有任何标签的图像。


推荐阅读