生成器和序列之间的Keras差

问题描述 投票:22回答:1

我正在使用深层的CNN + LSTM网络在1D信号的数据集上进行分类。我正在使用keras 2.2.4支持的tensorflow 1.12.0。由于我的数据集很大且资源有限,因此在训练阶段,我将使用生成器将数据加载到内存中。首先,我尝试了这个生成器:

def data_generator(batch_size, preproc, type, x, y):
    num_examples = len(x)
    examples = zip(x, y)
    examples = sorted(examples, key = lambda x: x[0].shape[0])
    end = num_examples - batch_size + 1
    batches = [examples[i:i + batch_size] for i in range(0, end, batch_size)]

    random.shuffle(batches)
    while True:
        for batch in batches:
            x, y = zip(*batch)
            yield preproc.process(x, y)

使用上述方法,我可以一次以最多30个样本的小批量启动训练。但是,这种方法不能保证网络每个时期每个样本仅训练一次。考虑到Keras网站上的评论:

Sequence是进行多处理的更安全方法。这种结构保证网络在每个样本上仅训练一次生成器不是这样的时代。

我尝试了使用以下类加载数据的另一种方式:

class Data_Gen(Sequence):

def __init__(self, batch_size, preproc, type, x_set, y_set):
    self.x, self.y = np.array(x_set), np.array(y_set)
    self.batch_size = batch_size
    self.indices = np.arange(self.x.shape[0])
    np.random.shuffle(self.indices)
    self.type = type
    self.preproc = preproc

def __len__(self):
    # print(self.type + ' - len : ' + str(int(np.ceil(self.x.shape[0] / self.batch_size))))
    return int(np.ceil(self.x.shape[0] / self.batch_size))

def __getitem__(self, idx):
    inds = self.indices[idx * self.batch_size:(idx + 1) * self.batch_size]
    batch_x = self.x[inds]
    batch_y = self.y[inds]
    return self.preproc.process(batch_x, batch_y)

def on_epoch_end(self):
    np.random.shuffle(self.indices)

[我可以确认使用此方法,网络每个时期对每个样本都进行了一次训练,但是这次当我在微型批处理中放入7个以上样本时,我内存不足错误:

OP_REQUIRES在random_op.cc处失败:202:资源耗尽:OOM时用形状分配张量......

我可以确认我使用相同的模型架构,配置和机器来进行此测试。我想知道为什么这两种加载数据的方式会有区别?

[如有需要,请随时询问更多详细信息。

谢谢。

编辑:

这是我用来拟合模型的代码:

reduce_lr = keras.callbacks.ReduceLROnPlateau(
            factor=0.1,
            patience=2,
            min_lr=params["learning_rate"])

        checkpointer = keras.callbacks.ModelCheckpoint(
            filepath=str(get_filename_for_saving(save_dir)),
            save_best_only=False)

        batch_size = params.get("batch_size", 32)

        path = './logs/run-{0}'.format(datetime.now().strftime("%b %d %Y %H:%M:%S"))
        tensorboard = keras.callbacks.TensorBoard(log_dir=path, histogram_freq=0,
                                                  write_graph=True, write_images=False)
        if index == 0:
            print(model.summary())
            print("Model memory needed for batchsize {0} : {1} Gb".format(batch_size, get_model_memory_usage(batch_size, model)))

        if params.get("generator", False):
            train_gen = load.data_generator(batch_size, preproc, 'Train', *train)
            dev_gen = load.data_generator(batch_size, preproc, 'Dev', *dev)
            valid_metrics = Metrics(dev_gen, len(dev[0]) // batch_size, batch_size)
            model.fit_generator(
                train_gen,
                steps_per_epoch=len(train[0]) / batch_size + 1 if len(train[0]) % batch_size != 0 else len(train[0]) // batch_size,
                epochs=MAX_EPOCHS,
                validation_data=dev_gen,
                validation_steps=len(dev[0]) / batch_size + 1  if len(dev[0]) % batch_size != 0 else len(dev[0]) // batch_size,
                callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])

            # train_gen = load.Data_Gen(batch_size, preproc, 'Train', *train)
            # dev_gen = load.Data_Gen(batch_size, preproc, 'Dev', *dev)
            # model.fit_generator(
        #     train_gen,
        #     epochs=MAX_EPOCHS,
        #     validation_data=dev_gen,
        #     callbacks=[valid_metrics, MyCallback(), checkpointer, reduce_lr, tensorboard])
python tensorflow keras generator
1个回答
0
投票

您需要减小批量大小。一般而言,对于图片而言,32似乎很大-尝试将其缩小为16。

然后增加小批量的大小。

© www.soinside.com 2019 - 2024. All rights reserved.