【问题标题】:Tensorflow: Cannot interpret feed_dict key as TensorTensorflow:无法将 feed_dict 键解释为张量
【发布时间】:2017-04-08 16:30:50
【问题描述】:

我正在尝试构建一个具有一个隐藏层(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))

【问题讨论】:

  • graph1 在哪里定义?我在您的代码中没有看到它!

标签: neural-network tensorflow deep-learning


【解决方案1】:

变量 xmodel 不在同一个图中,请尝试将所有这些定义在同一个图范围内。例如,

# 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
# ......

【讨论】:

  • 非常感谢。我做了你提到的改变。但是,我在同一行 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.) 。这是代码pastebin.com/raw/iGZjgEi9
  • 我刚刚检查了损失是一个 int,而不是它应该是一个张量。会尝试解决这个问题。 :)
【解决方案2】:

如果您使用 django 服务器,只需使用 --nothreading 运行服务器即可 例如:

python manage.py runserver --nothreading  

【讨论】:

  • 这适用于我在本地开发的情况,但在生产服务器上一切正常吗?
  • 这很有效,非常适合开发和测试。为了回答上述评论,我完全不鼓励在 HTTP 请求中映射 tensorflow 会话和运行预测。
  • @MattCremeens 不,您不应该在生产中禁用线程。它会削弱您的网络服务器。
【解决方案3】:

这对我有用

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()

【讨论】:

  • 似乎与问题无关
  • 我们永远无法找到该问题的直接答案。即使我有同样的误解,但在找到答案时,我在 git 上找到了答案,我的问题与给定的解决方案完全不同。
  • 它帮我解决了这个问题,似乎和问题有很大关系;)
  • 哇,谢谢您的解决方案。你救了一条命。
  • 有一个遗留项目并得到了这个问题,然后用这个解决方案解决了。你是我的救星
【解决方案4】:

在我的例子中,我在 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

注意:在我的情况下,应用程序第一次运行良好,然后出现上述错误。使用上述修复解决了问题。

希望对您有所帮助。

【讨论】:

  • 发布代码部分时,通过工具栏中的 { } 使用适当的格式
【解决方案5】:

如果您在其with 语句范围之外运行会话,也会出现错误消息TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("...", dtype=dtype) is not an element of this graph。考虑:

with tf.Session() as sess:
    sess.run(logits, feed_dict=feed_dict) 

sess.run(logits, feed_dict=feed_dict)

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

【讨论】:

    【解决方案6】:

    我对烧瓶有同样的问题。将--without-threads 标志添加到flask runthreaded=Falseapp.run() 修复它

    【讨论】:

    • 我想将它们与线程烧瓶服务器一起使用。我应该在一个线程中初始化模型并在另一个线程中运行推理吗?
    • @iratzhash 我认为您需要为此提出另一个问题。我不熟悉 python 上的线程以及如何使用 tensorflow 实现线程安全
    【解决方案7】:

    您还可以在使用托管在 Coursera 等在线学习平台上的笔记本时体验到这一点。因此,实现以下代码可以帮助解决这个问题。

    在 Notebook 文件的最顶部块实现:

    1. 从 keras 导入后端为 K
    2. K.clear_session()

    【讨论】:

      【解决方案8】:

      类似于@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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多