代码一:
选用默认设备计算
import tensorflow as tf
with tf.device('/gpu:0'):#选用默认设备(gpu:0)计算以下张量
inputs = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
weights = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
bias = tf.zeros(shape=[weights.get_shape()[-1]])
logits = tf.add(tf.matmul(inputs,weights),bias)
若tensorflow无法使用GPU加速,可以加上以下代码,可以动态分配cpu与gpu,并可以查看设备调用信息
#gpu_options
#gpu_options = tf.GPUOptions(allow_growth=True) #允许GPU内存分配动态增加
gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.4)#限制GPU使用率为0.4
#以上两gpu_options取其一
# allow_soft_placement:允许动态分配gpu内存
# log_device_placement:打印出设备信息
config = tf.ConfigProto(
allow_soft_placement=True,log_device_placement=True,gpu_options=gpu_options)
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
print("logits:",sess.run(logits))
注:log_device