如何输入大量数据训练Keras模型以防止RAM崩溃?

How to input large amount of data for training Keras model to prevent RAM crashing?

我正在尝试为顺序图像分类任务训练 Tensorflow Keras 模型。该模型本身是一个简单的 CNN-RNN 模型,我之前曾在一维信号的分类中使用过它,那里没有问题。

我无法加载必要的数据来在我的计算机上训练模型,因为 RAM 已满并且整个过程崩溃

我的数据是这样的:

(batch, timesteps, height, width, channels) = (batch, 30, 300, 600, 3)

我的数据管道是这样的顺序:

  1. glob.glob将一个文件夹中的所有文件放入列表
  2. 从一个文件中加载所有数据,创建一个大约为 (50, 30, 300, 600, 3) 的数组
  3. 使用 list.append
  4. 将单个文件中的数组堆叠到一个不断增长的列表中
  5. 在添加所有单个文件数据后,np.vstack 为 training/validation
  6. 创建最终数据

上面的过程还可以,但是我觉得appending/vstack在做图像处理的时候由于数据的大小不是一个好的选择。

有没有办法说将数据保存在 tf.records 中以减小整体大小?或者有没有办法设置数据输入管道,以便可以将数据加载到更小的 chunks?

非常感谢任何帮助,提前致谢。

你需要的叫DataGenerator

现在您的代码可能如下所示:

import numpy as np
from keras.models import Sequential

# Load entire dataset
X, y = np.load('some_training_set_with_labels.npy')

# Design model
model = Sequential()
[...] # Your architecture
model.compile()

# Train model on your dataset
model.fit(x=X, y=y)

您的数据生成器将类似于:

import numpy as np
import keras

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, list_IDs, labels, batch_size=32, dim=(32,32,32), n_channels=1,
                 n_classes=10, shuffle=True):
        'Initialization'
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_IDs
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))
        if self.shuffle == True:
            np.random.shuffle(self.indexes)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, *self.dim, self.n_channels))
        y = np.empty((self.batch_size), dtype=int)

        # Generate data
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            X[i,] = np.load('data/' + ID + '.npy')

            # Store class
            y[i] = self.labels[ID]

        return X, keras.utils.to_categorical(y, num_classes=self.n_classes)

我们必须相应地修改我们的 Keras 脚本,以便它接受我们刚刚创建的生成器。

import numpy as np

from keras.models import Sequential
from my_classes import DataGenerator

# Parameters
params = {'dim': (32,32,32),
          'batch_size': 64,
          'n_classes': 6,
          'n_channels': 1,
          'shuffle': True}

# Datasets
partition = # IDs
labels = # Labels

# Generators
training_generator = DataGenerator(partition['train'], labels, **params)
validation_generator = DataGenerator(partition['validation'], labels, **params)

# Design model
model = Sequential()
[...] # Architecture
model.compile()

# Train model on dataset
model.fit_generator(generator=training_generator,
                    validation_data=validation_generator,
                    use_multiprocessing=True,
                    workers=4)

查看 Stanford University website for more details. It's a bit dated. Have a look at pyimagesearch tutorial 以了解更多最新信息