如何为ImageDataGenerator中生成的样本指定标签

时间:2018-04-30 17:09:51

标签: python keras classification conv-neural-network

我是Convolutional Neural Networks的新手,我即将建立我的第一个ConvNet,它是一个多级图像分类ConvNet。

型号说明

假设我有两个图像文件夹,一个包含几千个特定类型叶子的图像(叶子A)(图像集X),其他文件夹包含相同类型叶子的相同数量的图像(叶子B)(图像集Y)。所以我需要训练我的模型以区分这两种类型。

问题背景

由于我有两类输出叶A和叶B,我有0,1作为输出或1,0作为叶A类或叶B类的给定图像的输出。

                            Leaves A | Leaves B
If Input is a Class A Leaf,     1         0
If Input is a Class B Leaf,     0         1

问题

所以为了做到这一点,我必须将我的图像集X标记为输出1,0而图像集Y标记为输出0,1。此外,由于我需要增加图像以获得更多训练样本,因此我使用了ImageDataGenerator。

training_imGen.flow_from_directory(
                                'path/to/image_folder_X',
                                target_size=(1100,180),
                                batch_size=batchSize,
                                color_mode='rgb',
                                class_mode='categorical'
                                )

但在这里我无法指定标签。不像我使用training_imGen.flow时那样。但是我发现classes参数可以在flow_from_directory下调用,

classes: optional list of class subdirectories (e.g. ['dogs', 'cats']). Default: None. If not provided, the list of classes will be automatically inferred from the subdirectory names/structure under directory, where each subdirectory will be treated as a different class (and the order of the classes, which will map to the label indices, will be alphanumeric).

但我不知道如何在那里指定两个类标签,因为我只提供image set X文件夹的路径。任何想法如何做到这一点?

更新

training_imGen.flow_from_directory(
                                '/Users/user/database/',
                                target_size=(1100,180),                                                 
                                batch_size=batchSize,
                                color_mode='rgb',
                                class_mode='categorical',
                                classes=['Set_A', 'Set_B']
                                )

/Users/user/database/路径下,有两个名为Set_ASet_B的文件夹。正如我所提到的,每个文件夹都包含相关的png图像文件。

1 个答案:

答案 0 :(得分:1)

查看DirectoryIterator的实施方式。这是一个非常简单的课程。

DirectoryIterator只是DirectoryIterator对象构造的包装器。您不必手动指定标签,因为A会自动假设每个样本都与该样本的父文件夹后面的类相关联。 因此,只要叶子A的所有样本都位于名为B的同一文件夹中,并且叶子class_mode的样本位于不同的文件夹中,它们就会被正确分配到各自的类中。

此外,迭代器的输出已经是单热编码,因为您将categorical定义为g = ImageDataGenerator() train = g.flow_from_directory('/path/to/dataset/train/', batch_size=32, target_size=(1100, 180)) x_batch, y_batch = next(train) assert x_batch.shape == (32, 1100, 180, 3) assert y_batch.shape == (32, 2) print(y_batch) [[0. 1.], [1. 0.], [1. 0.], ... [0. 1.]]

classes

directory参数不用于设置每个样本的标签,而是指定['A', 'B']的子文件夹列表,该子文件夹应被该迭代器视为类(例如{{ 1}})。如果保留默认None,则directory的所有子文件夹都被视为有效类,其中的所有图像都是该集合的潜在样本。当您只想使用标签子集,调试代码或延迟类时,这非常有用。

如果您希望覆盖默认标签,则可以简单地替换DirectoryIterator#classes中的内容,其中包含与ith元素ith元素相关联的类。例如,我们假设您要添加第三类没有关联文件夹的树叶:

train = g.flow_from_directory(...)
train.classes = np.asarray([0., 1., 2., ..., 0., 1.])
train.class_indices = {'A': 0, 'B': 1, 'C': 2}
train.num_classes = 3
相关问题