Numpy.dot在(m,)向量与(m,n)矩阵相乘时的行为机制
Great question—this is such a common gotcha when transitioning from textbook linear algebra to working with NumPy, so let’s unpack this clearly.
First, let’s clarify a key distinction: when you create a = np.array([1,2,3]), you’re making a rank-1 array with shape (3,). This is not the same as a row vector (shape (1,3)) or column vector (shape (3,1)) from linear algebra—it’s a "directionless" 1D structure with no inherent row/column identity. This is where the confusion starts!
@ (Matrix Multiplication) Handles 1D Arrays NumPy’s @ operator (and np.dot for 2D cases) has special logic for 1D arrays to make common operations more convenient, even if it bends strict linear algebra rules slightly:
- When a 1D array is on the left of
@with a 2D array, NumPy treats it as a row vector (automatically adds a leading dimension, making it shape(1, N)). After performing the matrix multiplication, it drops the singleton dimension to return a 1D array. - When a 1D array is on the right of
@with a 2D array, NumPy treats it as a column vector (automatically adds a trailing dimension, making it shape(N, 1)). Again, it drops the singleton dimension from the result.
Let’s walk through your code step by step:
import numpy as np a = np.array([1,2,3]) # shape (3,) b = np.array([[1,2], [3,4], [5,6]]) # shape (3,2)
Case 1: a @ b
- NumPy treats
aas a row vector(1,3) - Matrix multiplication:
(1,3) @ (3,2) = (1,2) - The singleton leading dimension is dropped, resulting in a 1D array
(2,)with values[22, 28]
Case 2: b.T @ a
b.Thas shape(2,3)- NumPy treats
aas a column vector(3,1) - Matrix multiplication:
(2,3) @ (3,1) = (2,1) - The singleton trailing dimension is dropped, resulting in a 1D array
(2,)with values[22, 28]
That’s why the two results look identical—they’re both 1D arrays with the same values, even though the intermediate linear algebra operations were slightly different.
To recap how NumPy determines array dimensions:
- Rank-1 (1D) arrays: Shape
(N,), no row/column orientation. Used for simple sequences of values. - Rank-2 (2D) arrays: Shape
(M,N), explicit rows (M) and columns (N). Matches linear algebra’s matrix/vector definition. - For matrix operations involving 1D arrays, NumPy automatically adjusts the 1D array’s "orientation" to fit the multiplication rules, then simplifies the result back to 1D for convenience.
If you want to stick strictly to linear algebra’s row/column vector rules, explicitly reshape your 1D array to a 2D array:
a_row = a.reshape(1, 3) # Row vector, shape (1,3) a_col = a.reshape(3, 1) # Column vector, shape (3,1) print(a_row @ b) # Output: [[22 28]] (shape (1,2), strict row vector result) print(b.T @ a_col) # Output: [[22], [28]] (shape (2,1), strict column vector result)
Now the results have distinct shapes that align with standard linear algebra expectations.
内容的提问来源于stack exchange,提问作者Touuka13

