【问题标题】:Why am I getting this ValueError?为什么我会收到这个 ValueError?
【发布时间】:2017-05-12 16:26:30
【问题描述】:

所以这是我的完整理解代码:https://hastebin.com/qigimomika.py .

所以基本上我对以下几行有疑问:

一点上下文:

def weight_variable(shape):
    initial = tensorflow.truncated_normal(shape, stddev=0.01)
    return tensorflow.Variable(initial)

def bias_variable(shape):
    initial = tensorflow.constant(0.01, shape=shape)
    return tensorflow.Variable(initial)

w_layer1 = weight_variable([4, 32])
b_layer1 = bias_variable([32])

input_layer = tensorflow.placeholder("float", [4])

产生错误的那一行:

h_layer1 = tensorflow.add(tensorflow.matmul(input_layer, w_layer1),b_layer1)

当我运行整个代码(如上)时,它会产生以下 ValueError

ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') 
            with input shapes: [4], [4,32].

现在我的问题是:会发生什么以及如何避免这种情况?

感谢您的关注

编辑:感谢 Prune 和 Ali Abbasi。

我的解决方案:我将 input_layer 更改为:

input_layer = tensorflow.placeholder("float", [1, 4])

问题是我的第一个数组是 tensorflow rank 1 ([4]) 和我的第二个数组 rank 2 ([4, 32])。所以我添加了这一行:

state = [state]

输入的状态是:

output_layer.eval(feed_dict={input_layer : state})

状态最初是 [1, 2, 3, 4](排名 1),现在是 [[1, 2, 3, 4]](排名 2)。

谢谢

EDIT2: 好的,自上次 EDIT 以来我改变了很多。我迷失了记录它们的变化。如果您想查看我的代码here 它是。我知道这他妈的乱七八糟。现在我很高兴该死的工作:“D。你将无法理解我的代码,这完全是一团糟,但我只是想记录当前状态。非常感谢Ali Abbasi :D.

【问题讨论】:

  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 感谢您的回复。我稍微改了一下,希望这样没问题。
  • 足够接近了。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。对于 NN,应该这样做。

标签: python error-handling tensorflow


【解决方案1】:

我们在这里,因为您知道MatMul 运算是经典的矩阵乘法运算,所以如果我们想将两个矩阵相乘,M1M2,形状分别为 AxBBxC,我们应该有相同的形状B 当我们想要乘法和结果时:

M1 x M2 生成矩阵 R,形状为 AxC

因此,在您的情况下,您尝试将两个矩阵与形状4x14x32 相乘,因此会引发形状问题的错误,您应该转置第一个张量,然后您有:

1x4 MatMul 4x32 产生1x32 矩阵。

你的代码在这里:

h_layer1 = tensorflow.add(tensorflow.matmul(input_layer, w_layer1),b_layer1)

这样使用:

h_layer1 = tensorflow.add(tensorflow.matmul(tf.transpose(input_layer), w_layer1),b_layer1)

如需更详细的答案,您可以打印每个阶段的张量形状,如:

print h_layer1.get_shape()

查看形状,然后您可以修改形状和输入。

祝你好运。

【讨论】:

  • 好的,再次感谢:D。这不完全是解决方案,但它让我找到了它。我将编辑我的帖子并在那里获得解决方案。
  • 很高兴得到有用的答案:)
猜你喜欢
  • 1970-01-01
  • 2021-04-20
  • 2021-12-04
  • 2022-01-23
  • 2020-12-01
  • 1970-01-01
  • 2020-04-08
  • 2019-07-24
  • 2018-05-04
相关资源
最近更新 更多