Tensorflow feed_dict键不能解释为Tensor

时间:2017-01-19 02:14:03

标签: python tensorflow

我刚开始学习python中的Tensorflow。当我从一个简单的AddTwo类开始时,我收到以下错误。错误消息是:

  

无法将feed_dict键解释为Tensor:Tensor   Tensor(“占位符:0”,dtype = float32)不是此元素   曲线图。

任何人都可以帮我指出正确的方法吗?

import numpy as np
import tensorflow as tf

class AddTwo(object):

    def __init__(self):
        self.graph = tf.Graph()

        with self.graph.as_default():
            self.sess = tf.Session()
            self.X = tf.placeholder(tf.float32)
            self.Y = tf.placeholder(tf.float32)

            # Create an op to add the two placeholders.
            self.Z = tf.add(self.X, self.Y)

    def Add(self, x, y):       
        with tf.Session() as sess:
            #self.Z = tf.add(x, y)
            result = sess.run(self, feed_dict={self.X: x, self.Y: y})
            return result

调用AddTwo类的主代码:

adder = graph.AddTwo()  
print adder.Add(50, 7)
print adder.Add([1,5],[6,7])

1 个答案:

答案 0 :(得分:1)

正如我在评论中建议的那样,你应该用创建的图打开会话,所以代码应该是这样的:

with self.graph.as_default():
    # no session here
    self.X = tf.placeholder(tf.float32)
    self.Y = tf.placeholder(tf.float32)

# open session with providing the graph
with tf.Session(graph=self.graph) as sess:
    pass