【问题标题】:Keras CNN model throws a memory issue when I try to train it当我尝试训练 Keras CNN 模型时,它会引发内存问题
【发布时间】:2020-12-24 07:22:18
【问题描述】:

我是 CNN 的新手,我正在尝试在 dataset 上使用 Keras 制作一个基本的猫对狗 CNN 模型,该模型由 12500 张猫和狗的图像组成,即总共 25000 张图像。 我目前处理数据的方法如下:

将所有图像转换为 128x128 大小 --> 将它们转换为 numpy 数组 --> 将它们全部转换为黑白图像 --> 将它们除以 255 以进行归一化 --> 使用数据增强 --> 使用训练 CNN他们

(如果我们使用彩色图像会出现内存问题)

这是我正在尝试训练的模型:

model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', activation ='relu', input_shape = (128,128, 1)))
model.add(Conv2D(filters = 64, kernel_size = (5,5),padding = 'Same', activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Dropout(0.25))
          
model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same', activation ='relu'))
model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same', activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
          

model.add(Conv2D(filters = 32, kernel_size = (2,2),padding = 'Same', activation ='relu'))
model.add(Conv2D(filters = 32, kernel_size = (2,2),padding = 'Same', activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Dropout(0.25))
          
model.add(Flatten())
model.add(Dense(512, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(1, activation = "sigmoid"))
          
          
optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(optimizer = optimizer , loss = "binary_crossentropy", metrics=["accuracy"])
          
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, factor=0.5, min_lr=0.00001)

但是,每当我尝试开始训练时,即call model.fit_generator,它会打印 Epoch(1/30),然后抛出此错误:

ResourceExhaustedError: 2 root error(s) found.
  (0) Resource exhausted: OOM when allocating tensor with shape[86,128,64,64] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[{{node conv2d_4/convolution}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

     [[metrics/accuracy/Identity/_117]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

  (1) Resource exhausted: OOM when allocating tensor with shape[86,128,64,64] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[{{node conv2d_4/convolution}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.

0 successful operations.
0 derived errors ignored.

训练停止。

我知道它有一些与我的电脑内存有关的问题,因为我正试图在我的本地 Windows 系统上训练它。 我的问题是,我该怎么做才能解决这个问题。

我无法进一步降低图像质量,我很喜欢使用黑白图像来减少内存消耗。

我的系统内存: 8GB 内存, 2GB Nvidia GeForce 940MX 显卡

如果有人需要完整代码,这是我完整的 python 笔记本link

另外,当我执行from keras.models import Sequential时,它会引发以下警告

FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])

【问题讨论】:

  • 2GB也不多,把512降到128什么的。

标签: numpy keras deep-learning jupyter-notebook conv-neural-network


【解决方案1】:

您正在将整个数据集加载到主内存中。如果您的数据集很大,则不建议这样做,因为您几乎总是会耗尽内存。

解决方案是使用 TensorFlow 的 flow_from_directory 方法,该方法允许您在需要时加载批次,而不是将整个数据集保存在内存中。
代码:

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        'data/train',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
        'data/validation',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
model.fit(
        train_generator,
        steps_per_epoch=2000,
        epochs=50,
        validation_data=validation_generator,
        validation_steps=800)

您的代码将如下所示。

有了这个,您可以进行图像增强以及加载数据而不将其存储在主内存中。

有关图像增强选项,请参阅 this

有关 flow_from_directory 选项,请参阅 this

这里,标签是从目录名称中推断出来的。 您的目录结构应如下所示。

train
    - cat
        - img1
        - imgn
    - dog
        - img1
        - imgn

This 是使用上述方法的完整端到端示例的链接。

注意:您的steps_per_epoch = total_samples / batch_size

如果您仍然收到 OOM 错误。

  1. 尝试减少批量大小
  2. 尝试缩小图片尺寸
  3. 尝试减少图像通道,即(RGB --> 灰度)
  4. 尝试减小模型大小。

【讨论】:

  • 是的,感谢您提供此信息,它应该对我有用,抱歉,我目前无法投票,因为我的声誉少于 15 个
  • 您可以通过单击答案上的复选标记来接受答案。请参阅this 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2020-01-19
  • 2018-10-16
  • 2020-01-27
相关资源
最近更新 更多