Python-Tensorflow在GPU而不是CPU上运行

时间:2017-10-20 14:47:38

标签: python tensorflow tensorflow-gpu

我有以下示例张量流代码

import tensorflow as tf
with tf.device('/cpu:0'):
  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)
print(sess.run(c))

显式我已经给出了tf.device('/ cpu:0'),但它给出了以下错误:

InvalidArgumentError (see above for traceback): Cannot assign a device for operation 'MatMul_5': Operation was explicitly assigned to /device:GPU:0 but available devices are [ /job:localhost/replica:0/task:0/cpu:0 ]. Make sure the device specification refers to a valid device.
     [[Node: MatMul_5 = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/device:GPU:0"](a_5, b_5)]]

Tensorflow版本:1.3.0, python版本:3.6.1 with Anaconda Distribution

1 个答案:

答案 0 :(得分:0)

我跑了这个并且它有效,输出如下:

MatMul: (MatMul): /job:localhost/replica:0/task:0/gpu:0
2017-10-20 15:50:04.556484: I 
tensorflow/core/common_runtime/simple_placer.cc:872] MatMul: 
(MatMul)/job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/cpu:0
2017-10-20 15:50:04.556595: I tensorflow/core/common_runtime/simple_placer.cc:872] b: (Const)/job:localhost/replica:0/task:0/cpu:0
a: (Const): /job:localhost/replica:0/task:0/cpu:0
2017-10-20 15:50:04.556624: I tensorflow/core/common_runtime/simple_placer.cc:872] a: (Const)/job:localhost/replica:0/task:0/cpu:0
[[ 22.  28.]
 [ 49.  64.]]

看起来matmul最终会在GPU上运行而你的GPU不可用。我有相同版本的Tensorflow,但是Python 3.5.4。