python - keras图像数据生成器.flow_from_directory(directory)统一/组合类

标签 python image-processing machine-learning keras deep-learning

我使用 Python 与 Keras 和 ImageDataGenerator 从目录生成图像。我有大约 20 个类,我想以某种方式统一它们。例如,类别 1-4 是 x,类别 5-8 是 y。 ImageDataGenerator 可以在 flow_from_directory 中执行此操作吗?或者我是否必须根据统一类的需要以不同方式拆分目录(例如,将目录 1-4 合并到 dir x 中)?

最佳答案

我认为没有内置的方法可以做到这一点。然而,一种替代方法是将生成器包装在另一个生成器中并修改其中的标签(为了演示,这里我假设我们最初有四个类,并且我们希望类一和类二被视为新的)一类和三类、四类被视为新的二类):

# 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), ...)

关于python - keras图像数据生成器.flow_from_directory(directory)统一/组合类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52384386/

相关文章:

python - 从函数调用时显示混淆矩阵

tensorflow - 对狗类型的图像识别不起作用,我的模型可能是问题所在,但我是新手

python - 如何在keras中进行多类图像分类?

python - 如何识别字符串中的单个数字以插入前导零?

image-processing - 防止ffmpeg在降低视频分辨率的同时改变颜色的强度

python - 如何学习计算机视觉编程和实时图像处理的基本概念

ios - 在 iOS 中通过 opencv 或 opengl 拉伸(stretch)图像区域

python - OpenCV + OS X + 外部网络摄像头 = 非常慢

python - 在 Django 中迁移时依赖项引用不存在的父节点错误

python - 如何在没有索引的情况下将数据框转换为 Pandas 中的字典