与向量十相乘的结果

2024-05-23 19:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用相应的矩阵乘以一组向量,最后求出向量的总和。作为一个numpy示例,假设我们有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 )

到目前为止,对于tensorflow 0.10,我得到:

^{pr2}$

但是这个符号乘法给了我一个错误“ValueError:Shape(?)?,150,10)必须具有等级2“。在

有人知道我为什么收到这样的错误信息吗?我怎样才能正确地得到tf\u allMuls?在


Tags: theinnumpyfornprange矩阵random
1条回答
网友
1楼 · 发布于 2024-05-23 19:25:06

来自tf.matmul的文档:

The inputs must be matrices (or tensors of rank > 2, representing batches of matrices), with matching inner dimensions, possibly after transposition.

考虑到您使用None作为占位符的第一个参数,第二个选项与您相关,即“矩阵的批处理”。但是你的tf_b是一批向量,而不是矩阵,所以这两个矩阵的秩是不一样的,这就是为什么会出现错误。您应该改用:

tf_b = tf.placeholder("float", [None, 10, 1])
tf_A = tf.placeholder("float", [None, 150, 10])
tf_allMuls = tf.matmul(tf_A, tf_b)

因此,matmul似乎无法广播(可能要检查这个post),我同意您得到的错误消息有点误导。在

下面是一个简单的例子:

^{pr2}$

哪个指纹

[[[ 14.]
  [ 32.]
  [ 50.]]]

还要注意tf.matmul参数的顺序很重要,就像你习惯于从实际的矩阵乘法。所以在这个时候

tf_b = tf.placeholder("float", [None, 1, 3])
tf_A = tf.placeholder("float", [None, 3, 3])
tf_allMuls = tf.matmul(tf_A, tf_b)

不起作用,以下将(当然,它不是在计算相同的东西,但它不会引发错误):

tf_b = tf.placeholder("float", [None, 1, 3])
tf_A = tf.placeholder("float", [None, 3, 3])
tf_allMuls = tf.matmul(tf_b, tf_A)

相关问题 更多 >