我正在尝试使用Tensorflow编写线性回归代码。但是我遇到一个错误:
> TypeError: Cannot interpret feed_dict key as Tensor: Tensor
> Tensor("Placeholder:0", shape=(?, 3), dtype=float32) is not an element
> of this graph.
也许我在弄混tf.Graph()
了,但是我试图删除这些部分并尝试重新运行,但出现相同的错误。
我的代码:
import numpy as np
import tensorflow as tf
x_data = np.random.randn(2000, 3)
w_real = [0.3, 0.5, 0.1]
b_real = -0.2
noise = np.random.randn(1,2000)*0.1
y_data = np.matmul(w_real, x_data.T) + b_real + noise
NUM_STEPS = 100
g = tf.Graph()
wb = []
with g.as_default():
x = tf.placeholder(tf.float32, shape=[None,3])
y_true = tf.placeholder(tf.float32, shape=None)
with tf.name_scope('inference') as scope:
w = tf.Variable([[0,0,0]], dtype=tf.float32,name='weights')
b = tf.Variable(0, dtype=tf.float32, name='bias')
y_pred = tf.matmul(w,tf.transpose(x)) + b
with tf.name_scope('loss_function') as scope:
loss = tf.reduce_mean(tf.square(y_true-y_pred))
with tf.name_scope('train') as scope:
learning_rate = 0.5
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(NUM_STEPS):
sess.run(train, {x:x_data, y_true:y_data})
if step%10 == 0:
print(step, sess.run([w,b]))
wb.append(sess.run([w,b]))
print("Final Weights: ", wb)
我已经看过Similar Question,但遇到相同的错误。
答案 0 :(得分:1)
每个会话都与一个图形相关联,并且您正在其中创建该会话:
with tf.Session() as sess:
是默认图形,而不是g
。要解决此问题,您只需执行以下操作即可:
with g.as_default(), tf.Session() as sess:
请注意,init
的定义也存在问题,它将是默认图中变量的初始化器-空。改为:
with g.as_default(), tf.Session() as sess:
init = tf.global_variables_initializer()