2016-06-23 136 views
9

我使用flow_from_directory得到训练,从一个文件夹设置的结构如下:如何在Keras培训多个班时获得标签ID?

train 
    class1 
    class2 
    class3 
    ... 

发电机被称为是如下:

train_generator = train_datagen.flow_from_directory( 
     train_data_dir,        
     target_size=(img_height, img_width),   
     batch_size=32,        
     class_mode='categorical') 

我没有设置参数classes,但我期望按字母顺序获取标签。

classes: optional list of class subdirectories (e.g. ['dogs', 'cats']). Default: None. If not provided, the list of classes will be automatically inferred (and the order of the classes, which will map to the label indices, will be alphanumeric).

但是,当我分类训练图像(用于检查哪些标签正在返回)时,我没有得到任何特定的排序。训练进行得很顺利(准确性达到85%),并且在对来自同一班级的图像进行分类时与输出标签保持一致。

如何推断由flow_from_directory生成的标签号码并将它们映射到类别?

+0

这个问题是固定的一个例子[此拉请求( https://github.com/fchollet/keras/pull/3052)。 –

回答

13

可以看到哪些类对应于整数看着变量ImageDataGenerator.class_indices

下面是关于如何使用它

def build(source=None): 
     datagen = ImageDataGenerator(rescale=1./255) 
     data_generator = datagen.flow_from_directory(
     source, # this is the target directory 
     target_size=(150, 150), # all images will be resized to 150x150 
     batch_size=11, 
     class_mode='sparse') 
     class_dictionary = data_generator.class_indices 
    return data_generator, class_dictionary 
+0

太棒了!谢谢!! –

+0

我得到的错误:'ImageDataGenerator'对象没有'class_indices' –

+0

的属性它可能不言而喻,但如果你不想在这种情况下运行'build()'函数时自动返回class_dictionary,你可以做:'全球class_dictionary',然后'class_dictionary = data_generator.class_indices'这将允许您访问全局的class_dictionary。 –