ValueError:形状必须是秩 2,但对于输入形状的'MatMul'(操作:"MatMul")的秩为 1:[6]、[6]



错误:

valueerror:形状必须为等级2,但具有输入形状的" matmul"(op:'matmul')的等级1:[6],[6]。

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

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

tf.matmul乘以矩阵,张量,具有2个维度。您正在尝试使用Matmul乘以两个具有1个维度的张量的向量。

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

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

否则,如果要执行矩阵乘法,而不是elementwise,则如其他答案中所建议的,您需要通过列矢量为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))

您可以使用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

最新更新