我试图将一组向量与相应的矩阵相乘,并希望在结尾处对得到的向量求和 . 作为一个简单的例子,让我们假设我们有20个矢量和矩阵分别为10x1和150x1:
import numpy as np
np_b=[ np.random.rand(10) for i in range(20)]
np_A=[ np.random.rand(150,10) for i in range(20)]
#first we multiply each vector with it's corresponding matrix
np_allMuls=np.array([np.dot(np_A[i],np_b[i]) for i in range(20)] )
#then we sum all of the vectors to get the 150 dimensional sum vector
np_allSum=np.sum( np_allMuls,axis=0 )
到目前为止,我已得到张量流0.10:
import tensorflow as tf
tf_b = tf.placeholder("float", [None,10])
tf_A= tf.placeholder("float", [None,150,10])
#the following gives me ValueError: Shape (?, 150, 10) must have rank 2
tf_allMuls=tf.matmul(tf_A,tf_b)
但是这个符号乘法给出了错误“ValueError:Shape(?,150,10)必须具有等级2” .
有谁知道为什么我收到这样的错误信息?我怎样才能正确获得tf_allMuls?
1 回答
从tf.matmul的文档:
考虑到您使用
None
作为占位符的第一个参数,第二个选项与您相关,即"batches of matrices" . 但是你的tf_b
是一批向量,而不是矩阵,所以两个矩阵的等级不一样,这就是你得到错误的原因 . 您应该使用:因此似乎
matmul
无法广播(可能会检查此post)并且我同意您收到的错误消息有点误导 .这是一个简单的例子:
打印
另请注意,
tf.matmul
的参数顺序非常重要,就像您习惯于实际的矩阵乘法一样 . 所以虽然这样不工作,以下会(当然,它不是计算相同的东西,但它不会引发错误):