Tensorflow:无法将feed_dict键解释为张量。

31

我正在尝试构建一个具有一个隐藏层(1024个节点)的神经网络模型。这个隐藏层只是一个ReLU单元。我还将输入数据分批处理,每批128个。

输入是28 * 28大小的图像。在下面的代码中,我在第

_, c = sess.run([optimizer, loss], feed_dict={x: batch_x, y: batch_y})
Error: TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder_64:0", shape=(128, 784), dtype=float32) is not an element of this graph.

这是我写的代码

#Initialize

batch_size = 128

layer1_input = 28 * 28
hidden_layer1 = 1024
num_labels = 10
num_steps = 3001

#Create neural network model
def create_model(inp, w, b):
    layer1 = tf.add(tf.matmul(inp, w['w1']), b['b1'])
    layer1 = tf.nn.relu(layer1)
    layer2 = tf.matmul(layer1, w['w2']) + b['b2']
    return layer2

#Initialize variables
x = tf.placeholder(tf.float32, shape=(batch_size, layer1_input))
y = tf.placeholder(tf.float32, shape=(batch_size, num_labels))

w = {
'w1': tf.Variable(tf.random_normal([layer1_input, hidden_layer1])),
'w2': tf.Variable(tf.random_normal([hidden_layer1, num_labels]))
}
b = {
'b1': tf.Variable(tf.zeros([hidden_layer1])),
'b2': tf.Variable(tf.zeros([num_labels]))
}

init = tf.initialize_all_variables()
train_prediction = tf.nn.softmax(model)

tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)

model = create_model(x, w, b)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model, y))    
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#Process
with tf.Session(graph=graph1) as sess:
    tf.initialize_all_variables().run()
    total_batch = int(train_dataset.shape[0] / batch_size)

    for epoch in range(num_steps):    
        loss = 0
        for i in range(total_batch):
            batch_x, batch_y = train_dataset[epoch * batch_size:(epoch+1) * batch_size, :], train_labels[epoch * batch_size:(epoch+1) * batch_size,:]

            _, c = sess.run([optimizer, loss], feed_dict={x: batch_x, y: batch_y})
            loss = loss + c
        loss = loss / total_batch
        if epoch % 500 == 0:
            print ("Epoch :", epoch, ". cost = {:.9f}".format(avg_cost))
            print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
            valid_prediction = tf.run(tf_valid_dataset, {x: tf_valid_dataset})
            print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))
    test_prediction = tf.run(tf_test_dataset,  {x: tf_test_dataset})
    print("TEST accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

1
图表1在哪里定义的?我在你的代码中没有看到它! - Pannag Sanketi
8个回答

68

这对我起作用了

from keras import backend as K

在预测完我的数据后,我插入了以下代码,然后重新加载了模型。

K.clear_session()

我在生产服务器上遇到了这个问题,但在我的电脑上它正常运行。

from keras import backend as K

#Before prediction
K.clear_session()

#After prediction
K.clear_session()

1
似乎与问题无关 - Andrii Muzalevskyi
4
我们永远无法直接找到答案。即使我也有同样的误解,但在寻找答案时,我在 git 上找到了它,发现我的问题与给出的解决方案完全不同。 - yunus
9
它帮助我解决了这个问题,看起来与这个问题非常相关 ;) - trust512
2
有一个遗留项目,遇到了这个问题,然后用这个解决方案解决了。你是我的救星。 - Adiyat Mubarak
@yunus 我尝试了你的方法,但是它给我返回了以下错误信息:"AttributeError: 'History'对象没有'predict'属性"。 - waleeds37
一小段代码片段可能有助于诊断您的用例,因为这对其他人有效过。 - yunus

17

变量x不在同一张图中,与model不在同一个计算图中,请尝试在相同的计算图范围内定义它们。例如:

# define a graph
graph1 = tf.Graph()
with graph1.as_default():
    # placeholder
    x = tf.placeholder(...)
    y = tf.placeholder(...)
    # create model
    model = create(x, w, b)

with tf.Session(graph=graph1) as sess:
# initialize all the variables
sess.run(init)
# then feed_dict
# ......

1
非常感谢。我已经按照您提到的更改进行了修改。但是,我在相同的行“sess.run(.., feed_dict=...)”中没有得到以下错误:“Fetch argument 0 has invalid type <type 'int'>, must be a string or Tensor. (Can not convert a int into a Tensor or Operation.)”。这是代码:http://pastebin.com/raw/iGZjgEi9 - Pratyush
我刚刚检查了一下,发现损失值应该是张量(Tensor),而不是整数(int)。我会尝试修复这个问题。 :) - Pratyush

15
如果你使用 Django 服务器,只需使用 --nothreading 运行 runserver 命令,例如:
python manage.py runserver --nothreading  

这在我本地开发时可行,但在生产服务器上一切都会没问题吗? - Matt Cremeens
1
这个很好用,非常适合开发和测试。回答上面的评论,我会毫不犹豫地劝阻在HTTP请求中映射tensorflow会话并运行预测。 - Chris Conlan
@MattCremeens 不,你不应该在生产环境中禁用线程。这会使你的Web服务器瘫痪。 - Chris Conlan

5

我在使用flask时遇到了相同的问题。将--without-threads标志添加到flask run 或将threaded=False添加到app.run()中均可解决该问题。


我想在一个线程化的Flask服务器中使用它们。我应该在一个线程中初始化模型并在另一个线程中运行推理吗? - Irtaza
@iratzhash 我认为你需要针对这个问题提出另一个问题。我不熟悉Python上的线程以及如何使用TensorFlow实现线程安全。 - ahmadali shafiee
@iratzhash 嘿,你解决了这个问题吗?你在使用什么多线程 Flask 和 Tensorflow 1?Tensorflow Serving? - MrR

3
在我的情况下,我在多次调用CNN时使用了循环,我通过以下方式解决了我的问题:
# Declare this as global:

global graph

graph = tf.get_default_graph()

# Then just before you call in your model, use this

with graph.as_default():

# call you models here

注意:在我的情况下,应用程序第一次运行正常,然后出现了上述错误。使用上述修复方法解决了这个问题。
希望这有所帮助。

在发布代码段时,请使用工具栏中的 { } 进行适当的格式设置。 - NitinSingh

2

如果你在像Coursera这样的在线学习平台上使用笔记本电脑,也可以遇到这个问题。因此,实施以下代码可能有助于解决问题。

将以下代码实施在笔记本文件的最顶部块:

  1. from keras import backend as K
  2. K.clear_session()

2
错误信息 TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("...", dtype=dtype) is not an element of this graph 也可能出现在您在其 with 语句范围之外运行会话的情况下。请考虑:
with tf.Session() as sess:
    sess.run(logits, feed_dict=feed_dict) 

sess.run(logits, feed_dict=feed_dict)

如果logitsfeed_dict被正确定义,第一个sess.run命令将正常执行,但第二个命令将引发上述错误。

0

与@javan-peymanfard和@hmadali-shafiee类似,当在API中加载模型时我遇到了这个问题。我正在使用FastAPI和uvicorn。为了解决这个问题,我只需将API函数定义设置为async,就像这样:

@app.post('/endpoint_name')
async def endpoint_function():
    # Do stuff here, including possibly (re)loading the model

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接