【问题标题】:Tensorflow: Tensor Tensor("Placeholder:0", shape=(?, 3), dtype=float32) is not an element of this graphTensorflow:Tensor Tensor("Placeholder:0", shape=(?, 3), dtype=float32) 不是此图的元素
【发布时间】:2019-09-24 23:47:56
【问题描述】:

我正在尝试使用 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,但遇到了同样的错误。

【问题讨论】:

    标签: python python-3.x tensorflow


    【解决方案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()
    

    【讨论】:

    • 谢谢。确实问题出在init = tf.global_variables_initializer()
    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 2020-06-09
    • 2019-09-17
    • 2019-10-23
    • 2018-04-27
    • 1970-01-01
    • 2018-04-25
    • 2021-09-23
    相关资源
    最近更新 更多