问题 Could not satisfy explicit device specification '/gpu:X' 的解决方法

tf源码里debug代码时遇到了下面的错误:

tensorflow.python.framework.errors.InvalidArgumentError: Cannot assign a device to node 'box_encodings': Could not satisfy explicit device specification '/device:GPU:0' because no supported kernel for GPU devices is available

原因是tf里的一个bug,解决方法是设置配置里面的allow_soft_placement=True,当运行在出现不允许在GPU运行的时候,可以切换到CPU运行。

一个例子:

import tensorflow as tf

def main():
    with tf.device("/cpu:0"):
        a = tf.Variable(1)
        b = tf.Variable(2)
        c = a + b   
        init_var = tf.global_variables_initializer() 
    with tf.Session() as sess:
        sess.run(init_var)
        sumResult = sess.run(c)
        print(sumResult)

    with tf.device("/gpu:0"):
        a = tf.Variable(1)
        b = tf.Variable(2)
        c = a + b   
        init_var = tf.global_variables_initializer() 
    with tf.Session() as sess:
        sess.run(init_var)
        sumResult = sess.run(c)
        print(sumResult)    

if __name__ == '__main__':
    main()

运行上面的代码,就会遇到Could not satisfy explicit device specification '/gpu:0' 的问题,通过设置allow_soft_placement=True来解决该问题:

    config = tf.ConfigProto(allow_soft_placement=True)

    with tf.Session(config=config) as sess:

解决后的完整代码如下:

import tensorflow as tf

def main():
    with tf.device("/cpu:0"):
        a = tf.Variable(1)
        b = tf.Variable(2)
        c = a + b   
        init_var = tf.global_variables_initializer() 
    with tf.Session() as sess:
        sess.run(init_var)
        sumResult = sess.run(c)
        print(sumResult)

    with tf.device("/gpu:0"):
        a = tf.Variable(1)
        b = tf.Variable(2)
        c = a + b   
        init_var = tf.global_variables_initializer() 
    config = tf.ConfigProto(allow_soft_placement=True)
    with tf.Session(config=config) as sess:
        sess.run(init_var)
        sumResult = sess.run(c)
        print(sumResult)    

if __name__ == '__main__':
    main()


你可能感兴趣的:(Tensorflow)