Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there really an @ operator in Python to calculate dot product?

Is this answer correct: https://stackoverflow.com/a/39662710/1175080 ?

Quoting that answer.

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)

It does not seem to work for me.

$ 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'
>>>

But the linked answer has received 6 upvotes, so I must be missing something. Can you provide a complete example that shows how to use the @ operator to calculate a dot product?

like image 449
Lone Learner Avatar asked Aug 01 '17 16:08

Lone Learner


People also ask

Is there a dot product function in Python?

Python provides a very efficient method to calculate the dot product of two vectors. By using numpy. dot() method which is available in the NumPy module one can do so.

How do you do dot product in Python?

In Python, one way to calulate the dot product would be taking the sum of a list comprehension performing element-wise multiplication. Alternatively, we can use the np. dot() function. Keeping to the convention of having x and y as column vectors, the dot product is equal to the matrix multiplication xTy x T y .

How do you find the dot product of a list in Python?

We can calculate the dot product of lists of equal length using the zip() function and the sum() function. The zip function returns a zip object by combining elements in a sequence of tuples from both iterables. On the other hand, the sum function returns the sum of items in iterables such as lists.

How do you take the dot product of a vector in Python?

To return the dot product of two vectors, use the numpy. vdot() method in Python.


1 Answers

See 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.

So, you would have to implement those methods yourself.

Or, use numpy>=1.10 which already has support for the new operator:

>>> import numpy
>>> x = numpy.ones(3)
>>> m = numpy.eye(3)
>>> x @ m
array([ 1., 1., 1.])
like image 120
randomir Avatar answered Sep 18 '22 17:09

randomir