Tensorflow 无法为具有形状 '(?, 128)' 的 Tensor 'x:0' 提供 shape(1,) 的值

Tensorflow cannot feed the value of shape(1,) for Tensor 'x:0' which has the shape '(?, 128)'

我刚刚浏览了 Stack Overflow 和其他论坛,但没有找到任何对我的问题有帮助的信息。不过好像跟.

有关

我目前有一个经过训练的 Tensorflow 模型(128 个输入和 11 个输出),我按照 Tensorflow 的 MNIST 教程保存了它。

它似乎成功了,我现在在这个文件夹中有一个模型,包含 3 个文件(.meta、.ckpt.data 和 .index)。但是,我想恢复它并将其用于预测:

#encoding[0] => numpy ndarray (128, ) # anyway a list with only one entry
#unknowndata = np.array(encoding[0])[None]
unknowndata = np.expand_dims(encoding[0], axis=0)
print(unknowndata.shape) # Output (1, 128)

# Restore pre-trained tf model
with tf.Session() as sess:
    #saver.restore(sess, "models/model_1.ckpt")
    saver = tf.train.import_meta_graph('models/model_1.ckpt.meta')
    saver.restore(sess,tf.train.latest_checkpoint('models/./'))
    y = tf.get_collection('final tensor') # tf.nn.softmax(tf.matmul(y2, W3) + b3)
    X = tf.get_collection('input') # tf.placeholder(tf.float32, [None, 128])

    # W1 = tf.get_collection('vars')[0]
    # b1 = tf.get_collection('vars')[1]
    # W2 = tf.get_collection('vars')[2]
    # b2 = tf.get_collection('vars')[3]
    # W3 = tf.get_collection('vars')[4]
    # b3 = tf.get_collection('vars')[5]

    # y1 = tf.nn.relu(tf.matmul(X, W1) + b1)
    # y2 = tf.nn.relu(tf.matmul(y1, W2) + b2)
    # yLog = tf.matmul(y2, W3) + b3
    # y = tf.nn.softmax(yLog)

    prediction = tf.argmax(y, 1)

    print(sess.run(prediction, feed_dict={i: d for i,d in zip(X, unknowndata.T)}))
    # also had sess.run(prediction, feed_dict={X: unknowndata.T}) and also not transposed, still errors

# Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # one should be 1 obviously with a specific percentage

那里我只有运行个问题...

ValueError: Cannot feed value of shape (1,) for Tensor 'x:0', which has shape '(?, 128)' Altough I print the shape of the 'unknowndata' and it matches the (1, 128). I also tried it with

sess.run(prediction, feed_dict={X: unknownData})) # with transposed etc. but nothing worked for me there I got the other error

TypeError: unhashable type: 'list'

我只想要这个漂亮的 Tensorflow 训练模型的一些预测。

我找到问题了! 首先,我需要恢复所有的值(权重和偏差并分别对它们进行矩阵运算)。 其次,我需要创建与训练模型相同的输入,在我的例子中:

X = tf.placeholder(tf.float32, [None, 128])

然后调用预测:

sess.run(prediction, feed_dict={X: unknownData})

但我没有得到任何百分比分布,但我预计这是由于 softmax 函数。有人知道如何访问这些吗?

prediction张量是通过y上的argmax得到的。您可以在执行 sess.run.

时将 y 添加到输出提要,而不是仅返回 prediction
output_feed = [prediction, y]
preds, probs = sess.run(output_feed, print(sess.run(prediction, feed_dict={i: d for i,d in zip(X, unknowndata.T)}))

preds 将得到模型的预测,probs 将得到概率分数。

首先,当你保存时,你必须将你需要的占位符添加到集合中 tf.add_to_collection('i', i) 然后检索它们并将它们传递给 feed_dict.

在你的例子中是"i":

i = tf.get_collection('i')[0]
#sess.run(prediction, feed_dict={i: d for i,d in zip(X, unknowndata.T)})