在tensorflow中无法识别在函数中创建的占位符
我通过点击和试用找到了问题的解决方案,但不明白它为什么有效 我正在经历。我一直运行代码,直到下面的代码块结束,它工作正常在tensorflow中无法识别在函数中创建的占位符,tensorflow,Tensorflow,我通过点击和试用找到了问题的解决方案,但不明白它为什么有效 我正在经历。我一直运行代码,直到下面的代码块结束,它工作正常 W = tf.Variable([.3], tf.float32) b = tf.Variable([-.3], tf.float32) x = tf.placeholder(tf.float32) linear_model = W * x + b y = tf.placeholder(tf.float32) squared_deltas = tf.square(linea
W = tf.Variable([.3], tf.float32)
b = tf.Variable([-.3], tf.float32)
x = tf.placeholder(tf.float32)
linear_model = W * x + b
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
现在,我认为丢失
看起来像是函数中应该包含的东西。我尝试了以下方法
def get_loss(linear_model):
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
return tf.reduce_sum(squared_deltas)
loss = get_loss(linear_model)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
但它给了我一个错误
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Placeholder_26' with dtype float
[[Node: Placeholder_26 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
然后我尝试了以下方法。唯一的区别是我也返回了y
def get_loss(linear_model):
y = tf.placeholder(tf.float32)
squared_deltas = tf.square(linear_model - y)
return y, tf.reduce_sum(squared_deltas)
y, loss = get_loss(linear_model)
print(sess.run(loss, {x:[1,2,3,4], y:[0,-1,-2,-3]}))
成功了。为什么?它不起作用,因为
y
在get\u loss()的范围之外不可见。如果返回底部的y
,则y
现在可见,因此它可以工作
如果您不想返回y,您可以改为在y中输入其名称:
def get_loss(linear_model):
# give y a name 'y'
y = tf.placeholder(tf.float32, name='y')
squared_deltas = tf.square(linear_model - y)
return tf.reduce_sum(squared_deltas)
loss = get_loss(linear_model)
print(sess.run(loss, {x:[1,2,3,4], 'y:0':[0,-1,-2,-3]}))
是关于“y:0”
的“:0”部分的一些讨论,我知道它不在范围之内。那是我的猜测。该字典是否实际使用变量本身作为键?它使用占位符tensor对象或其名称作为键。y只是对张量对象的赋值(名称),这是在代码中访问该对象的唯一方法。