使用 numpy 自定义矩阵乘法 [英] custom matrix multiplication with numpy
本文介绍了使用 numpy 自定义矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个奇怪的点积用于 numpy 中的矩阵乘法.对于矩阵A
的一行[1,2,3]
和矩阵B的
,我想用乘积"[4,5,6]
列min(1+4, 2+5, 3+6)
来得到矩阵乘积AB
.>
I want a strange dot product for matrix multiplication in numpy.
For a line [1,2,3]
of matrix A
and a column [4,5,6]
for matrix B
, I wish to use the "product" min(1+4, 2+5, 3+6)
for obtaining the matrix product AB
.
推荐答案
In [498]: A = np.arange(12).reshape(4,3)
In [499]: B = np.arange(4,10).reshape(3,2)
In [500]: A
Out[500]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
In [501]: B
Out[501]:
array([[4, 5],
[6, 7],
[8, 9]])
参考迭代解决方案:
In [504]: res = np.zeros((A.shape[0],B.shape[1]), A.dtype)
...: for i,row in enumerate(A):
...: for j,col in enumerate(B.T):
...: res[i,j] = np.min(row+col)
...:
In [505]: res
Out[505]:
array([[ 4, 5],
[ 7, 8],
[10, 11],
[13, 14]])
使用广播的更快版本:
In [506]: np.min(A[:,:,None]+B[None,:,:], axis=1)
Out[506]:
array([[ 4, 5],
[ 7, 8],
[10, 11],
[13, 14]])
===
证明与矩阵乘积的等价性:
Demonstrate the equivalence to a matrix product:
In [507]: np.dot(A,B)
Out[507]:
array([[ 22, 25],
[ 76, 88],
[130, 151],
[184, 214]])
In [508]: np.sum(A[:,:,None]*B[None,:,:], axis=1)
Out[508]:
array([[ 22, 25],
[ 76, 88],
[130, 151],
[184, 214]])
这篇关于使用 numpy 自定义矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文