[PYTHON] Behavior of numpy.dot when passing 1d array and 2d array

Question

>>> a = np.array([1,2,3])
>>> b = np.array([2,3,4])
>>> np.dot(a, b)
20
>>> A = np.array([[1,2],[2,3],[3,4]]) # 3x2
>>> B = np.array([[1,2,3],[2,3,4]]) # 2x3
>>> np.dot(A, B)
array([[ 5,  8, 11],
       [ 8, 13, 18],
       [11, 18, 25]])

As shown above, numpy.dot with two 1d arrays gives an inner product, and two 2d arrays gives a matrix product, What if I pass one 1d array and one 2d array?

Verification

Pass 1d array as the first argument

>>> A = np.array([[1,2],[2,3],[3,4]]) # 3x2
>>> b = np.array([1,2,3])
>>> np.dot(b, A)
array([14, 20])

The 3D 1d array passed as the first argument, b, is treated like a 1x3 2d array. The matrix product is converted to a 1d array and returned.

>>> A = np.array([[1,2],[2,3],[3,4]]) # 3x2
>>> B = np.array([[1,2,3]]) #1x3
>>> np.dot(B, A)
array([[14, 20]])

Pass 1d array as the second argument

>>> A = np.array([[1,2],[2,3],[3,4]]) # 3x2
>>> b = np.array([1,2])
>>> np.dot(A, b)
array([ 5,  8, 11])

When passed as the second argument, it will be treated like a 2x1 2d array.

>>> A = np.array([[1,2],[2,3],[3,4]]) # 3x2
>>> B = np.array([[1],[2]]) # 2x1
>>> np.dot(A, B)
array([[ 5],
       [ 8],
       [11]])

Conclusion

N-dimensional 1d array is

Recommended Posts

Behavior of numpy.dot when passing 1d array and 2d array
Python> link> 2D array initialization and assignment
Differences between Numpy 1D array [x] and 2D array [x, 1]
Correspondence summary of array operation of ruby and python
Behavior when Trainable = False of Container in Keras
Behavior of multiprocessing.pool.Pool.map
Indent behavior of json.dumps is different between python2 and python3