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?
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.
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.
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.
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.
a
is a 2D array with 1 row and 3 columns and b
is a 2D array with 1 column and 3 rows.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.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With