tensorflow使用——(八)GPU

一、指定GPU

1、tf.ConfigProto

tf.ConfigProto一般用在创建session的时候。用来对session进行参数配置

with tf.Session(config = tf.ConfigProto(...),...)

 2、参数

#tf.ConfigProto()的参数
log_device_placement=True : 是否打印设备分配日志
allow_soft_placement=True : 如果你指定的设备不存在,允许TF自动分配设备

3、实例 :查看运算设备

#coding:utf-8
import tensorflow as tf
a=tf.constant([1.0,2.0,3.0],shape=[3],name='a')
b=tf.constant([1.0,2.0,3.0],shape=[3],name='b')
c=a+b
#log_device_placement=True 输出运行每一个运算的设备
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    print(sess.run(c))

 4、分别指定不同设备

可以把运算放在不同的device上
#coding:utf-8
import tensorflow as tf
with tf.device('/cpu:0'):
    a=tf.constant([1.0,2.0,3.0],shape=[3],name='a')
    b=tf.constant([1.0,2.0,3.0],shape=[3],name='b')
with tf.device('/gpu:0'):
    c=a+b
#log_device_placement=True 输出运行每一个运算的设备
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    print(sess.run(c))

二、动态分配GPU。

不会占用整个GPU,可以在一块GPU上同时运行多个任务

import tensorflow as tf
import os
def set_config():
    # 控制使用率
    os.environ['CUDA_VISIBLE_DEVICES'] = '1'
    # 假如有16GB的显存并使用其中的8GB:
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)
    config = tf.ConfigProto(gpu_options=gpu_options)
    # session = tf.Session(config=config)
    return config
 
if __name__ == '__main__':
    a = tf.constant([1.0, 2.0, 3.0], shape=[3], name='a')
    b = tf.constant([1.0, 2.0, 3.0], shape=[3], name='b')
 
    c = a + b
    cfg=set_config()
    with tf.Session(config=cfg) as sess:
        print(sess.run(c))

猜你喜欢

转载自blog.csdn.net/weixin_37799689/article/details/106507157