sessionConfig = tf.ConfigProto()#配置session参数
sessionConfig.gpu_options.allow_growth = True#gpu按需分配
sess = tf.Session(config=sessionConfig)
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(tf.global_variables())
(1)在tensorflow中定义session时作如下设置,该设置会启用最少的GPU显存来运行程序。
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
(2)在tensorflow中定义session时作如下设置,该设置会强制程序只占用指定比例的GPU显存。
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.4 # 占用GPU40%的显存
session = tf.Session(config=config)
查询gpu是否可用
终端中
import numpy
import tensorflow as tf
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))
jupyter
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
TensorFlow-gpu安装成功,gpu不能使用,可能原因是cpu和gpu同时安装了,需要重新卸载cpu和gpu版本TensorFlow,然后只安装TensorFlow-gpu版本
pip uninstall tensorflow
pip uninstall tensorflow-gpu
#conda list 查看是否完全卸载,要彻底卸载
pip install tensorflow-gpu=1.8.0
指定GPU运行
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
$CUDA_VISIBLE_DEVICES=0 python *.py ...