Oct*_*ami 158 python operators matrix-multiplication python-3.x python-3.5
我知道@是装饰器,但@=Python的用途是什么?这只是对未来想法的保留吗?
这只是我阅读时的众多问题之一tokenizer.py.
rig*_*old 176
的
@(在)操作者意图被用于矩阵乘法.没有内置的Python类型实现此运算符.
该@操作符是在Python 3.5中引入的.@=正如您所期望的那样,是矩阵乘法,然后是赋值.它们映射到__matmul__,__rmatmul__或__imatmul__类似于如何+和+=映射__add__,__radd__或__iadd__.
PEP 465详细讨论了运营商及其背后的基本原理.
And*_*bis 48
@=并且@是Python 3.5中引入的新运算符,执行矩阵乘法.它们旨在澄清迄今为止与运算符存在的混淆,运算符*用于元素乘法或矩阵乘法,这取决于特定库/代码中采用的约定.因此,将来,运算符*仅用于逐元素乘法.
如PEP0465中所述,引入了两个运营商:
A @ B,类似于A * BA @= B,类似于A *= B为了快速突出差异,对于两个矩阵:
A = [[1, 2], B = [[11, 12],
[3, 4]] [13, 14]]
Run Code Online (Sandbox Code Playgroud)
元素乘法将产生:
A * B = [[1 * 11, 2 * 12],
[3 * 13, 4 * 14]]
Run Code Online (Sandbox Code Playgroud)矩阵乘法将产生:
A @ B = [[1 * 11 + 2 * 13, 1 * 12 + 2 * 14],
[3 * 11 + 4 * 13, 3 * 12 + 4 * 14]]
Run Code Online (Sandbox Code Playgroud)到目前为止,Numpy使用了以下约定:
的*操作者(和算术运算符在普通)被定义为在元件为单位的运算ndarrays并作为矩阵乘法numpy.matrix类型.
方法/函数 dot用于ndarrays的矩阵乘法
引入@运算符使得涉及矩阵乘法的代码更容易阅读.PEP0465给我们举了一个例子:
# Current implementation of matrix multiplications 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))
# Current implementation of matrix multiplications using dot method
S = (H.dot(beta) - r).T.dot(inv(H.dot(V).dot(H.T))).dot(H.dot(beta) - r)
# Using the @ operator instead
S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)
Run Code Online (Sandbox Code Playgroud)
显然,最后一个实现更容易阅读和解释为一个等式.
ame*_*hta 10
@是Python3.5中新增的矩阵乘法运算符
参考:https://docs.python.org/3/whatsnew/3.5.html#whatsnew-pep-465
例子
C = A @ B
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26436 次 |
| 最近记录: |