【问题标题】:keras image data generator .flow_from_directory(directory) unify/combine classeskeras 图像数据生成器 .flow_from_directory(directory) 统一/组合类
【发布时间】:2019-02-22 08:39:36
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 使用class_mode sparse时,鉴于我的原始标签不是整数,它们将如何排序?例如猫狗和鸟,谁将成为 0,1 和 2?
    • @thebeancounter 根据the documentation,将对目录名称进行排序,然后进行索引映射:“将映射到标签索引的类的顺序将是字母数字” .此外,您可以使用class_indices 属性访问此映射(即字典)。
    猜你喜欢
    • 2018-03-05
    • 2019-01-12
    • 2019-08-11
    • 2021-04-29
    • 2018-02-09
    • 1970-01-01
    • 2017-06-01
    • 2017-10-04
    • 2020-03-11
    相关资源
    最近更新 更多