Tensorflow框架GPU使用

 在配置好GPU环境的TensorFlow中,如果操作没有明确地指定运行设备,那么TensorFlow会优先选择GPU,但只会选择一个GPU来计算
可以通过tf.device来手动指定:
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:1'):
    c = a + b
#加入参数,将运行每一个操作的设备输出到控制台
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print sess.run(c)
   
 但是有些操作是不能放在GPU中的,如果程序中全部使用强制指定设备的方式会降低程序的可移植性,解决方法如下:
 TensorFlow在生成会员时可以指定allow_soft_placement参数为True,如果运算无法由GPU执行,那么TensorFlow会自动放在CPU中执行。如
import tensorflow as tf

a_cpu = tf.Variable(0, name="a_cpu")
with tf.device('/gpu:0'):
    a_gpu = tf.Variable(0, name='a_gpu')

#通过allow_soft_placement参数自动将无法放在GPU上的操作放回CPU中
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
sess.run(tf.initialize_all_variables())


Tip:一般将计算密集型的运算放在GPU上,而将其他操作放在CPU中。

猜你喜欢

转载自blog.csdn.net/qq_27150893/article/details/80857135