使用tf.device()怎么指定运行tensorflow

这篇文章给大家介绍使用tf.device()怎么指定运行tensorflow,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

设置使用GPU

使用 tf.device('/gpu:1') 指定Session在第二块GPU上运行:

import tensorflow as tf
 
with tf.device('/gpu:1'):
  v1 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v1')
  v2 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v2')
  sumV12 = v1 + v2
 
  with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    print sess.run(sumV12)

ConfigProto() 中参数 log_device_placement=True  会打印出执行操作所用的设备,以上输出:

使用tf.device()怎么指定运行tensorflow

如果安装的是GPU版本的tensorflow,机器上有支持的GPU,也正确安装了显卡驱动、CUDA和cuDNN,默认情况下,Session会在GPU上运行:

import tensorflow as tf
 
v1 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v1')
v2 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v2')
sumV12 = v1 + v2
 
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
  print sess.run(sumV12)

默认在GPU:0上执行:

使用tf.device()怎么指定运行tensorflow

设置使用cpu

tensorflow中不同的GPU使用/gpu:0和/gpu:1区分,而CPU不区分设备号,统一使用 /cpu:0

import tensorflow as tf
 
with tf.device('/cpu:0'):
  v1 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v1')
  v2 = tf.constant([1.0, 2.0, 3.0], shape=[3], name='v2')
  sumV12 = v1 + v2
 
  with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    print sess.run(sumV12)

使用tf.device()怎么指定运行tensorflow

关于使用tf.device()怎么指定运行tensorflow就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。