keras图像数据生成器.flow_from_directory(directory)统一/合并类 [英] keras image data generator .flow_from_directory(directory) unify/combine classes

查看:1387
本文介绍了keras图像数据生成器.flow_from_directory(directory)统一/合并类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Python与Keras和ImageDataGenerator结合使用,以从目录生成图像.我大约有20堂课,我想以某种方式统一它们.例如,类别1-4是x,而类别5-8是y. 可以在flow_from_directory中做到这一点吗?还是我必须根据统一类的需要对目录进行不同的拆分(例如,将目录1-4合并到dir x)?

I am using Python with Keras and ImageDataGenerator to generate images from directory. I have about 20 classes, and I would like to unify them in some way. For instance, classes 1-4 are x and 5-8 are y. Can ImageDataGenerator do that in flow_from_directory or do I have to split the directories differently according to my need of unifying classes (e.g combining directories 1-4 into dir x)?

推荐答案

我认为没有内置的方法.但是,一种替代方法是将生成器包装在另一个生成器中,并在其中修改标签(为演示起见,在这里,我假设我们最初有四个类,我们希望将一类和二类视为新类.一等,三等和四等被认为是新的二等):

I don't think there is a built-in way to do so. However, one alternative way is to wrap the generator inside another generator and modify the labels in it (for the sake of demonstration, here I have assumed we have four classes initially, and we want the classes one and two to be considered as the new class one and the classes three and four to be considered as the new class two):

# define the generator
datagen = ImageDataGenerator(...)

# assign class_mode to 'sparse' to make our work easier
gen = datagen.flow_from_directory(..., class_mode= 'sparse')

# define a mapping from old classes to new classes (i.e. 0,1 -> 0 and 2,3 -> 1)
old_to_new = np.array([0, 0, 1, 1])

# the wrapping generator
def new_gen(gen):
    for data, labels in gen:
        labels = old_to_new[labels]
        # now you can call np_utils.to_categorical method 
        # if you would like one-hot encoded labels
        yield data, labels

# ... define your model

# fit the model
model.fit(new_gen(gen), ...)

这篇关于keras图像数据生成器.flow_from_directory(directory)统一/合并类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆