Python 中真的有@运算符来计算点积吗?
Is there really an @ operator in Python to calculate dot product?
这个答案是否正确: ?
引用那个答案。
In Python 3.5, there is a new operator for the dot product, so you
can write a= A @ B instead of a= numpy.dot(A,B)
它似乎不适合我。
$ python3
Python 3.6.1 (default, Apr 4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a @ b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for @: 'list' and 'list'
>>>
但是链接的答案已经获得了 6 个赞成票,所以我一定遗漏了什么。您能否提供一个完整的示例来说明如何使用 @
运算符计算点积?
参见what's new in Python 3.5, section matrix mult (PEP 465):
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.
因此,您必须自己实施这些方法。
或者,使用已经支持新运算符的numpy>=1.10
:
>>> import numpy
>>> x = numpy.ones(3)
>>> m = numpy.eye(3)
>>> x @ m
array([ 1., 1., 1.])
这个答案是否正确: ?
引用那个答案。
In Python 3.5, there is a new operator for the dot product, so you can write a= A @ B instead of a= numpy.dot(A,B)
它似乎不适合我。
$ python3
Python 3.6.1 (default, Apr 4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a @ b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for @: 'list' and 'list'
>>>
但是链接的答案已经获得了 6 个赞成票,所以我一定遗漏了什么。您能否提供一个完整的示例来说明如何使用 @
运算符计算点积?
参见what's new in Python 3.5, section matrix mult (PEP 465):
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.
因此,您必须自己实施这些方法。
或者,使用已经支持新运算符的numpy>=1.10
:
>>> import numpy
>>> x = numpy.ones(3)
>>> m = numpy.eye(3)
>>> x @ m
array([ 1., 1., 1.])