两个numpy数组服装乘法的函数
function for two numpy array costume multiplication
我需要一个简单的 numpy 函数来执行此乘法运算而不需要 for 循环 并且更省时。
实际上我想要一个函数将 a
的每一行乘以 b
a=np.arange(2,12).reshape(5,2)
b=np.array([[1,2],[3,4]])
c=np.array([[a[i,:]@b] for i in range(a.shape[0])])
使用 numpy 中的 matmul 函数将两个矩阵相乘。
让我知道这是否有帮助。谢谢。
c = np.matmul(a,b)
使用 numpy einsum you could do (edited to reshape the array based on @dobkind's ):
c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
哪个应该更快。
%timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
与(使用 @
矩阵乘法运算符,在 Python 3 中有效)
%timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
c = np.tensordot(a, b, axes=1)
如果你坚持shape
会是一样的:
c.reshape(5,1,2)
要使用 @
,请将 a
与 (2,2)(或 (1,2,2))成对的 3d 数组 (5,1,2) 通过自动广播).
In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
Out[448]:
array([[[11, 16]],
[[19, 28]],
[[27, 40]],
[[35, 52]],
[[43, 64]]])
In [450]: a[:,None,:]@b
Out[450]:
array([[[11, 16]],
[[19, 28]],
[[27, 40]],
[[35, 52]],
[[43, 64]]])
这实际上比 einsum
解决方案要快一些 - 尽管对于这么小的示例,我不会在时间上花太多时间。
我需要一个简单的 numpy 函数来执行此乘法运算而不需要 for 循环 并且更省时。
实际上我想要一个函数将 a
的每一行乘以 b
a=np.arange(2,12).reshape(5,2)
b=np.array([[1,2],[3,4]])
c=np.array([[a[i,:]@b] for i in range(a.shape[0])])
使用 numpy 中的 matmul 函数将两个矩阵相乘。 让我知道这是否有帮助。谢谢。
c = np.matmul(a,b)
使用 numpy einsum you could do (edited to reshape the array based on @dobkind's
c = np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
哪个应该更快。
%timeit np.einsum('ki,ij->kj', a, b).reshape(5,1,2)
1.87 µs ± 10.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
与(使用 @
矩阵乘法运算符,在 Python 3 中有效)
%timeit np.array([[a[i,:]@b] for i in range(a.shape[0])])
10.2 µs ± 36.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
c = np.tensordot(a, b, axes=1)
如果你坚持shape
会是一样的:
c.reshape(5,1,2)
要使用 @
,请将 a
与 (2,2)(或 (1,2,2))成对的 3d 数组 (5,1,2) 通过自动广播).
In [448]: np.array([[a[i,:]@b] for i in range(a.shape[0])])
Out[448]:
array([[[11, 16]],
[[19, 28]],
[[27, 40]],
[[35, 52]],
[[43, 64]]])
In [450]: a[:,None,:]@b
Out[450]:
array([[[11, 16]],
[[19, 28]],
[[27, 40]],
[[35, 52]],
[[43, 64]]])
这实际上比 einsum
解决方案要快一些 - 尽管对于这么小的示例,我不会在时间上花太多时间。