Tensorflow:无法将feed_dict键解释为Tensor
deep-learning
neural-network
tensorflow
6
0

我正在尝试建立一个具有一个隐藏层(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))
参考资料:
Stack Overflow
收藏
评论
共 5 个回答
高赞 时间 活跃

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

# 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
# ......
收藏
评论

就我而言,我在多次调用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

注意:就我而言,该应用程序也第一次运行正常,然后出现了以上错误。使用以上修复程序解决了该问题。

希望能有所帮助。

收藏
评论

这对我有用

from keras import backend as K

在预测了我的数据之后,我插入了这部分代码,然后再次加载了模型。

K.clear_session()

我在生产服务器中遇到了此问题,但是在我的PC上运行正常

......

from keras import backend as K

#Before prediction
K.clear_session()

#After prediction
K.clear_session()
收藏
评论

错误消息TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("...", dtype=dtype) is not an element of this graph如果您在其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命令将正常执行,但是第二个命令将引发上述错误。

收藏
评论

如果您使用的是django服务器,则只需运行带有--nothreading服务器即可:

python manage.py runserver --nothreading  
收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号