Skip to main content
 首页 » 编程设计

python之使用 ImageDataGenerator 时,具有 mxnet 后端和 8 个 GPU 的 Keras 训练速度很慢

2025年02月15日7pengyingh

关注这篇精彩的帖子:Scaling Keras Model Training to Multiple GPUs我尝试升级我的模型以在我的多个 GPU 实例上并行运行。

起初我按照此处建议运行了 MNIST 示例:MNIST in Keras编译命令中的附加语法如下:

# Prepare the list of GPUs to be used in training 
NUM_GPU = 8 # or the number of GPUs available on your machine 
gpu_list = [] 
for i in range(NUM_GPU): gpu_list.append('gpu(%d)' % i) 
 
# Compile your model by setting the context to the list of GPUs to be used in training. 
model.compile(loss='categorical_crossentropy', 
              optimizer=opt, 
              metrics=['accuracy'],  
              context=gpu_list) 

然后我训练了模型:

model.fit(x_train, y_train, 
          batch_size=batch_size, 
          epochs=epochs, 
          verbose=1, 
          validation_data=(x_test, y_test)) 

到目前为止一切顺利。它每个 epoch 的运行时间不到 1 秒,我真的很兴奋和高兴,直到我尝试了 - 数据增强。

到那时,我的训练图像是一个大小为 (6000,1,28,28) 的 numpy 数组,标签的大小为 (10,60000) - one-hot 编码。对于数据扩充,我使用了 ImageDataGenerator 函数:

gen = image.ImageDataGenerator(rotation_range=8, width_shift_range=0.08, shear_range=0.3, 
                               height_shift_range=0.08, zoom_range=0.08) 
batches = gen.flow(x_train, y_train, batch_size=NUM_GPU*64) 
test_batches = gen.flow(x_test, y_test, batch_size=NUM_GPU*64) 

然后:

model.fit_generator(batches, batches.N, nb_epoch=1,  
                    validation_data=test_batches, nb_val_samples=test_batches.N) 

不幸的是,从每轮 1 秒开始,我开始每轮 11 秒...我认为 ImageDataGenerator 的“影响”是破坏性的,它可能运行所有(读取->增强->写入 gpu)过程真的很慢而且效率低下。

将 keras 扩展到多个 GPU 很棒,但数据增强对于我的模型足够稳健至关重要。

我想一个解决方案可能是:从目录加载所有图像并编写您自己的函数来随机播放和扩充这些图像。但我确信必须有一些更简单的方法来使用 keras API 优化此过程。

谢谢!

请您参考如下方法:

好的,我找到了解决方案。 您需要使用 mxnet 的迭代器。看这里: Image IO - Loading and pre-processing images 而不是 Keras 的 data_generator