Course map
Stage 1: Foundations
Stage 2: Machine Learning
Stage 3: Deep Learning
Stage 4: LLMs & Generative AI
Stage 5: Production & Specialization

Part 01 / Topic 4 of 7

Broadcasting

Broadcasting is NumPy's rule for combining arrays of different shapes: dimensions of size 1 (or missing dimensions) are stretched to match. The most common use in ML is applying a per-column statistic to every row.

# examples/02_broadcasting_standardize_every_column_in_one.py
import numpy as np

X = np.array([[1.0, 200.0],
              [2.0, 300.0],
              [3.0, 400.0]])
X_std = (X - X.mean(axis=0)) / X.std(axis=0)   # (3,2) - (2,) broadcasts per column
print(X_std.round(3))
print("column means:", X_std.mean(axis=0).round(6))
print("column stds: ", X_std.std(axis=0))
# [[-1.225 -1.225]
#  [ 0. 0. ]
#  [ 1.225 1.225]]
# column means: [0. 0.]
# column stds: [1. 1.]

That one line — subtract the column means, divide by the column stds — is standardization, and you will use it before gradient descent (Part 4), k-means (Part 7) and neural networks (Stage 3).

Shapes must be compatible from the right. (3, 2) with (2,) works; (3, 2) with (3,) raises:

ValueError: operands could not be broadcast together with shapes (3,2) (3,)

🧪 Quick quiz

  1. X has shape (3, 2) and X.mean(axis=0) has shape (2,). What happens in X - X.mean(axis=0)?
Show the answer

The mean row is broadcast and subtracted from every row, so each column ends up with mean 0.

Done here? The practice set for Part 1 — 4 exercises with solutions — is on the part page.

Search the guide