Home > Net >  Python: why does x @ y.T not produce the same output as np.outer(x,y)?
Python: why does x @ y.T not produce the same output as np.outer(x,y)?

Time:11-03

In python, if x,y are vectors, I expected x @ y.T to give me the outer product of x and y, i.e. to match the result of np.outer(x,y). However, to my surprise, x @ y.T returns a scalar. Why? Are vectors (i.e. one-dimensional arrays) not considered to be column vectors by numpy?

For example, the code

import numpy as np

x=np.array([1,2])
y=np.array([3,4])

wrong_answer = x @ y.T 
right_answer = np.outer(x,y)

gives the (interactive) output

In [1]: wrong_answer
Out[1]: 11

In [2]: right_answer
Out[2]: 
array([[3, 4],
       [6, 8]])

CodePudding user response:

The @ takes the dot product, not the outer product.

Using the variables you defined in the code:

>>> x=np.array([1,2])
>>> y=np.array([3,4])
>>> np.dot(x,y)
11

You get 11, which is the dot product that was produced using '@'

EDIT: update from discussion

Based on this answer as well as digging through the PEP465, the @ operator uses __matmul__ under the hood, which is also taking the dot product.

>>> x.__matmul__(y)
11

CodePudding user response:

"Are vectors (i.e. one-dimensional arrays) not considered to be column vectors by numpy?" -> No, you would need to add a dimension. And @ is a dot product, not a multiplication.

You need:

x[:,None]*y

Output:

array([[3, 4],
       [6, 8]])

You can check that transposing a 1D array doesn't change anything:

y.T
array([3, 4])
  • Related