【问题标题】:Image Data Generator augmentation argument for specific folders only (Keras)仅针对特定文件夹的图像数据生成器扩充参数 (Keras)
【发布时间】:2018-11-16 20:13:19
【问题描述】:

我有 4 个独立的图像文件夹,它们有自己独立的标签(文件夹 1 中的图像对应于标签 1 等)。

但是,图像数据集不平衡,其中标签 1 和 2 的图像过多,但标签 3 和 4 的图像不足。

因此,我决定尝试进行图像增强来提升我的图像数据集。

这是我的代码的样子。

train_datagen = ImageDataGenerator(rotation_range=20,width_shift_range=0.2, height_shift_range=0.2,preprocessing_function=preprocess_input,horizontal_flip=True)


train_generator=train_datagen.flow_from_directory('/trainImages',target_size=(80,80),batch_size=32,class_mode='categorical')

所有图像文件夹都在路径“/trainImages”中(例如:“/trainImages/1”、“/trainImages/2”)

这种方法的问题是对文件夹 1 和 2 中的图像也进行了扩充(不需要扩充)

有没有办法自定义 ImageDataGenerator 以忽略文件夹 1 和 2 的图像增强参数?

我对 Python 和 Keras 都很陌生...

【问题讨论】:

    标签: python keras


    【解决方案1】:

    您可以创建两种文件夹结构:

    • 文件夹 1 - 仅包含不增加类的结构
    • 文件夹 2 - 包含要扩充的类的结构

    然后创建两个不同的生成器。

    dataGen1 = ImageDataGenerator(...)
    dataGen2 = ImageDataGenerator(.... withAugmentation ....)
    
    sequencer1 = dataGen1.flow_from_directory(dir1, ....)
    sequencer2 = dataGen2.flow_from_directory(dir2, ....)
    

    现在您创建自己的生成器,它应该包含每个序列器的索引列表。

    此代码未经测试,如果有错误可以评论,我明天测试它

    def myGenerator(seq1, seq2, multiplySeq2By):
    
        generators = [seq1,seq2]
    
        #here we're creating indices to get data from the generators
        len1 = len(seq1)
        len2 = len(seq2)
    
        indices1 = np.zeros((len1,2))
        indices2 = np.ones((len2,2))
    
        indices1[:,1] = np.arange(len1) #pairs like [0,0], [0,1], [0,2]....
        indices2[:,1] = np.arange(len2) #pairs like [1,0], [1,1], [1,2]....
    
        indices2 = [indices2] * multiplySeq2By #repeat indices2 to generate more from it
        allIndices = np.concatenate([indices1] + indices2, axis=0)
    
        #you can randomize the order here:
        np.random.shuffle(allIndices)
    
        #now we loop the indices infinitely to get data from the original generators
        while True: 
            for g, el in allIndices:
                x,y = generators[g][el]
                yield x,y #when training, or "yield x" when testing                    
    
            #you may want another round of shuffling here for the next epoch. 
    

    记得使用steps_per_epoch = len1 + (multiplySeq2By * len2)

    【讨论】:

    • 感谢您的回答。我在 x,y = generators[g][el] 处收到 TypeError,它说“只有整数标量数组可以转换为标量索引”
    • 你能打印allIndices.shape吗? type(g)type(el)?
    • 嗯,我想我明白了,在创建 allIndices 时查看新的 np.concatenate 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2018-02-09
    • 2017-06-01
    • 2019-01-12
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多