Broadcasting & Linear Algebra Ops
Master NumPy broadcasting rules plus dot products, norms, and matrix ops used in ML math.
In plain words
NumPy can combine a small array with a big one by repeating the small one as needed, as long as the shapes line up from the right.
Think of it like…
Stretching a single row of a table downwards like a sticker that repeats on every line, without printing copies: the program behaves as if the row were repeated, but memory isn't duplicated. If rows and columns don't line up, the sticker can't be stretched and you get an error.
Where you’ve seen it
To standardise a (10000, 5) feature matrix X, the code (X - X.mean(axis=0)) / X.std(axis=0) subtracts a (5,) mean vector from every row and divides by a (5,) std vector: no loops, no copies of the vectors. To score a linear model, X @ w + b multiplies (10000, 5) by (5,) to get 10,000 predictions in one call.
Words you’ll hear
- Broadcasting rule
- Align shapes from the right; dimensions must be equal or 1.
- np.newaxis / None
- Adds a length-1 dimension so shapes can broadcast as intended.
- Dot product / matmul
a @ b: sum of products for vectors; row-by-column product for matrices.- Norm
- A vector's length:
np.linalg.norm(v); ‖v‖₂ is Euclidean.
Visual diagram
Theory & deep dive
The broadcasting rules, with examples
Write the two shapes one above the other, right-aligned, and pad the shorter one with 1s on the left. Each column of dimensions must be equal or contain a 1; the output takes the larger of the two. (3, 4) with (4,) works (the vector is a row repeated 3 times). (3, 4) with (3,) fails, because 4 ≠ 3, but (3, 4) with (3, 1) works, because the column vector repeats across 4 columns. (3, 1) with (1, 4) gives a full (3, 4) grid, the basis of pairwise-difference tables.
Use x[:, np.newaxis] or x.reshape(-1, 1) to turn a vector into a column and keepdims=True on reductions to preserve dimensions. The trap is accidental outer products: a - b where a has shape (n,) and b has shape (n, 1) returns (n, n), which may be huge and silently wrong. Always check .shape of the result.
For points P of shape (n, 2): diff = P[:, None, :] - P[None, :, :] has shape (n, n, 2), and dist = np.sqrt((diff ** 2).sum(axis=-1)) is the (n, n) distance matrix. It uses O(n²) memory, so chunk it for large n.
Linear algebra you'll use constantly
a @ b is matrix multiplication: (m, k) @ (k, n) gives (m, n), so inner dimensions must match; a * b is element-wise, a common mix-up. The dot product of two vectors is the sum of their element-wise products, and cosine similarity is that dot product divided by the product of norms. np.linalg.norm(v) computes length, np.linalg.norm(A, axis=1) row norms. A.T transposes.
To solve linear systems use np.linalg.solve(A, b) rather than computing np.linalg.inv(A) @ b, which is slower and less numerically stable; least squares regression is np.linalg.lstsq(X, y, rcond=None). Eigen and singular value decompositions (np.linalg.eigh, np.linalg.svd) underlie PCA and recommender models. Watch dtypes and conditioning: nearly collinear features make matrices close to singular and results unstable.
X1 = np.column_stack([np.ones(len(X)), X]); coef, *_ = np.linalg.lstsq(X1, y, rcond=None) returns the intercept and slopes minimising squared error; predictions are X1 @ coef.
@ for matrix products, solve and lstsq instead of inv, SVD/eigh for decompositions.How it works, step by step
Step 1 of 41. Write down both shapes
Right-align the shapes and check each dimension pair is equal or 1.
- Mismatch
- raises ValueError
When to use it & trade-offs
What it is
Broadcasting is NumPy's rule for combining arrays of different shapes without copying data: compare shapes from the right, and two dimensions are compatible if they are equal or one of them is 1 (a missing dimension counts as 1). A (1000, 3) matrix minus a (3,) vector subtracts the vector from every row. Linear algebra operations such as the dot product (a @ b), norms (np.linalg.norm) and matrix inverse or solve are the core arithmetic behind regression, PCA and neural networks.
Why it matters: Standardising columns, computing distances, scoring a model and many loss functions are one-liners with broadcasting and matrix products. Misunderstanding the rules produces the most confusing bug in NumPy: a calculation that runs without error but silently broadcasts an (n,) against an (n, 1) into an n × n matrix. Interviews for ML roles often ask you to reason about shapes.
When to reach for it
- Standardising features by column
- Distances and similarity matrices
- Scoring linear models with matrix products
When to avoid or be careful
- Using
np.linalg.invto solve equations - Mixing
*and@without thinking about shapes - Building n × n arrays for large n without chunking
Ways to combine arrays of different shapes
Strengths: No loops or copies; concise.
Watch out: Silent shape surprises; big temporaries for outer-style ops.
Strengths: Explicit result array.
Watch out: Uses real memory; rarely necessary.
Strengths: Maximum flexibility.
Watch out: Much slower on large arrays.
Interview signals & numbers to know
When this topic comes up
- “What shape is the result of this operation?”
- “Standardise each column without a loop”
- “Compute pairwise distances”
- @ vs *
- Numerical stability
Benchmarks & rules of thumb
- right-aligned
- how shapes are compared
- (n,) vs (n, 1)
- the classic broadcasting trap
- O(n²)
- memory of pairwise distance matrices
Common mistakes & follow-ups
Common interview mistakes
- Subtracting a (n, 1) column from a (n,) vector and getting an unintended (n, n) matrix.
- Using
*where@was needed, producing an element-wise result of the wrong shape or meaning. - Computing the inverse of an ill-conditioned matrix and trusting the result.
Likely interviewer follow-ups
- What are the broadcasting rules?
- How do you compute pairwise distances without loops?
- Why prefer
np.linalg.solvetoinv?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Broadcasting & Linear Algebra Ops with data science interview Q&A and hands-on practice.