【问题标题】:Integrate the ImageDataGenerator in own customized fit_generator将 ImageDataGenerator 集成到自己定制的 fit_generator 中
【发布时间】:2020-08-31 02:04:46
【问题描述】:

我想使用存储在我的内存中且没有标签(只是一个任意的虚拟标签)的多个输入来拟合 Siamese CNN。因此,为了在 Keras 中使用 CNN 模型,我不得不编写自己的 data_generator 函数。

我的数据生成器如下形式

class DataGenerator(keras.utils.Sequence):

def __init__(self, train_data, train_triplets, batch_size=32, dim=(128,128), n_channels=3, shuffle=True):
    self.dim = dim
    self.batch_size = batch_size
    #Added
    self.train_data = train_data
    self.train_triplets = train_triplets 
    self.n_channels = n_channels
    self.shuffle = shuffle
    self.on_epoch_end()

def __len__(self):
    'Denotes the number of batches per epoch'
    n_row = self.train_triplets.shape[0]
    return int(np.floor(n_row / self.batch_size))


def __getitem__(self, index): 
    'Generate one batch of data'
    # Generate indexes of the batch
    #print(index)
    indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
    # Find list of IDs      
    list_IDs_temp = self.train_triplets.iloc[indexes,]

    # Generate data
    [anchor, positive, negative] = self.__data_generation(list_IDs_temp)
    y_train = np.random.randint(2, size=(1,2,self.batch_size)).T

    return [anchor,positive, negative], y_train

def on_epoch_end(self):
    'Updates indexes after each epoch'
    n_row = self.train_triplets.shape[0]
    self.indexes = np.arange(n_row)
    if self.shuffle == True:
        np.random.shuffle(self.indexes)

def __data_generation(self, list_IDs_temp):
    'Generates data containing batch_size samples' 
    # anchor positive and negatives: (n_samples, *dim, n_channels)
    # Initialization
    anchor = np.zeros((self.batch_size,*self.dim,self.n_channels))
    positive = np.zeros((self.batch_size,*self.dim,self.n_channels))
    negative = np.zeros((self.batch_size,*self.dim,self.n_channels))

    nrow_temp = list_IDs_temp.shape[0] 
    # Generate data
    for i in range(nrow_temp):
        list_ind = list_IDs_temp.iloc[i,]
        anchor[i] = self.train_data[list_ind[0]]
        positive[i] = self.train_data[list_ind[1]]
        negative[i] = self.train_data[list_ind[2]]   

    return [anchor, positive, negative]

其中 train_data 是所有图像的列表,训练三元组是一个包含图像索引的数据框,以创建包含三组图像的输入。 现在,我想为提供给我的 CNN 的每个 mini batch 做一些数据增强。我试图集成 Keras 的 ImageDataGenerator,但我无法在我的代码中实现它。有没有可能做到这一点?我对 python 不是很有经验,如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: machine-learning keras conv-neural-network


    【解决方案1】:

    this article 会回答你的问题吗?

    简而言之,Kera 的 ImageDataGenerator 在个性化批处理生成器方面缺乏灵活性,而仍然使用数据增强的最简单方法是简单地切换到另一个数据增强工具(如所描述的 albumentations 库在上一篇文章中,但您也可以使用imgaug)。

    我只是想警告你,我遇到了albumentations 的几个问题(我在 GitHub 上的 this question 中描述过,但现在我仍然没有答案),所以也许使用 imgaug 是一个更好的主意.

    希望这会有所帮助,祝你的模型好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2018-06-03
      • 2018-05-01
      • 2023-04-07
      • 2017-06-07
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多