[英]vector, matrix multiplication and sum
我正在用numpy
/ scipy
所有选项scipy
。 点积,乘法,matmul,张量点,einsum等
我想将1d向量与2d矩阵相乘(这将是稀疏的csr)并求和结果,所以我得到了1d向量
例如
oneDarray = np.array([1, 2, 3])
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
# multiple and sum the oneDarray against the rows of the matrix
# eg 1*1 + 1*2 + 1*3 = 6, 2*4 + 2*5 + 2*6 = 30, 3*7 + 3*8 + 3*9 = 42
so output we be [6,30,53]
# multiple and sum the oneDarray against the columns of the matrix
# eg 1*1 + 1*4 + 1*7 = 28, 2*2 + 2*5 + 2*8 = 30, 3*3 + 3*6 + 3*9 = 486
so output we be [28,30,486]
任何帮助将不胜感激。
# 1*1 + 1*2 + 1*3 = 6, 2*4 + 2*5 + 2*6 = 30, 3*7 + 3*8 + 3*9 = 42
1*1 + 1*2 + 1*3 = 6
2*4 + 2*5 + 2*6 = 30,
3*7 + 3*8 + 3*9 = 42
1*(1 + 2 + 3) = 6,
2*(4 + 5 + 6) = 30,
3*(7 + 8 + 9) = 42
因此,可以通过几种方式进行计算:
In [92]: oneDarray*(matrix.sum(axis=1))
Out[92]: array([ 6, 30, 72])
In [93]: np.einsum('i,ij->i', oneDarray, matrix)
Out[93]: array([ 6, 30, 72])
In [94]: (oneDarray[:,None]*matrix).sum(axis=1)
Out[94]: array([ 6, 30, 72])
它不适合通常的dot
(矩阵)乘积,后者具有einsum
表达式,如ij,j->i
(对错误的索引求和)。
另一个表达式是(您的值是错误的,除了中间一个):
In [95]: matrix.sum(axis=0)*oneDarray
Out[95]: array([12, 30, 54])
如果矩阵是稀疏的csr:
In [96]: M = sparse.csr_matrix(matrix)
In [97]: M
Out[97]:
<3x3 sparse matrix of type '<class 'numpy.int64'>'
with 9 stored elements in Compressed Sparse Row format>
In [98]: M.sum(axis=1)
Out[98]:
matrix([[ 6],
[15],
[24]])
In [99]: M.sum(axis=1).A1*oneDarray
Out[99]: array([ 6, 30, 72])
sum
是(3,1) np.matrix
。 A1
平为1d ndarray
,从而使元素明智的乘法更加容易。
In [103]: M.sum(axis=0)
Out[103]: matrix([[12, 15, 18]], dtype=int64)
In [104]: M.sum(axis=0).A1*oneDarray
Out[104]: array([12, 30, 54], dtype=int64)
In [116]: np.multiply(M.sum(0), oneDarray)
Out[116]: matrix([[12, 30, 54]], dtype=int64)
好吧,您的问题中存在一些计算错误。第一个将导致[6, 30, 72]
,第二个部分将导致[12, 30, 54]
。 如果我理解正确,第一个可以解决
np.sum(oneDarray * matrix.T, axis=0)
第二部分
np.sum(np.multiply(matrix, oneDarray), axis=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.