ubuntu 16.04 使用keras框架 对比cpu和gpu训练神经网络的速度

本机配置:

cpu:i5-4500H

gpu:gtx 950M

照例,先查看本机可以使用的设备

在spyder中输入:

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices()) 

 

也就是说,我可以选择调用cpu,也可以选择调用gpu。

先上测试代码:

import tensorflow as tf
from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical
with tf.device('/gpu:0'):   #选择使用的设备,设备编号之前已经得到
    (train_images,train_labels),(test_images,test_labels)=mnist.load_data()
    network=models.Sequential()
    network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
    network.add(layers.Dense(10,activation='softmax'))
    network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
    train_images=train_images.reshape((60000,28*28))
    train_images=train_images.astype('float32')/255
    test_images=test_images.reshape((10000,28*28))
    test_images=test_images.astype('float32')/255
    train_labels=to_categorical(train_labels)
    test_labels=to_categorical(test_labels)
    network.fit(train_images,train_labels,epochs=5,batch_size=32)

我在windows10 环境下,通过keras框架,对比cpu和gpu训练神经网络的速度时使用过这段代码,所以我就不多介绍了。

但是要注意的是我加了注释的那一行代码,那一行用于选择执行任务的设备,简单地说就是选择cpu或者gpu。

gpu运行结果:

除了第一个epoch以外其他的epoch耗时只需要6秒,这个速度比在windows系统中使用gpu训练还快,可能这就是普遍采用linux系统来训练神经网络的一个原因吧。

平均epoch:6s

平均step:104us

cpu运行结果:

在ubuntu系统下cpu训练神经网络的速度也比在windows环境下要快。

平均epoch:11s

平均step:180us

总结:在ubuntu系统下,使用同样的配置和同样的框架,使用gpu训练简单的神经网络相比于使用cpu训练相同的神经网络可以节省约42%的时间。

在windows环境下gpu和cpu训练相同的神经网络速度对比可以见链接:

https://blog.csdn.net/qq_38279908/article/details/88758080

猜你喜欢

转载自blog.csdn.net/qq_38279908/article/details/88817518