The tensorflow feed_dict key cannot be interpreted as a tensor

I am just starting to learn Tensorflow in python. I got the following error when I start with a simple AddTwo class. error messages:

The feed_dict key cannot be interpreted as a tensor: the tensor ("Placeholder: 0", dtype = float32) is not an element of this graph.

Can someone help me point out the right path for me?

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

which calls the AddTwo class:

adder = graph.AddTwo()  
print adder.Add(50, 7)
print adder.Add([1,5],[6,7])
+4
source share
1 answer

As I suggested in the comment, you should open a session with the created graph, so the code should look something like this:

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
+1
source

Source: https://habr.com/ru/post/1667212/


All Articles