【问题标题】:ValueError: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [6], [6]ValueError:形状必须为 2 级,但对于输入形状为 [6]、[6] 的“MatMul”(操作:“MatMul”)为 1 级
【发布时间】:2019-02-15 06:35:12
【问题描述】:

错误:

ValueError:形状必须为 2 级,但对于输入形状为 [6]、[6] 的“MatMul”(操作:“MatMul”)为 1 级。

import tensorflow as tf

with tf.device('/gpu:1'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
    b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
    c = tf.matmul(a, b)

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))

我不知道怎么了。非常感谢您的帮助。

【问题讨论】:

  • 你期待什么结果?
  • a 和 b 相乘。

标签: tensorflow


【解决方案1】:

tf.matmul 将矩阵、二维张量相乘。您正在尝试使用 matmul 将两个作为 1 维张量的向量相乘。

您的预期结果是[ 1. 4. 9. 16. 25. 36.],这是向量元素的元素乘法。要获得它,您必须使用tf.multiply op。

import tensorflow as tf

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="a")
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name="b")
c = tf.multiply(a, b)

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print(sess.run(c))

【讨论】:

    【解决方案2】:

    否则,如果您想进行矩阵乘法,而不是元素乘法,正如其他答案中所建议的那样,您需要将向量设为 2D 才能将行向量乘以列向量:

    import tensorflow as tf
    a = tf.constant([[1.0], [2.0], [3.0], [4.0], [5.0], [6.0]], name="a") # Shape [6, 1]
    b = tf.constant([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]], name="b") # Shape [1, 6]
    c = tf.matmul(a, b)
    sess = tf.Session(config=tf.ConfigProto(log_device_placement=True)) print(sess.run(c))
    

    【讨论】:

      【解决方案3】:

      您可以使用 tf.expand_dims(a,0) 和 tf.expand_dims(b,1) 来获得 2 级形状。 试试下面的代码:

      a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='a')
      b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='b')
      c = tf.matmul(tf.expand_dims(a,0), tf.expand_dims(b, 1))
      c2=tf.squeeze(c)
      sess=tf.Session()
      print(sess.run(c))
      print(sess.run(c2))enter code here
      

      它将显示:

      [[ 91.]]
      91.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-12
        • 2020-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多