TensorFlow-gpu使用方法


Table of Contents

软硬件:

TensorFlow-gpu信息

TensorFlow—gpu使用方法(1)

TensorFlow—gpu使用方法(2)

A. 定量设置显存

B. 按需设置显存

实测:

 


软硬件:

  • GTX1063  
  • CUDA9.1
  • TensorFlow-gpu
  • Pycharm
  • python3.6

TensorFlow-gpu信息

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

获取如下信息:

2019-03-02 14:32:43.615840: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1432] Found device 0 with properties: 
name: GeForce GTX 1060 3GB major: 6 minor: 1 memoryClockRate(GHz): 1.7335
pciBusID: 0000:01:00.0
totalMemory: 3.00GiB freeMemory: 2.42GiB
2019-03-02 14:32:43.616103: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1511] Adding visible gpu devices: 0
2019-03-02 14:32:44.358785: I tensorflow/core/common_runtime/gpu/gpu_device.cc:982] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-03-02 14:32:44.358937: I tensorflow/core/common_runtime/gpu/gpu_device.cc:988]      0 
2019-03-02 14:32:44.359027: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1001] 0:   N 
2019-03-02 14:32:44.359277: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 2115 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060 3GB, pci bus id: 0000:01:00.0, compute capability: 6.1)


TensorFlow—gpu使用方法(1)

如果电脑有多个GPU,tensorflow默认全部使用。如果想只使用部分GPU,可以设置CUDA_VISIBLE_DEVICES。在执行python程序时,可以通过如下方式初始化:

import os

os.environ["CUDA_VISIBLE_DEVICES"] = "0"

当python编译器找到相应的devices之后就会自动启用GPU来进行计算。


TensorFlow—gpu使用方法(2)

在方法1中,我们使用了简单的命令来调用GPU,但是这会使得实际使用中的GPU显存利用率交由系统,而我们无法再进行动态分配和管理,因此,在启用GPU时应当对显存使用形式及利用率进行定义,进而防止因爆显存而死机的现象。

A. 定量设置显存

默认tensorflow是使用GPU尽可能多的显存。可以通过下面的方式,来设置使用的GPU显存:

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.7)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

分配给tensorflow的GPU显存大小为:GPU实际显存*0.7。 
可以按照需要,设置不同的值,来分配显存。


B. 按需设置显存

上面的只能设置固定的大小。如果想按需分配,可以使用allow_growth参数

gpu_options = tf.GPUOptions(allow_growth=True)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))   

实测:

如果对显卡计算能力没有太多顾虑,使用方法1最为直接高效,实测面部识别训练模型,1W+2W的训练数据集,i5 8400CPU训练时间接近30分钟

使用GPU加速:训练时间小于2分钟,加速明显。

After 2144 training step(s), loss on training batch is 0.00834797. 
After 2145 training step(s), loss on training batch is 0.016617. 
After 2146 training step(s), loss on training batch is 0.00964502. 
After 2147 training step(s), loss on training batch is 0.0582324. 
After 2148 training step(s), loss on training batch is 0.0779959. 
After 2149 training step(s), loss on training batch is 0.180952. 
accuracy higher than 0.991197 !
Model saved in file:  E:\FaceDetection\my_faces\model

猜你喜欢

转载自blog.csdn.net/hhaowang/article/details/88075649