【问题标题】:How can I use a GPU with Keras?如何将 GPU 与 Keras 一起使用?
【发布时间】:2023-02-04 04:18:54
【问题描述】:

我的问题是,我正在尝试在 google colab 中使用 Keras 训练一个卷积神经网络,它能够区分狗和猫,但是在进入训练阶段时,我的模型需要很长时间才能训练,我想知道如何以正确的方式使用 GPU 以缩短训练时间。


from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)

training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/files/dataset_CNN/training_set',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/Colab Notebooks/files/dataset_CNN/test_set',
                                            target_size = (64, 64),
                                            batch_size = 32,
                                            class_mode = 'binary')
device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
  raise SystemError('GPU device not found')
with tf.device('/device:GPU:0'):#I tried to put this part that I found by researching on the internet 
  
  classifier = Sequential()
  classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
  classifier.add(MaxPooling2D(pool_size = (2, 2)))
  classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
  classifier.add(MaxPooling2D(pool_size = (2, 2)))
  classifier.add(Flatten())
  classifier.add(Dense(units = 128, activation = 'relu'))
  classifier.add(Dense(units = 1, activation = 'sigmoid'))
  classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
  classifier.fit(training_set,
                         steps_per_epoch = 8000,
                         epochs = 25,
                         validation_data = test_set,
                         validation_steps = 2000)

之前我没有把这部分代码放在“with tf.device('/device:GPU:0')”,我在网上的一个例子中看到了这部分代码,但是训练的时候还是很慢。我已经使用以下方法检查了可用的 GPU:


device_name = tf.test.gpu_device_name()
if device_name != '/device:GPU:0':
  raise SystemError('GPU device not found')


【问题讨论】:

  • 您是否将 Colab 的运行时配置为使用 GPU?默认情况下,colab 启动一个 CPU 实例。转到运行时 > 更改运行时类型 > 硬件加速器并切换到 GPU。
  • 此外,也许最好使用 tf.test.is_gpu_available() 而不是设备名称,因为在某些系统中你可能不会得到“GPU:0”,但其他一些设备
  • 这回答了你的问题了吗? Can I run Keras model on gpu?
  • 我在 Google colab 上从 CPU 切换到 GPU 使用,是的,我进入那个论坛 link 并尝试过,但无论如何它在训练阶段很慢。
  • “慢”是什么意思,GPU 并不是能让你的代码更快的灵丹妙药。

标签: python tensorflow keras deep-learning


【解决方案1】:

在 Google Colab 中选择 GPU -
选择编辑-笔记本设置-硬件加速器-GPU-保存

ImageDataGenerator 不推荐用于新代码。相反,您可以在模型训练中直接通过 layers 使用这些增强功能,如下所示:

classifier = tf.keras.Sequential([
#data augmention layers
  layers.Resizing(IMG_SIZE, IMG_SIZE),
  layers.Rescaling(1./255),
  layers.RandomFlip("horizontal"),
  layers.RandomZoom(0.1),
#model building layers
  layers.Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'),
  layers.MaxPooling2D(pool_size = (2, 2)),
  layers.Conv2D(32, (3, 3), activation = 'relu'),
  layers.MaxPooling2D(pool_size = (2, 2)),
  layers.Flatten(),
  layers.Dense(units = 128, activation = 'relu'),
  layers.Dense(units = 1, activation = 'sigmoid')
])

此外,您应该使用 image_dataset_from_directory 导入图像数据集,该数据集从目录中的图像文件生成 tf.data.Dataset。请参考这个gist的复制代码。

笔记:fit() 根据 batch_size 从训练集中自动计算 Steps_per_epoch。
Steps_per_epoch = len(training_dataset)//batch_size

【讨论】:

    猜你喜欢
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2021-07-03
    • 2020-09-28
    • 2020-12-15
    • 2016-08-20
    相关资源
    最近更新 更多