Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the multiplication operator actually doing with numpy arrays? [duplicate]

Tags:

python

numpy

I am learning NumPy and I am not really sure what is the operator * actually doing. It seems like some form of multiplication, but I am not sure how is it determined. From ipython:

In [1]: import numpy as np  In [2]: a=np.array([[1,2,3]])  In [3]: b=np.array([[4],[5],[6]])  In [4]: a*b Out[4]:  array([[ 4,  8, 12],        [ 5, 10, 15],        [ 6, 12, 18]])  In [5]: b*a Out[5]:  array([[ 4,  8, 12],        [ 5, 10, 15],        [ 6, 12, 18]])  In [6]: b.dot(a) Out[6]:  array([[ 4,  8, 12],        [ 5, 10, 15],        [ 6, 12, 18]])  In [7]: a.dot(b) Out[7]: array([[32]]) 

It seems like it is doing matrix multiplication, but only b multiplied by a, not the other way around. What is going on?

like image 408
Karel Bílek Avatar asked Aug 17 '13 22:08

Karel Bílek


People also ask

What happens when you multiply an array in Python?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

What happens when you multiply two arrays?

C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.

What happens when you multiply two NP arrays?

Multiply two numpy arraysIt returns a numpy array of the same shape with values resulting from multiplying values in each array elementwise. Note that both the arrays need to have the same dimensions.


1 Answers

It's a little bit complicated and has to do with the concept of broadcasting and the fact that all numpy operations are element wise.

  1. a is a 2D array with 1 row and 3 columns and b is a 2D array with 1 column and 3 rows.
  2. If you try to multiply them element by element (which is what numpy tries to do if you do a * b because every basic operation except the dot operation is element wise), it must broadcast the arrays so that they match in all their dimensions.
  3. Since the first array is 1x3 and the second is 3x1 they can be broadcasted to 3x3 matrix according to the broadcasting rules. They will look like:
a = [[1, 2, 3],      [1, 2, 3],      [1, 2, 3]]  b = [[4, 4, 4],      [5, 5, 5],      [6, 6, 6]] 

And now Numpy can multiply them element by element, giving you the result:

[[ 4,  8, 12],  [ 5, 10, 15],  [ 6, 12, 18]] 

When you are doing a .dot operation it does the standard matrix multiplication. More in docs

like image 127
Viktor Kerkez Avatar answered Oct 08 '22 13:10

Viktor Kerkez