NumPy Broadcasting
Broadcasting is a powerful NumPy feature that allows operations between arrays of different shapes. Instead of manually replicating data, NumPy automatically stretches the smaller array to match the larger one, as long as certain rules are satisfied.
Broadcasting eliminates the need for explicit loops when combining arrays of different sizes.
Simple Example: Adding a Scalar to an Array
arr = np.array([1,2,3])
result = arr + 10 # [11,12,13]
# 10 is broadcast to [10,10,10] automaticallyAdding a 1D Array to a 2D Array (Row‑wise)
matrix = np.array([[1,2,3],[4,5,6]]) # shape (2,3)
row = np.array([10,20,30]) # shape (3,)
result = matrix + row # broadcasts row to both rows
# result = [[11,22,33],[14,25,36]]Broadcasting Rules
Two dimensions are compatible when:
- They are equal, or
- One of them is 1.
Why Broadcasting Matters in AI
- Add a bias vector to every sample in a batch (common in neural networks).
- Normalize each column by subtracting the column mean.
- Apply a constant shift to an entire image array.
Example: Normalizing Data
data = np.array([[10,20],[30,40],[50,60]])
mean = np.mean(data, axis=0) # [30,40]
normalized = data - mean # broadcasting subtracts row vectorTwo Minute Drill
- Broadcasting automatically matches array shapes without copying data.
- Scalar broadcast to any shape.
- 1D array can broadcast to 2D if the trailing dimensions align.
- Used heavily in AI for bias addition and data normalization.
Need more clarification?
Drop us an email at career@quipoinfotech.com
