NumPy Vectorization and Broadcasting

NumPy vectorization expresses many repeated scalar calculations as one array operation. For the neural-network calculations here, array operations mirror the linear algebra and let NumPy perform the repeated work in compiled routines. Broadcasting lets operands with compatible shapes reuse values along an axis. It avoids explicitly copying those operands into repeated arrays, although the operation can still allocate a large result.

From scalar loops to matrix operations

Suppose a model must calculate a score for 10,000 customers. A loop can process one customer at a time, repeating the same calculation for all 10,000. Vectorization reorganizes those customers into a matrix and describes the repeated work as one matrix operation. The computer still performs arithmetic for every customer, but NumPy sends the work to optimized numerical routines instead of interpreting a Python loop one step at a time.

For vectors \(w,x\in\mathbb{R}^n\), the dot product is \(w^Tx=\sum_jw_jx_j\). With one example per column of \(X\in\mathbb{R}^{n_x\times m}\) and weights shaped (n_x, 1), all scores are \(Z=w^TX+b\), with shape (1, m). Run the following body blocks in order; they reuse the same arrays.

import numpy as np

X = np.array([[1., 2., 3.], [4., 5., 6.]])
w = np.array([[0.2], [-0.1]])
b = 0.3
Z = w.T @ X + b
A = 1 / (1 + np.exp(-Z))
print(Z.shape, A.shape)
print(np.round(Z, 4))
# (1, 3) (1, 3)
# [[0.1 0.2 0.3]]

A complete one-hidden-layer implementation of this is in Building a Shallow Neural Network with NumPy.

The first column gives \(0.2\times1-0.1\times4+0.3=0.1\). The other columns give 0.2 and 0.3, matching the three entries of Z.

Choose one data convention

The body examples store one example per column. Here \(m\) counts examples, \(n_x\) counts input features, and \(n_l\) counts units in layer \(l\). The superscript \([l]\) identifies a layer. An examples-as-rows convention is also valid, provided the equations and operations use it consistently. This choice of axis meaning is separate from row-major or column-major memory storage.

ArrayShapeMeaning
\(X\)(n_x, m)features by examples
\(W^{[l]}\)(n_l, n_{l-1})one row per unit
\(b^{[l]}\)(n_l, 1)one bias per unit
\(A^{[l]}\)(n_l, m)activations for the batch

How broadcasting works

Broadcasting can be understood as applying one reusable value along a compatible direction. If a layer has three neurons, its bias has three valuesโ€”one for each neuron. Those same three values must be added to every example in the batch. A bias shaped (3, 1) makes that intention explicit: preserve the neuron axis and repeat along the example axis.

NumPy compares shapes from the trailing (rightmost) dimensions. Missing leading dimensions are treated as size 1. Two dimensions are compatible when they are equal or one of them is 1. Adding \(b\in\mathbb{R}^{n_l\times1}\) to \(Z\in\mathbb{R}^{n_l\times m}\) therefore reuses each neuronโ€™s bias across the batch, without materializing a repeated bias matrix.

Broadcasting can also hide mistakes. A one-dimensional array with shape (n,) has no explicit row or column orientation. Adding it to a two-dimensional matrix may succeed while producing an unintended result. Prefer (n, 1) or (1, n) and state the intended axis.

A small addition makes the alignment visible. Shapes (2, 1) and (1, 3) combine to (2, 3): the first operand supplies one value per row, and the second one per column.

row_offsets = np.array([[10.], [20.]])
column_values = np.array([[1., 2., 3.]])
print(row_offsets + column_values)
# [[11. 12. 13.]
#  [21. 22. 23.]]

The upper-right result is 10 + 3 = 13. Both operands are reused, but the new result contains six numbers. This distinction matters at larger sizes: adding a (10000, 1) array to a (1, 10000) array produces 100 million entries. With 8-byte float64 values, that result alone occupies 800 million bytes, about 763 MiB. Working in smaller batches can keep intermediate arrays manageable. The NumPy broadcasting guide discusses this memory tradeoff.

Vectorizing loss and gradients

For the sigmoid binary classifier above, use binary labels \(Y\) shaped (1, m). For a single example, sigmoid combined with binary cross-entropy gives logit derivative \(a-y\). The code uses the mean loss over \(m\) examples, so dZ = (A - Y) / m is its derivative with respect to the whole logit array. Matrix multiplication aggregates the contributions to dw, and a sum across examples gives db. The averaging factor is already in dZ and must not be applied again. The loss below is evaluated directly from logits, using the stable form explained in Logistic Regression.

Y = np.array([[0., 1., 1.]])
assert Y.shape == A.shape
cost = np.mean(np.maximum(Z, 0) - Z * Y + np.log1p(np.exp(-np.abs(Z))))
m = X.shape[1]
dZ = (A - Y) / m
dw = X @ dZ.T
db = np.sum(dZ, axis=1, keepdims=True)
print("cost", round(float(cost), 6))
print("dw", dw.shape, np.round(dw.ravel(), 6))
print("db", db.shape, np.round(db.ravel(), 6))
# cost 0.632297
# dw (2, 1) [-0.550675 -0.901419]
# db (1, 1) [-0.116915]

Axis, reduction, and keepdims

A reduction combines values along the axis named by axis. With examples in columns, sum(axis=1) adds across examples for each feature. By default that axis is removed; keepdims=True retains it with length 1. For this two-dimensional array, the result is a column vector:

row_sums = X.sum(axis=1)
kept_sums = X.sum(axis=1, keepdims=True)
print(row_sums.shape, row_sums)
print(kept_sums.shape, kept_sums)
normalized = X / kept_sums
print(np.round(normalized, 4))
print(normalized.sum(axis=1))
# (2,) [ 6. 15.]
# (2, 1) [[ 6.]
#  [15.]]
# [[0.1667 0.3333 0.5   ]
#  [0.2667 0.3333 0.4   ]]
# [1. 1.]

The denominator has shape (2, 1), so every entry in the first row is divided by 6 and every entry in the second by 15. Each resulting row sums to 1. This arithmetic example uses positive row sums; division by a zero sum would need separate handling.

Shape bugs to watch for

  • Using X.T in one function but not in the next.
  • Allowing labels to become shape (m,) instead of (1,m).
  • Using elementwise * where matrix multiplication @ is required.
  • Calling reshape with the correct size but the wrong semantic order.
  • Reducing over the feature axis instead of the example axis.
  • Depending on accidental broadcasting from a one-dimensional array.

Changing the examples-as-columns convention to examples-as-rows requires a transpose. A reshape to the same destination shape can rearrange which values belong to each example. With the original X, the difference is visible:

print(X.T)
# [[1. 4.]
#  [2. 5.]
#  [3. 6.]]
print(X.reshape(3, 2))
# [[1. 2.]
#  [3. 4.]
#  [5. 6.]]

The transpose keeps the first exampleโ€™s features together as [1, 4]. The default reshape reads the values in row order and groups them into pairs, starting with [1, 2]. Both results have shape (3, 2), so a shape assertion alone cannot distinguish their meanings.

A reliable debugging workflow

The following check uses the same two-feature, three-example batch. It checks shapes explicitly before comparing a loop calculation with the vectorized result. Shape checks matter because np.allclose can itself broadcast unequal shapes. The finite-value check can catch numerical failures, but neither check proves that an implementation is correct for every input.

assert X.ndim == 2
assert w.shape == (X.shape[0], 1)
assert Y.shape == Z.shape == (1, X.shape[1])
assert np.all(np.isfinite(A))
Z_loop = np.zeros_like(Z)
for k in range(X.shape[1]):
    Z_loop[0, k] = b
    for f in range(X.shape[0]):
        Z_loop[0, k] += w[f, 0] * X[f, k]
assert Z_loop.shape == Z.shape
print(np.allclose(Z_loop, Z, rtol=1e-12, atol=1e-12))
# True

The L-layer forward and backward passes are written out in Deep Neural Networks: Architecture and Backpropagation.

The comparison agrees within the stated tolerance on this batch. Timing needs repeated measurements because system activity, allocation, and library warm-up can affect a single call.

For a new vectorized expression, identify which axis indexes examples, write the expected output shape, and compare a small result with a direct calculation. Then measure runtime and memory for the sizes you need. np.vectorize is a convenience wrapper whose implementation is essentially a loop; its name does not promise the performance of operations such as matrix multiplication.

The same training stages are implemented with PyTorch tensors, modules, and autograd in Building a PyTorch Training Loop with nn.Module, Dataset, and DataLoader.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.