什么是 tensorflow float ref?

What is a tensorflow float ref?

尝试运行以下基本示例运行条件计算我收到以下错误消息:

'x' was passed float incompatible with expected float_ref

什么是 tensorflow float_ref 以及如何修改代码?

import tensorflow as tf
from tensorflow.python.ops.control_flow_ops import cond

a = tf.Variable(tf.constant(0.),name="a")
b = tf.Variable(tf.constant(0.),name="b")
x = tf.Variable(tf.constant(0.),name="x")

def add():
    x.assign( a + b)
    return x

def last():
    return x

calculate= cond(x==0.,add,last)

with tf.Session() as s:
    val = s.run([calculate], {a: 1., b: 2., x: 0.})
    print(val) # 3
    val=s.run([calculate],{a:4.,b:5.,x:val})
    print(val) # 3

这并没有解释什么是 float_ref,但它解决了以下问题:

1) 需要在会话中创建变量 2) 赋值操作不是我们所期望的

此固定代码有效:

def add():
    print("add")
    x = a + b
    return x

def last():
    print("last")
    return x

with tf.Session() as s:
    a = tf.Variable(tf.constant(0.),name="a")
    b = tf.Variable(tf.constant(0.),name="b")
    x = tf.constant(-1.)
    calculate= cond(x.eval()==-1.,add,last)
    val = s.run([calculate], {a: 1., b: 2.})
    print(val) # 3
    print(s.run([calculate],{a:3.,b:4.})) # 7
    print(val) # 3

仅供参考。 我遇到了类似的错误,我的错误是:

node GradientDescent/update_input/ApplyGradientDescent was passed float from _arg_input_0_1:0 incompatible with expected float_ref.

发生这种情况是因为在我的节点树中某处我有一个 tf.Variable 而不是 t.fplaceholder。用占位符替换变量后,它起作用了。

float_ref 这里指的是对浮点数的引用,即你的 Tensorflow 浮点变量 x.

here所述,您遇到此错误是因为您不能在同一会话中同时将变量作为feed_dict分配和传递运行 就像你在这个声明中所做的那样:

val = s.run([calculate], {a: 1., b: 2., x: 0.})

当您解析该语句以结束时,它变得更加明显:

val = s.run([x.assign( a + b)], {a: 1., b: 2., x: 0.})

改变

a = tf.Variable(tf.constant(0.),name="a")
b = tf.Variable(tf.constant(0.),name="b")
x = tf.Variable(tf.constant(0.),name="x")

def add():
    x.assign( a + b)
    return x

至:

    a = tf.placeholder(dtype=tf.float32,name="a")
    b = tf.placeholder(dtype=tf.float32,name="b")
    x = tf.placeholder(dtype=tf.float32,name="x")
    def add():
        x= a + b
        return x