gpt4 book ai didi

python - 向量、矩阵乘法和求和

转载 作者:行者123 更新时间:2023-12-01 00:42:55 27 4
gpt4 key购买 nike

我正在绕着numpy/scipy中的所有选项转圈。点积、乘法、matmul、tensordot、einsum 等

我想将一维向量与二维矩阵(这将是稀疏csr)相乘并对结果求和,这样我就有了一个一维向量

例如

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.matrixA1 将其展平为一维 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)

关于python - 向量、矩阵乘法和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57210645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com