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中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值