最近看到使用@来代替矩阵乘法的写法,查了一下python相关的官方文档之后看到如下内容:

PEP 465 adds the @ infix operator for matrix multiplication. Currently, no builtin Python types implement the new 
operator, however, it can be implemented by defining __matmul__(), __rmatmul__(), and __imatmul__() for regular, 
reflected, and in-place matrix multiplication. The semantics of these methods is similar to that of methods 
defining other infix arithmetic operators.

其中提到了__matmul__() __rmatmul__() __imatmul__()这三个函数,但是并没有进一步详细的介绍与使用说明。
所以自己做了些实验,下面是具体的用法说明。

python : 3.8.3
numpy: 1.22.3

首先,测试代码如下:

import numpy as np

a = np.reshape(np.arange(1, 5), (2, 2))
b = np.reshape(np.arange(4, 0, -1), (2, 2))

"""
a:
[[1 2] 
[3 4]]
b:
[[4 3]
[2 1]]
"""
print(a.__matmul__(b))
print(a.__rmatmul__(b))
输出结果为:
[[ 8  5]
 [20 13]]
[[13 20]
 [ 5  8]]

可以看到,a.__matmul__(b)的作用就是返回a、b矩阵乘积的结果,而a.__rmatmul__(b)返回的是b、a矩阵乘积的结果。

a.__matmul__(b)的作用跟np.matmul(a, b)相同,而a.__rmatmul__(b)的作用与np.matmul(b, a)相同。

然后,__imatmul__()函数在我使用的python3.8版本中已经取消。

取而代之的是__imul__()函数,同时,还有__mul__()、__rmul__(),这三个函数的作用相同,都是计算a与b矩阵的内积,这也是字母i的含义,i表示in-place
测试代码如下:

......
print(a.__rmul__(b))
print(a.__mul__(b))
print(a.__imul__(b))
输出结果为:
[[4 6]
 [6 4]]
[[4 6]
 [6 4]]
[[4 6]
 [6 4]]
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐