Tensorflow feed_dict key 不能解释为 Tensor [英] Tensorflow feed_dict key cannot be interpreted as Tensor

查看:25
本文介绍了Tensorflow feed_dict key 不能解释为 Tensor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

无法将 feed_dict 键解释为张量:张量Tensor("Placeholder:0", dtype=float32) 不是这个元素图表.

Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", dtype=float32) is not an element of this graph.

谁能帮我指出正确的方法?

Can anyone help me to point out the correct way 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

调用 AddTwo 类的主要代码:

main code that calls the AddTwo class:

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

推荐答案

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

As I suggested in comment, you should open the session with created graph, so code should be 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

这篇关于Tensorflow feed_dict key 不能解释为 Tensor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆