【问题标题】:How to change python generator into Keras Sequence object?如何将 python 生成器更改为 Keras 序列对象?
【发布时间】:2019-09-07 16:08:05
【问题描述】:

我正在研究一个回归问题。我的 CNN 训练形状为 32x513x30 - 每批 32 个 513x30 实例,然后是 4810 批的数据。

我将这些批次保存在一个目录中,每个都命名为“batch#number.npy”。

在使用 Python 生成器时,我不断收到来自 TensorFlow 的警告:

警告:tensorflow:使用带有use_multiprocessing=True的生成器 并且多个工作人员可能会复制您的数据。请考虑使用 keras.utils.Sequence 类。

我想出了如何使用 Python 生成器加载它们。但是,在使用多处理时,建议使用 Keras 的 Sequence 类:https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence

不幸的是,这对我来说有点太复杂了。 这是我一直在使用的代码:

def batch_gen(num):

    os.chdir('mydirectory/train')

    for n in num:
        placeholder = np.load('batch#' + str(n) + '.npy')
        X = placeholder[:,:513,:]
        Y1= placeholder[:,513:,:]

        Y = X * Y1

        X = X / normalization # normalize X
        X = scale_mag*X.astype(np.float32)

        Y = Y / normalization 
        Y = scale_mag*Y.astype(np.float32)


        X = np.reshape(X,(32,513,30,1))
        Y = np.reshape(Y,(32,513,30,1))
        yield (X, Y)

my_gen = batch_gen(C)   # C is an array with indexes 1 to 4810 (looped by number of training epochs)

我使用生成器的方式是否会导致我的数据在训练期间重复?如果是这样,我怎么能把它翻译成一个序列类?

谢谢。

【问题讨论】:

    标签: python tensorflow keras generator sequence


    【解决方案1】:
      class MyBatchGenerator(Sequence):
        def __init__(self, C):
            self.C = C
    
        def __len__(self):
            return len(self.C)
    
        def __getitem__(self, idx):   
    
            n = self.C[idx]
            os.chdir('mydirectory/train')
    
            placeholder = np.load('batch#' + str(n) + '.npy')
            X = placeholder[:,:513,:]
            Y1= placeholder[:,513:,:]
    
            Y = X * Y1
    
            X = X / normalization # normalize X
            X = scale_mag*X.astype(np.float32)
    
            Y = Y / normalization 
            Y = scale_mag*Y.astype(np.float32)
    
    
            X = np.reshape(X,(32,513,30,1))
            Y = np.reshape(Y,(32,513,30,1))
            return (X, Y)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 2016-06-30
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      相关资源
      最近更新 更多