摘要
在 Python 3.5 中,矩阵乘法函数 numpy.matmul 遵循 PEP465,引入了 @ 运算符。
规范
运算符 | 优先级 / 结合性 | 方法 |
---|---|---|
@ | 与 * 相同 | __matmul__, __rmatmul__ |
@= | N/A | __imatmul__ |
问题
当我们进行如公式 S=(Hβ−r)T(HVHT)−1(Hβ−r) (各种变量都是矢量或矩阵)的运算时:
使用
numpy.dot()
函数:1
2# Using dot function:
S = np.dot((np.dot(H, beta) - r).T, np.dot(inv(np.dot(np.dot(H, V), H.T)), np.dot(H, beta) - r))使用
numpy.ndarray
对象的.dot()
方法1
2# Using dot method:
S = (H.dot(beta) - r).T.dot(inv(H.dot(V).dot(H.T))).dot(H.dot(beta) - r)使用
@
运算符1
2# Using @ operator:
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)
我们能明显看出使用@
运算符写出的等式更加接近数学公式的形式。
用例
a, b 均为 2*2 的列表时:
1
2
3
4
5
6
7
8
9
10
11
121, 0], [0, 1]] a = [[
4, 1], [2, 2]] b = [[
# Using dot function:
np.dot(a, b)
array([[4, 1],
[2, 2]])
# Using dot method:
a.dot(b)
AttributeError: 'list' object has no attribute 'dot'
# Using @ operator:
a @ b
TypeError: unsupported operand type(s) for @: 'list' and 'list'a, b 均为二维矩阵时:
1
2
3
4
5
6
7
8
9
10
11
12
13
14a = np.array([[1, 0], [0, 1]])
b = np.array([[4, 1], [2, 2]])
# Using dot function:
np.dot(a, b)
array([[4, 1],
[2, 2]])
# Using dot method:
a.dot(b)
array([[4, 1],
[2, 2]])
# Using @ operator:
a @ b
array([[4, 1],
[2, 2]])