flowchart TD
subgraph Fwd["Forward Pass"]
direction LR
F1["Linear 1<br/>Z1 = X@W1 + b1<br/>(n, h)"] --> F2["ReLU Hidden<br/>A1 = max(0, Z1)<br/>(n, h)"]
F2 --> F3["Linear 2 & Sigmoid<br/>Z2 = A1@W2 + b2<br/>p = sig(Z2) (n, 1)"]
end
subgraph Bwd["Backprop Pass"]
direction LR
B3["Output Grad<br/>dZ2 = (p - y)/n<br/>dW2, db2"] --> B2["ReLU Mask<br/>dZ1 = (dZ2@W2.T)<br/>* (Z1 > 0)"]
B2 --> B1["Input Grad & Step<br/>dW1 = X.T@dZ1<br/>W -= lr * dW"]
end
Fwd -->|"BCE Loss L(p, y)"| Bwd
27 Neural Networks from Scratch in NumPy — Perceptrons, Activations, Backpropagation, and MLPs
Chapter Mission: Open Part VI (Deep Learning) by stripping away every ounce of framework magic. Before touching PyTorch in Chapter 28, you will build a complete multi-layer neural network in pure NumPy—starting from Rosenblatt’s linear perceptron and its failure on XOR, deriving ReLU, Sigmoid, Tanh, and overflow-safe Softmax, assembling a two-layer MLP forward pass with He initialization, deriving reverse-mode backpropagation via the chain rule, verifying every analytical derivative to \(< 10^{-10}\) against centered finite differences, solving XOR to
100.0%accuracy, and benchmarking your scratch MLP againstLogisticRegressionon Bangladesh maternal and child health survey data (mch_survey_sample).
Chapter Companion Notebooks (1-to-1 Mirrored in Google Colab)
| Lab Type | Interactive Colab Notebook | Scan (Print) |
|---|---|---|
| Walkthrough | ch27 / 01_walkthrough.ipynb | ![]() |
| Guided To-Dos | ch27 / 02_guided_todos.ipynb | ![]() |
| Coding Exam | ch27 / 03_coding_exam.ipynb | ![]() |
Learning Objectives
By the end of this chapter, you will be able to:
- Explain geometrically why a single linear perceptron solves linearly separable gates like
AND(100%) yet provably fails onXOR, motivating hidden layers with nonlinear activations. - Implement ReLU (and its subgradient mask), Sigmoid, Tanh, and numerically stable Softmax using the row-wise max-shift trick so extreme logits (
[1000.0, 1001.0, 999.0]) never overflow toNaN/Inf. - Derive and code Binary Cross-Entropy (BCE) loss with probability clipping (
[1e-12, 1 - 1e-12]) and its clean analytical logit gradient \(\frac{\partial L}{\partial z} = \frac{p - y}{n}\). - Build a vectorized two-layer MLP forward pass (
Z1 -> ReLU -> Z2 -> Sigmoid) that caches intermediate tensors (X,Z1,A1,Z2,probs) for exact reverse-mode differentiation. - Derive and implement chain-rule backpropagation (
dW2,db2,dW1,db1) without falling into the(n, 1) - (n,)broadcasting trap, and audit every tensor gradient via centered finite-difference gradient checking (max |ana - num| < 1e-8). - Train a He-initialized pure-NumPy MLP end-to-end on nonlinear synthetic data (
XOR, two moons) and realmch_survey_samplestunting outcomes, benchmarking honestly againstLogisticRegressionon an identical leak-free split.
27.1 Stage 1 — First-Principles Intuition: Why Hidden Layers Bend Space
Across Part V (Chapters 21–26), you built classical supervised and unsupervised pipelines—from regularized linear models and calibrated classifiers to tree ensembles and nested cross-validation. Linear models like logistic regression draw a single flat hyperplane \(w^T x + b = 0\) across feature space. That works wonderfully when risk increases monotonically with predictors, yet breaks completely the moment classes interact nonlinearly.
The simplest counterexample in computer science is the two-bit XOR gate: inputs (0, 0) and (1, 1) belong to class 0, while (0, 1) and (1, 0) belong to class 1. No straight line on the 2D plane can separate the two diagonals. A Multi-Layer Perceptron (MLP) solves this by composing two affine transformations separated by a nonlinear activation function \(\sigma(\cdot)\):
\[Z_1 = X W_1 + b_1, \qquad A_1 = \text{ReLU}(Z_1), \qquad Z_2 = A_1 W_2 + b_2, \qquad p = \sigma(Z_2)\]
Five foundational principles power every deep neural network—from a 17-parameter XOR net to a billion-parameter transformer:
- Nonlinearity Is Non-Negotiable: Stacking two linear layers without an activation collapses mathematically into a single linear layer: \((X W_1) W_2 = X (W_1 W_2) = X W_{\text{eff}}\). Putting ReLU (\(\max(0, z)\)) or Tanh between layers bends the coordinate system so a linear output head can slice previously tangled classes cleanly.
- Symmetry Breaking & He Initialization: Initializing all hidden weights
W1 = 0gives every hidden neuron identical activations and identical gradients on every epoch—effectively reducing 16 neurons to 1. SamplingW1from \(\mathcal{N}(0, \sqrt{2 / d_{\text{in}}})\) (He initialization) breaks symmetry while preserving activation variance through ReLU’s half-zeroing behavior. - Numerical Stability First: Deep networks routinely produce large pre-activation logits. Calling raw
np.exp(1000.0)overflows IEEE-754float64(limit \(\approx e^{709.78}\)), whilenp.log(0.0)produces-infandNaNgradients. Subtracting row maxima in Softmax and clipping sigmoid probabilities to[1e-12, 1 - 1e-12]prevents silent explosions. - Reverse-Mode Autodiff (Backpropagation): Rather than recomputing the loss \(2P\) times for \(P\) parameters, backpropagation caches forward tensors (
X,Z1,A1,Z2,probs) and walks the computational graph backward once using the multivariable chain rule, computing all parameter gradients in \(\mathcal{O}(1)\) forward-pass equivalents. - Never Trust Hand-Derived Gradients Without Finite Differences: One missing transpose, forgotten
/ n, or(n, 1) - (n,)broadcast bug can make loss plateau or diverge quietly. Comparing analytical gradients against centered finite differences \(\frac{L(W + \varepsilon) - L(W - \varepsilon)}{2\varepsilon}\) catches algebraic mistakes to \(10^{-10}\) precision before training begins.
Separately, the sigmoid derivative \(\sigma'(z) = p(1 - p)\) vanishes near \(0\) and \(1\), while the BCE derivative with respect to probability \(\frac{\partial L}{\partial p} = -\frac{y}{p} + \frac{1 - y}{1 - p}\) blows up near \(0\) and \(1\). When chained together with respect to the pre-sigmoid logit \(z\), the \(p(1 - p)\) factors cancel identically, leaving \(\frac{\partial L}{\partial z} = \frac{p - y}{n}\)—the exact same clean residual form you derived for linear regression in Chapter 22!
27.2 Stage 2 — Visual Mental Model: Forward & Backpropagation Computational Graph
Follow the exact tensor flow left-to-right during the Forward Pass and right-to-left during the Backprop Pass for a two-layer ReLU-to-Sigmoid MLP on a batch of \(n\) examples:
Every single equation in mlp_forward_two_layer and mlp_backward_two_layer maps 1-to-1 onto these six boxes: the forward pass caches (X, Z1, A1, Z2, probs) while computing the scalar BCE loss, and the backward pass consumes those exact cached tensors in reverse order to compute (dW2, db2) and (dW1, db1).
- The
(n, 1) - (n,)Broadcasting Trap: Ifprobshas shape(n, 1)andy_trueis a 1D vector of shape(n,), writingprobs - y_truedoes not raise an error immediately—NumPy silently broadcasts it into an(n, n)matrix! Always reshapey_col = np.asarray(y_true, dtype=float).reshape(-1, 1)first. - Missing
keepdims=Truein Row Sums: Computingz - np.max(z, axis=1)ordb1 = np.sum(dZ1, axis=0)drops a dimension, creating subtle shape bugs whenever batch sizenhappens to equal class countkor hidden widthh. Always passkeepdims=True. - Training on Unstandardized Tabular Features: Passing raw
maternal_age_years(\(\sim 30\)) alongside binaryis_urban(\(0/1\)) without train-onlyStandardScalersaturates initial logits and forces tiny learning rates.
27.3 Stage 3 — Line-by-Line Code Walkthrough & Error Anatomy
Open part_06_deep_learning/ch27_neural_nets_from_scratch/01_walkthrough.ipynb in Colab and execute every cell top-to-bottom alongside the dissections below.
27.3.1 Setup: Loading & Cleaning mch_survey_sample
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import sharukh_tutor as tutor
mch_raw = tutor.load_data("mch_survey_sample", as_pandas=True)
mch = mch_raw.copy()
mch["anc_visits"] = mch["anc_visits"].replace(999, np.nan)
mch["residence"] = (
mch["residence"].astype(str).str.strip().str.title()
)
mch["is_urban"] = (mch["residence"] == "Urban").astype(int)
wealth_map = {
"Poorest": 1, "Poorer": 2, "Middle": 3,
"Richer": 4, "Richest": 5,
}
mch["wealth_num"] = (
mch["wealth_quintile"].astype(str).str.strip()
.str.title().map(wealth_map)
)
feat_cols = [
"anc_visits", "maternal_hb_g_dl",
"maternal_age_years", "is_urban", "wealth_num",
]
clean = mch[feat_cols + ["child_stunted"]].dropna()
rate = clean["child_stunted"].mean() * 100.0
print(f"Raw rows: {len(mch_raw)} -> Complete rows: {len(clean)}")
print(f"Child stunting prevalence: {rate:.1f}%")Expected Output:
Working strictly on a non-mutating .copy() (zero inplace=True, fully Pandas 3.x safe), we replace sentinel anc_visits == 999 with np.nan, normalize residence casing into binary is_urban, encode ordinal wealth_quintile (1..5), and retain 470 complete child records with 13.8% stunting prevalence.
27.3.2 The Perceptron & Why XOR Breaks Linear Boundaries
def train_perceptron(X, y, lr=0.1, epochs=30):
w = np.zeros(X.shape[1], dtype=float)
b = 0.0
for _ in range(epochs):
for xi, yi in zip(X, y):
pred = 1 if (xi @ w + b) >= 0.0 else 0
err = yi - pred
w = w + lr * err * xi
b = b + lr * err
preds = ((X @ w + b) >= 0.0).astype(int)
return preds, float(np.mean(preds == y))
X_gate = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y_and = np.array([0, 0, 0, 1])
y_xor = np.array([0, 1, 1, 0])
p_and, acc_and = train_perceptron(X_gate, y_and)
p_xor, acc_xor = train_perceptron(X_gate, y_xor)
print(f"AND gate -> preds={p_and.tolist()}, acc={acc_and:.2f}")
print(f"XOR gate -> preds={p_xor.tolist()}, acc={acc_xor:.2f}")Expected Output:
Rosenblatt’s perceptron converges effortlessly on the linearly separable AND gate (acc = 1.00), yet oscillates forever on XOR (acc = 0.50). Because a single linear inequality \(w_1 x_1 + w_2 x_2 + b \ge 0\) divides the 2D plane into just two half-spaces, solving XOR requires at least one nonlinear hidden layer.
27.3.3 Activation Functions & Numerically Stable Softmax
def relu_and_grad(z):
z_arr = np.asarray(z, dtype=float)
return np.maximum(0.0, z_arr), (z_arr > 0).astype(float)
def sigmoid(z):
z_c = np.clip(np.asarray(z, dtype=float), -500.0, 500.0)
return 1.0 / (1.0 + np.exp(-z_c))
def stable_softmax(logits):
z = np.asarray(logits, dtype=float)
shifted = z - np.max(z, axis=1, keepdims=True)
exp_z = np.exp(shifted)
return exp_z / np.sum(exp_z, axis=1, keepdims=True)
z_demo = np.array([-2.0, 0.0, 1.5, 3.0])
r_val, r_grad = relu_and_grad(z_demo)
print("ReLU out :", r_val, "| grad:", r_grad)
print("Sigmoid :", np.round(sigmoid(z_demo), 4))
print("Tanh :", np.round(np.tanh(z_demo), 4))
big_logits = np.array([[1000.0, 1001.0, 999.0], [1.0, 2.0, 0.0]])
sm_probs = stable_softmax(big_logits)
print("Stable softmax:\n", np.round(sm_probs, 4))
print("Row sums :", sm_probs.sum(axis=1))Expected Output:
Look closely at big_logits: shifting [1000.0, 1001.0, 999.0] by its row maximum 1001.0 produces [-1.0, 0.0, -2.0], which yields the exact same probability distribution [0.2447, 0.6652, 0.0900] as [1.0, 2.0, 0.0]—with zero floating-point overflow!
27.3.4 Binary Cross-Entropy & Two-Layer MLP Forward Pass
def binary_bce_loss_and_grad(y_true, logits):
y = np.asarray(y_true, dtype=float)
z = np.asarray(logits, dtype=float)
p = np.clip(sigmoid(z), 1e-12, 1.0 - 1e-12)
loss = -float(np.mean(
y * np.log(p) + (1.0 - y) * np.log(1.0 - p)
))
return round(loss, 5), (p - y) / len(y)
def mlp_forward_two_layer(X, W1, b1, W2, b2):
X_a = np.asarray(X, dtype=float)
Z1 = X_a @ W1 + b1
A1 = np.maximum(0.0, Z1)
Z2 = A1 @ W2 + b2
probs = sigmoid(Z2)
cache = {
"X": X_a, "Z1": Z1, "A1": A1,
"Z2": Z2, "probs": probs,
}
return probs, cache
rng = np.random.default_rng(42)
X_mini = rng.normal(size=(5, 3))
y_mini = np.array([0.0, 1.0, 1.0, 0.0, 1.0])
W1 = rng.normal(0.0, np.sqrt(2.0 / 3), size=(3, 4))
b1 = np.zeros((1, 4))
W2 = rng.normal(0.0, np.sqrt(2.0 / 4), size=(4, 1))
b2 = np.zeros((1, 1))
probs_m, cache_m = mlp_forward_two_layer(X_mini, W1, b1, W2, b2)
bce_val, dz2_vec = binary_bce_loss_and_grad(
y_mini, cache_m["Z2"].ravel()
)
print(f"Z1 shape: {cache_m['Z1'].shape} | probs: {probs_m.shape}")
print(f"Initial BCE loss: {bce_val:.5f}")
print("Probs :", np.round(probs_m.ravel(), 4))Expected Output:
Notice the healthy initial state produced by He initialization (std = sqrt(2 / d_in)): predicted probabilities sit cleanly in (0.50, 0.89) rather than saturating at 0.000 or 1.000, and the initial BCE loss (0.66041) sits right near the random-guess benchmark \(\ln(2) \approx 0.69315\).
27.3.5 Chain-Rule Backpropagation & Numerical Gradient Check
Walking backward from mean BCE loss \(L = -\frac{1}{n}\sum_i [y_i \ln p_i + (1 - y_i) \ln(1 - p_i)]\) yields six exact matrix equations:
\[dZ_2 = \frac{p - y}{n}, \qquad dW_2 = A_1^T dZ_2, \qquad db_2 = \sum_{i=1}^n dZ_{2,i}\]
\[dZ_1 = (dZ_2 W_2^T) \odot \mathbb{I}(Z_1 > 0), \qquad dW_1 = X^T dZ_1, \qquad db_1 = \sum_{i=1}^n dZ_{1,i}\]
Let’s verify every single analytical tensor against centered finite differences:
def mlp_backward_two_layer(y_true, cache, W2):
y_col = np.asarray(y_true, dtype=float).reshape(-1, 1)
n = len(y_col)
dZ2 = (cache["probs"] - y_col) / n
dW2 = cache["A1"].T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dA1 = dZ2 @ np.asarray(W2, dtype=float).T
dZ1 = dA1 * (cache["Z1"] > 0).astype(float)
dW1 = cache["X"].T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
return {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2}
def numerical_gradient_check(loss_fn, W, eps=1e-5):
W_work = np.asarray(W, dtype=float).copy()
grad = np.zeros_like(W_work)
for idx in np.ndindex(W_work.shape):
orig = W_work[idx]
W_work[idx] = orig + eps
lp = float(loss_fn(W_work))
W_work[idx] = orig - eps
lm = float(loss_fn(W_work))
W_work[idx] = orig
grad[idx] = (lp - lm) / (2.0 * eps)
return grad
grads = mlp_backward_two_layer(y_mini, cache_m, W2)
def loss_of(w1_, b1_, w2_, b2_):
p_, _ = mlp_forward_two_layer(X_mini, w1_, b1_, w2_, b2_)
p_c = np.clip(p_, 1e-12, 1.0 - 1e-12)
yc = y_mini.reshape(-1, 1)
return -float(np.mean(
yc * np.log(p_c) + (1.0 - yc) * np.log(1.0 - p_c)
))
checks = [
("dW1", grads["dW1"], lambda w: loss_of(w, b1, W2, b2), W1),
("db1", grads["db1"], lambda b: loss_of(W1, b, W2, b2), b1),
("dW2", grads["dW2"], lambda w: loss_of(W1, b1, w, b2), W2),
("db2", grads["db2"], lambda b: loss_of(W1, b1, W2, b), b2),
]
for name, g_ana, fn_l, param in checks:
g_num = numerical_gradient_check(fn_l, param, eps=1e-6)
diff = float(np.max(np.abs(g_ana - g_num)))
print(f"{name} shape={g_ana.shape} | max |ana - num| = {diff:.2e}")Expected Output:
Every single parameter gradient (dW1, db1, dW2, db2) matches centered finite differences to ~10^-10, proving our chain-rule math, matrix transposes, ReLU mask, and / n scaling are 100% exact!
27.3.6 Solving XOR in Pure NumPy
Now let’s watch a 2-layer 2 -> 8 -> 1 MLP with tanh hidden activations crush the XOR task that defeated our linear perceptron:
rng_x = np.random.default_rng(42)
X_xor = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y_xor_col = np.array([[0.], [1.], [1.], [0.]])
W1_x = rng_x.normal(0.0, np.sqrt(1.0 / 2), size=(2, 8))
b1_x = np.zeros((1, 8))
W2_x = rng_x.normal(0.0, np.sqrt(1.0 / 8), size=(8, 1))
b2_x = np.zeros((1, 1))
lr_x = 0.5
for ep in range(1, 2501):
A1_x = np.tanh(X_xor @ W1_x + b1_x)
p_x = sigmoid(A1_x @ W2_x + b2_x)
if ep in (1, 500, 2500):
pc = np.clip(p_x, 1e-12, 1.0 - 1e-12)
lx = -float(np.mean(
y_xor_col * np.log(pc) + (1 - y_xor_col) * np.log(1 - pc)
))
print(f"Epoch {ep:4d} -> BCE loss: {lx:.5f}")
dZ2 = (p_x - y_xor_col) / 4.0
dW2 = A1_x.T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dZ1 = (dZ2 @ W2_x.T) * (1.0 - A1_x ** 2)
dW1 = X_xor.T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
W1_x -= lr_x * dW1; b1_x -= lr_x * db1
W2_x -= lr_x * dW2; b2_x -= lr_x * db2
p_final = sigmoid(np.tanh(X_xor @ W1_x + b1_x) @ W2_x + b2_x)
preds_xor = (p_final.ravel() >= 0.5).astype(int).tolist()
print("XOR probs:", np.round(p_final.ravel(), 4).tolist())
print("XOR preds:", preds_xor, "| Accuracy: 100.0%")Expected Output:
Because tanh has derivative \(1 - \tanh^2(z) = 1 - A_1^2\), every neuron receives smooth, non-zero gradients across all four corners—driving BCE from 0.71318 down to 0.00139 and predicting [0, 1, 1, 0] with > 99.7% confidence on every example.
27.3.7 Training Our Pure-NumPy MLP on mch_survey_sample vs. LogisticRegression
Now let’s bring our scratch ReLU MLP onto real Bangladesh maternal and child health survey data (child_stunted), comparing it fairly against Scikit-Learn’s LogisticRegression on the exact same stratified 75/25 split and train-only StandardScaler:
X_mch = clean[feat_cols].to_numpy(dtype=float)
y_mch = clean["child_stunted"].to_numpy(dtype=int)
X_tr, X_te, y_tr, y_te = train_test_split(
X_mch, y_mch, test_size=0.25, stratify=y_mch, random_state=42
)
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr)
X_te_s = scaler.transform(X_te)
rng_m = np.random.default_rng(42)
W1_m = rng_m.normal(0.0, np.sqrt(2.0 / 5), size=(5, 16))
b1_m = np.zeros((1, 16))
W2_m = rng_m.normal(0.0, np.sqrt(2.0 / 16), size=(16, 1))
b2_m = np.zeros((1, 1))
losses_m = []
for ep in range(400):
p_tr, c_tr = mlp_forward_two_layer(X_tr_s, W1_m, b1_m, W2_m, b2_m)
l_tr, _ = binary_bce_loss_and_grad(y_tr, c_tr["Z2"].ravel())
losses_m.append(l_tr)
g_m = mlp_backward_two_layer(y_tr, c_tr, W2_m)
W1_m -= 0.1 * g_m["dW1"]; b1_m -= 0.1 * g_m["db1"]
W2_m -= 0.1 * g_m["dW2"]; b2_m -= 0.1 * g_m["db2"]
p_te_mlp, _ = mlp_forward_two_layer(X_te_s, W1_m, b1_m, W2_m, b2_m)
mlp_auc = roc_auc_score(y_te, p_te_mlp.ravel())
log_clf = LogisticRegression(max_iter=500).fit(X_tr_s, y_tr)
log_auc = roc_auc_score(y_te, log_clf.predict_proba(X_te_s)[:, 1])
print(f"MLP BCE Epoch 1: {losses_m[0]:.5f} -> "
f"Epoch 100: {losses_m[99]:.5f} -> Epoch 400: {losses_m[-1]:.5f}")
print(f"Holdout ROC-AUC -> NumPy MLP: {mlp_auc:.4f} "
f"| LogisticRegression: {log_auc:.4f}")Expected Output:
Notice the honest, publication-grade scientific takeaway:
- Smooth Optimization: Training BCE drops monotonically from
0.52489to0.33101over 400 batch gradient steps without a single line of PyTorch or Scikit-Learn neural code. - Honest Tabular Benchmarking: On this modest 470-household tabular survey with five noisy clinical predictors, our pure-NumPy MLP edges out
LogisticRegression(0.5968vs.0.5772holdout ROC-AUC). As you will see in Part VI, neural networks shine brightest on high-dimensional nonlinear data (images, sequences, text), whereas on small tabular surveys a linear or tree baseline is always mandatory!
27.3.8 Break It On Purpose! (Neural Network Error Anatomy)
Python’s Traceback:
Diagnosis: Matrix multiplication (n, d_in) @ (d_in, h) requires the inner dimension k to match identically. Here X_bad has 5 features, while W1_bad expects only 3.
Fix: Always initialize W1 dynamically from d_in = X.shape[1] (size=(d_in, hidden_dim)) rather than hardcoding input feature counts.
Python’s Traceback:
Diagnosis: Subtracting 1D y_flat (4,) from column probs_col (4, 1) did not fail on line 5—NumPy silently broadcast dZ2_bad into a (4, 4) matrix! The bug only surfaced two lines later when A1_demo.T @ dZ2_bad became (8, 4) instead of (8, 1).
Fix: Reshape targets defensively on line 1 of every loss or backprop helper: y_col = np.asarray(y_true, dtype=float).reshape(-1, 1).
Python’s Traceback:
Diagnosis: IEEE-754 float64 overflows at \(\approx 1.8 \times 10^{308}\) (\(e^{709.78}\)). Without np.errstate(over="raise"), naive np.exp(raw_logits) silently returns [inf, inf, inf], causing inf / inf = nan across your entire batch!
Fix: Always apply the row-wise max-shift trick shifted = z - np.max(z, axis=1, keepdims=True) before calling np.exp(shifted).
27.4 Stage 4 — The Researcher’s Problem-Structuring Blueprint
Scenario: Your research group wants a self-contained, auditable function run_mch_mlp_blueprint(raw_df, hidden_dim=16, lr=0.1, epochs=400, seed=42) that cleans raw mch_survey_sample without mutating it, creates a stratified 75/25 split with train-only scaling, runs an automatic pre-flight finite-difference gradient check (max |ana - num| < 1e-8) before launching training, trains the pure-NumPy 2-layer ReLU MLP, and reports holdout ROC-AUC side-by-side against LogisticRegression(max_iter=500).
27.4.1 Blueprint (Completed on Paper Before Coding)
Non-Mutating Cleaning & Stratified Leak-Free Split:
- Copy
raw_df, replaceanc_visits == 999withnp.nan, normalizeresidence->is_urban, mapwealth_quintile->wealth_num (1..5), and drop NaNs across the 5 features +child_stunted. - Split 75/25 stratified (
random_state=seed) and fitStandardScalerstrictly onX_tr.
- Copy
He Initialization & Pre-Flight Gradient Verification:
- Initialize
W1 ~ N(0, sqrt(2 / d_in))andW2 ~ N(0, sqrt(2 / hidden_dim))usingnp.random.default_rng(seed). - Compare analytical
dW2against centered finite differences (eps=1e-6) on an 8-row training slice before training.
- Initialize
Training & Linear Baseline Audit:
- Train the 2-layer ReLU MLP for
epochsgradient-descent steps, evaluate holdoutmlp_auc, fitLogisticRegression(max_iter=500)on the exact same scaled split, and return all audit metrics in one dict.
- Train the 2-layer ReLU MLP for
27.4.2 Clean Python Implementation (Verbatim in 01_walkthrough.ipynb)
def run_mch_mlp_blueprint(
raw_df, hidden_dim=16, lr=0.1, epochs=400, seed=42
):
"""Clean MCH data, gradient-check MLP, and benchmark vs Logistic."""
df = raw_df.copy()
df["anc_visits"] = df["anc_visits"].replace(999, np.nan)
df["residence"] = (
df["residence"].astype(str).str.strip().str.title()
)
df["is_urban"] = (df["residence"] == "Urban").astype(int)
wmap = {
"Poorest": 1, "Poorer": 2, "Middle": 3,
"Richer": 4, "Richest": 5,
}
df["wealth_num"] = (
df["wealth_quintile"].astype(str).str.strip()
.str.title().map(wmap)
)
feats = [
"anc_visits", "maternal_hb_g_dl",
"maternal_age_years", "is_urban", "wealth_num",
]
cdf = df[feats + ["child_stunted"]].dropna()
X_a = cdf[feats].to_numpy(dtype=float)
y_a = cdf["child_stunted"].to_numpy(dtype=int)
X_tr, X_te, y_tr, y_te = train_test_split(
X_a, y_a, test_size=0.25, stratify=y_a, random_state=seed
)
sc = StandardScaler()
X_tr_s = sc.fit_transform(X_tr)
X_te_s = sc.transform(X_te)
# 1. He initialization + pre-flight gradient check on 8-row slice
rng_b = np.random.default_rng(seed)
d_in = X_tr_s.shape[1]
W1 = rng_b.normal(0.0, np.sqrt(2.0 / d_in), size=(d_in, hidden_dim))
b1 = np.zeros((1, hidden_dim))
W2 = rng_b.normal(0.0, np.sqrt(2.0 / hidden_dim), size=(hidden_dim, 1))
b2 = np.zeros((1, 1))
_, c_chk = mlp_forward_two_layer(X_tr_s[:8], W1, b1, W2, b2)
g_chk = mlp_backward_two_layer(y_tr[:8], c_chk, W2)
def chk_loss(w2_cand):
p_, _ = mlp_forward_two_layer(X_tr_s[:8], W1, b1, w2_cand, b2)
pc = np.clip(p_, 1e-12, 1.0 - 1e-12)
yc = y_tr[:8].astype(float).reshape(-1, 1)
return -float(np.mean(yc * np.log(pc) + (1 - yc) * np.log(1 - pc)))
grad_err = float(np.max(np.abs(
g_chk["dW2"] - numerical_gradient_check(chk_loss, W2, eps=1e-6)
)))
# 2. Train pure-NumPy 2-layer MLP
for _ in range(epochs):
_, c_t = mlp_forward_two_layer(X_tr_s, W1, b1, W2, b2)
g_t = mlp_backward_two_layer(y_tr, c_t, W2)
W1 -= lr * g_t["dW1"]; b1 -= lr * g_t["db1"]
W2 -= lr * g_t["dW2"]; b2 -= lr * g_t["db2"]
p_te, _ = mlp_forward_two_layer(X_te_s, W1, b1, W2, b2)
mlp_auc = round(float(roc_auc_score(y_te, p_te.ravel())), 4)
# 3. Linear baseline on exact same split
lr_m = LogisticRegression(max_iter=500).fit(X_tr_s, y_tr)
lr_auc = round(float(
roc_auc_score(y_te, lr_m.predict_proba(X_te_s)[:, 1])
), 4)
return {
"n_clean": len(cdf),
"grad_check_err": grad_err,
"mlp_auc": mlp_auc,
"logistic_auc": lr_auc,
}
report = run_mch_mlp_blueprint(mch_raw)
print(f"Clean rows: {report['n_clean']} | "
f"Grad-check max err: {report['grad_check_err']:.2e}")
print(f"Test ROC-AUC -> NumPy MLP: {report['mlp_auc']:.4f} | "
f"Logistic: {report['logistic_auc']:.4f}")Output:
Notice the engineering rigor baked into this blueprint: before a single weight update runs, our finite-difference gate certifies Grad-check max err: 4.72e-11, guaranteeing our hand-coded backprop engine is bug-free before benchmarking against LogisticRegression.
27.5 Stage 5 — Guided “To-Do” Practice Labs
Open part_06_deep_learning/ch27_neural_nets_from_scratch/02_guided_todos.ipynb in Google Colab, run Step 0 to activate sharukh-tutor, and implement all six pure-NumPy neural network functions below. Pass each function name (without parentheses!) to tutor.check(...).
- To-Do 27.1 (
relu_and_grad(z)): Convertzto a float NumPy array without mutating input, and return(np.maximum(0.0, z), (z > 0).astype(float)). - To-Do 27.2 (
stable_softmax(logits)): On a 2D(n, k)array without mutating input, subtract row-wise max (axis=1, keepdims=True) before exponentiating so large logits like[1000.0, 1001.0, 999.0]return exact row-normalized probabilities summing to1.0. - To-Do 27.3 (
binary_bce_loss_and_grad(y_true, logits)): Compute clipped sigmoidp = np.clip(1 / (1 + np.exp(-np.clip(logits, -500, 500))), 1e-12, 1 - 1e-12), mean BCE loss rounded to 5 decimals (float), and analytical gradientdlogits = (p - y_true) / len(y_true), returning(loss_round5, dlogits_array). - To-Do 27.4 (
mlp_forward_two_layer(X, W1, b1, W2, b2)): ComputeZ1 = X @ W1 + b1,A1 = np.maximum(0.0, Z1),Z2 = A1 @ W2 + b2, and clipped sigmoidprobs, returning(probs, cache)wherecachehas exact keys{"X", "Z1", "A1", "Z2", "probs"}. - To-Do 27.5 (
mlp_backward_two_layer(y_true, cache, W2)): Reshapey_truesafely to(-1, 1)and compute analytical BCE backprop gradients{"dW1", "db1", "dW2", "db2"}(keepdims=Trueon biases) matching centered finite differences within< 1e-5. - To-Do 27.6 (
numerical_gradient_check(loss_fn, W, eps=1e-5)): Compute centered finite differences(loss_fn(W_plus) - loss_fn(W_minus)) / (2 * eps)per element on a.copy()ofWwithout mutatingW, returning a gradient array matchingW.shape.
27.6 Stage 6 — Concept & Execution Trace Test (No Computer Allowed!)
Work through all 10 neural-network trace questions on paper before checking Stage 8:
- Why Linear Layers Alone Collapse: Suppose you stack two layers with no nonlinear activation: \(h = X W_1\) and \(\hat{y} = h W_2\). Prove in one line why this 2-layer network has the exact same expressive power as a 1-layer linear model.
- XOR Linear Inseparability: Why can a single perceptron reach at most
75%(3/4) accuracy on the 4-point XOR truth table[(0,0)->0, (0,1)->1, (1,0)->1, (1,1)->0]? - ReLU Forward & Subgradient by Hand: Given pre-activation vector
z = [-3.0, 0.0, 2.5, -0.4], write the exact output ofrelu_and_grad(z). What happens to the upstream gradient flowing through neurons0and3during backprop? - Softmax Max-Shift Invariance: Prove algebraically why subtracting a constant \(c = \max_j z_j\) from every logit in a row leaves \(\text{softmax}(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}}\) completely unchanged while eliminating floating-point overflow.
- BCE Loss & Gradient at Zero Logits: For
y_true = [1.0, 0.0]andlogits = [0.0, 0.0], computep, mean BCE loss (in terms of \(\ln 2\)), anddlogits = (p - y_true) / nby hand. - Tensor Shape Audit: For batch size \(n = 32\), input features \(d_{\text{in}} = 5\), hidden width \(h = 16\), and 1 binary output, write the exact shapes of
W1,b1,Z1,A1,W2,b2,Z2,dZ2,dW2,dZ1, anddW1. - Zero-Initialization Symmetry Trap: Why does initializing
W1 = np.zeros((5, 16))break a 16-neuron MLP even though initializingw = np.zeros(5)worked fine for linear regression in Chapter 22? - The
(n, 1) - (n,)Broadcasting Bug: Ifprobshas shape(10, 1)andy_truehas shape(10,), what is the shape ofprobs - y_truein NumPy, and what error occurs when computingW2 -= lr * (A1.T @ dZ2)? - He Initialization Scaling: Why does He initialization sample ReLU layer weights with \(\text{std} = \sqrt{2 / d_{\text{in}}}\) rather than \(\sqrt{1 / d_{\text{in}}}\)?
- Centered vs. One-Sided Finite Differences: Given \(f(w) = w^3\) at \(w = 2.0\) with \(\varepsilon = 0.1\), compute both the one-sided difference \(\frac{f(w + \varepsilon) - f(w)}{\varepsilon}\) and the centered difference \(\frac{f(w + \varepsilon) - f(w - \varepsilon)}{2\varepsilon}\), and compare both to the exact derivative \(f'(2) = 12\).
27.7 Stage 7 — Chapter 27 Coding Exam (100 Points)
Open part_06_deep_learning/ch27_neural_nets_from_scratch/03_coding_exam.ipynb, implement all three functions, and run tutor.check_exam("ch27", exam_submissions) to earn your Chapter 27 score out of 100 points.
27.7.1 Exam Task 27.1 (30 Points): solve_xor_mlp_numpy(seed=42, epochs=2500, lr=0.5)
- Train a pure-NumPy 2-layer MLP (
2 -> 8 -> 1) withtanhorReLUhidden layer and seedednp.random.default_rng(seed)on XOR[[0,0], [0,1], [1,0], [1,1]] -> [0, 1, 1, 0]. - Return
{"accuracy": float, "final_loss": round5, "preds": list_of_4_ints}achievingaccuracy == 1.0,preds == [0, 1, 1, 0], andfinal_loss < 0.1deterministically across seeds.
27.7.3 Exam Task 27.3 (35 Points): compare_numpy_mlp_vs_logistic_mch(mch_df, seed=42)
Without mutating mch_df:
- Copy
mch_df, replaceanc_visits == 999withnp.nan, title-caseresidence->is_urban, mapwealth_quintile(Poorest..Richest) to ordinal1..5(wealth_num), and drop NaNs across["anc_visits", "maternal_hb_g_dl", "maternal_age_years", "is_urban", "wealth_num", "child_stunted"]. - Perform a stratified 75/25 split (
test_size=0.25, stratify=y, random_state=seed) and fitStandardScaler()strictly onX_train. - Compare a pure-NumPy 2-layer ReLU MLP (
hidden_dim=16, lr=0.1, epochs=400, seed=seed) againstLogisticRegression(max_iter=500), returning{"mlp_auc": round4, "logistic_auc": round4, "mlp_final_loss": round5}.
27.8 Stage 8 — Complete Annotated Solutions & Debugging Post-Mortem
27.8.1 A. Concept & Execution Trace Test Key
- Because matrix multiplication is associative, \((X W_1) W_2 = X (W_1 W_2) = X W_{\text{eff}}\)—a single linear weight matrix \(W_{\text{eff}}\). Without a nonlinear activation between layers, depth adds zero expressive power.
- Any straight line in \(\mathbb{R}^2\) separates the plane into two convex half-spaces. In XOR, the line segment joining the two class-
1points(0, 1)and(1, 0)intersects the segment joining the two class-0points(0, 0)and(1, 1)at(0.5, 0.5), so no single linear boundary can keep both pairs apart (maximum3/4 = 75%accuracy). relu_and_grad([-3.0, 0.0, 2.5, -0.4])returns(array([0.0, 0.0, 2.5, 0.0]), array([0.0, 0.0, 1.0, 0.0])). Neurons0and3have local gradient0.0, so upstream gradients passing through them are multiplied by zero (gating inactive units).- Factoring \(e^{-c}\) from numerator and denominator gives \(\frac{e^{z_i - c}}{\sum_j e^{z_j - c}} = \frac{e^{-c} e^{z_i}}{e^{-c} \sum_j e^{z_j}} = \frac{e^{z_i}}{\sum_j e^{z_j}}\). Setting \(c = \max_j z_j\) guarantees every exponent \(z_i - c \le 0\), so \(e^{z_i - c} \in (0, 1]\) and overflow is mathematically impossible.
- At
logits = [0.0, 0.0]: \(p = [0.5, 0.5]\), mean BCE \(= -\frac{1}{2}(\ln 0.5 + \ln 0.5) = \ln 2 \approx \mathbf{0.69315}\), anddlogits\(= ([0.5, 0.5] - [1.0, 0.0]) / 2 = \mathbf{[-0.25, +0.25]}\). W1: (5, 16),b1: (1, 16),Z1: (32, 16),A1: (32, 16),W2: (16, 1),b2: (1, 1),Z2: (32, 1),dZ2: (32, 1),dW2: (16, 1),dZ1: (32, 16), anddW1: (5, 16). Note every gradient tensor matches its parameter’s exact shape!- Linear regression has a single convex bowl with one weight per feature, so starting at
0converges cleanly. In a multi-neuron hidden layer, setting all weights to0makes all 16 neurons compute identical outputs and receive identical updates forever (symmetry collapse), destroying hidden-layer capacity. - NumPy broadcasts
(10, 1) - (10,)into a(10, 10)matrix! ThenA1.T @ dZ2produces(h, 10)instead of(h, 1), raisingValueError: non-broadcastable output operandwhen updatingW2 -= lr * dW2. - Because ReLU zeroes out roughly half of all symmetric pre-activations (\(z < 0\)), it cuts signal variance in half at each layer. Multiplying the standard Xavier variance \(1 / d_{\text{in}}\) by
2(\(\text{std} = \sqrt{2 / d_{\text{in}}}\)) restores unit variance across forward and backward passes. - With \(w = 2.0, \varepsilon = 0.1\): one-sided gives \((2.1^3 - 2.0^3) / 0.1 = (9.261 - 8.0) / 0.1 = \mathbf{12.61}\) (error
0.61), whereas centered gives \((2.1^3 - 1.9^3) / 0.2 = (9.261 - 6.859) / 0.2 = \mathbf{12.01}\) (error0.01, \(61\times\) tighter because \(O(\varepsilon)\) error terms cancel!).
27.8.2 B. Annotated Solutions — Guided To-Dos (Mirrored in 02_guided_todos_SOLUTION.ipynb)
import numpy as np
# To-Do 27.1
def relu_and_grad(z):
"""Return (ReLU(z), dReLU/dz) as float ndarrays without mutating z."""
z_arr = np.asarray(z, dtype=float)
out = np.maximum(0.0, z_arr)
grad = (z_arr > 0).astype(float)
return (out, grad)
# To-Do 27.2
def stable_softmax(logits):
"""Compute overflow-safe row-wise softmax on a 2D (n, k) array."""
z = np.asarray(logits, dtype=float)
shifted = z - np.max(z, axis=1, keepdims=True)
exp_z = np.exp(shifted)
return exp_z / np.sum(exp_z, axis=1, keepdims=True)
# To-Do 27.3
def binary_bce_loss_and_grad(y_true, logits):
"""Return (mean_bce_round5, dlogits) from binary labels & logits."""
y = np.asarray(y_true, dtype=float)
z = np.asarray(logits, dtype=float)
p_raw = 1.0 / (1.0 + np.exp(-np.clip(z, -500.0, 500.0)))
p = np.clip(p_raw, 1e-12, 1.0 - 1e-12)
loss = -float(np.mean(
y * np.log(p) + (1.0 - y) * np.log(1.0 - p)
))
dlogits = (p - y) / len(y)
return (round(loss, 5), dlogits)
# To-Do 27.4
def mlp_forward_two_layer(X, W1, b1, W2, b2):
"""Run 2-layer ReLU->Sigmoid forward pass; return (probs, cache)."""
X_a = np.asarray(X, dtype=float)
Z1 = X_a @ W1 + b1
A1 = np.maximum(0.0, Z1)
Z2 = A1 @ W2 + b2
probs = 1.0 / (1.0 + np.exp(-np.clip(Z2, -500.0, 500.0)))
cache = {
"X": X_a, "Z1": Z1, "A1": A1,
"Z2": Z2, "probs": probs,
}
return (probs, cache)
# To-Do 27.5
def mlp_backward_two_layer(y_true, cache, W2):
"""Compute analytical BCE backprop gradients for a 2-layer MLP."""
y_col = np.asarray(y_true, dtype=float).reshape(-1, 1)
n = len(y_col)
dZ2 = (cache["probs"] - y_col) / n
dW2 = cache["A1"].T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dA1 = dZ2 @ np.asarray(W2, dtype=float).T
dZ1 = dA1 * (cache["Z1"] > 0).astype(float)
dW1 = cache["X"].T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
return {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2}
# To-Do 27.6
def numerical_gradient_check(loss_fn, W, eps=1e-5):
"""Compute centered finite-difference gradient without mutating W."""
W_work = np.asarray(W, dtype=float).copy()
grad = np.zeros_like(W_work)
for idx in np.ndindex(W_work.shape):
orig = W_work[idx]
W_work[idx] = orig + eps
lp = float(loss_fn(W_work))
W_work[idx] = orig - eps
lm = float(loss_fn(W_work))
W_work[idx] = orig
grad[idx] = (lp - lm) / (2.0 * eps)
return grad27.8.3 C. Annotated Solutions — Chapter 27 Coding Exam (Mirrored in 03_coding_exam_SOLUTION.ipynb)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Exam Task 27.1 (30 pts)
def solve_xor_mlp_numpy(seed=42, epochs=2500, lr=0.5):
"""Train a pure-NumPy 2->8->1 MLP on XOR and return metrics."""
rng = np.random.default_rng(seed)
X = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y = np.array([[0.], [1.], [1.], [0.]])
W1 = rng.normal(0.0, np.sqrt(1.0 / 2), size=(2, 8))
b1 = np.zeros((1, 8), dtype=float)
W2 = rng.normal(0.0, np.sqrt(1.0 / 8), size=(8, 1))
b2 = np.zeros((1, 1), dtype=float)
n = len(X)
for _ in range(epochs):
A1 = np.tanh(X @ W1 + b1)
Z2 = A1 @ W2 + b2
probs = 1.0 / (1.0 + np.exp(-np.clip(Z2, -500.0, 500.0)))
dZ2 = (probs - y) / n
dW2 = A1.T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dZ1 = (dZ2 @ W2.T) * (1.0 - A1 ** 2)
dW1 = X.T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
W1 = W1 - lr * dW1
b1 = b1 - lr * db1
W2 = W2 - lr * dW2
b2 = b2 - lr * db2
A1 = np.tanh(X @ W1 + b1)
p = 1.0 / (1.0 + np.exp(-np.clip(A1 @ W2 + b2, -500.0, 500.0)))
pc = np.clip(p, 1e-12, 1.0 - 1e-12)
loss = -float(np.mean(
y * np.log(pc) + (1.0 - y) * np.log(1.0 - pc)
))
preds = [int(v >= 0.5) for v in p.ravel()]
acc = float(np.mean(np.array(preds) == y.ravel()))
return {
"accuracy": acc,
"final_loss": round(loss, 5),
"preds": preds,
}
# Exam Task 27.2 (35 pts)
def train_numpy_mlp_classifier(
X_train, y_train, X_val, y_val,
hidden_dim=16, lr=0.1, epochs=300, seed=42,
):
"""Train a He-init pure-NumPy 2-layer ReLU MLP binary classifier."""
X_tr = np.asarray(X_train, dtype=float)
y_tr = np.asarray(y_train, dtype=float).reshape(-1, 1)
X_va = np.asarray(X_val, dtype=float)
y_va = np.asarray(y_val, dtype=float).reshape(-1, 1)
n, d_in = X_tr.shape
rng = np.random.default_rng(seed)
W1 = rng.normal(0.0, np.sqrt(2.0 / d_in), size=(d_in, hidden_dim))
b1 = np.zeros((1, hidden_dim), dtype=float)
W2 = rng.normal(
0.0, np.sqrt(2.0 / hidden_dim), size=(hidden_dim, 1)
)
b2 = np.zeros((1, 1), dtype=float)
def _bce(y_c, p_raw):
pc = np.clip(p_raw, 1e-12, 1.0 - 1e-12)
return -float(np.mean(
y_c * np.log(pc) + (1.0 - y_c) * np.log(1.0 - pc)
))
train_losses, val_losses = [], []
for _ in range(epochs):
Z1 = X_tr @ W1 + b1
A1 = np.maximum(0.0, Z1)
Z2 = A1 @ W2 + b2
p_tr = 1.0 / (1.0 + np.exp(-np.clip(Z2, -500.0, 500.0)))
train_losses.append(_bce(y_tr, p_tr))
A1_v = np.maximum(0.0, X_va @ W1 + b1)
Z2_v = A1_v @ W2 + b2
p_va = 1.0 / (1.0 + np.exp(-np.clip(Z2_v, -500.0, 500.0)))
val_losses.append(_bce(y_va, p_va))
dZ2 = (p_tr - y_tr) / n
dW2 = A1.T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dZ1 = (dZ2 @ W2.T) * (Z1 > 0).astype(float)
dW1 = X_tr.T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
W1 = W1 - lr * dW1
b1 = b1 - lr * db1
W2 = W2 - lr * dW2
b2 = b2 - lr * db2
A1_v = np.maximum(0.0, X_va @ W1 + b1)
p_va = 1.0 / (1.0 + np.exp(-np.clip(A1_v @ W2 + b2, -500.0, 500.0)))
val_auc = round(float(roc_auc_score(y_va.ravel(), p_va.ravel())), 4)
return {
"train_losses": train_losses,
"val_losses": val_losses,
"val_roc_auc": val_auc,
"params": {"W1": W1, "b1": b1, "W2": W2, "b2": b2},
}
# Exam Task 27.3 (35 pts)
def compare_numpy_mlp_vs_logistic_mch(mch_df, seed=42):
"""Clean MCH data and benchmark NumPy MLP vs. LogisticRegression."""
work = mch_df.copy()
work["anc_visits"] = work["anc_visits"].replace(999, np.nan)
work["residence"] = (
work["residence"].astype(str).str.strip().str.title()
)
work["is_urban"] = (work["residence"] == "Urban").astype(int)
wmap = {
"Poorest": 1, "Poorer": 2, "Middle": 3,
"Richer": 4, "Richest": 5,
}
work["wealth_num"] = (
work["wealth_quintile"].astype(str).str.strip()
.str.title().map(wmap)
)
feats = [
"anc_visits", "maternal_hb_g_dl",
"maternal_age_years", "is_urban", "wealth_num",
]
clean = work[feats + ["child_stunted"]].dropna()
X = clean[feats].to_numpy(dtype=float)
y = clean["child_stunted"].to_numpy(dtype=int)
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=seed
)
scaler = StandardScaler()
X_tr_s = scaler.fit_transform(X_tr)
X_te_s = scaler.transform(X_te)
log_reg = LogisticRegression(max_iter=500)
log_reg.fit(X_tr_s, y_tr)
log_auc = round(float(
roc_auc_score(y_te, log_reg.predict_proba(X_te_s)[:, 1])
), 4)
rng = np.random.default_rng(seed)
n, d_in = X_tr_s.shape
h = 16
W1 = rng.normal(0.0, np.sqrt(2.0 / d_in), size=(d_in, h))
b1 = np.zeros((1, h), dtype=float)
W2 = rng.normal(0.0, np.sqrt(2.0 / h), size=(h, 1))
b2 = np.zeros((1, 1), dtype=float)
y_col = y_tr.astype(float).reshape(-1, 1)
final_loss = 0.0
for _ in range(400):
Z1 = X_tr_s @ W1 + b1
A1 = np.maximum(0.0, Z1)
Z2 = A1 @ W2 + b2
probs = 1.0 / (1.0 + np.exp(-np.clip(Z2, -500.0, 500.0)))
pc = np.clip(probs, 1e-12, 1.0 - 1e-12)
final_loss = -float(np.mean(
y_col * np.log(pc) + (1.0 - y_col) * np.log(1.0 - pc)
))
dZ2 = (probs - y_col) / n
dW2 = A1.T @ dZ2
db2 = np.sum(dZ2, axis=0, keepdims=True)
dZ1 = (dZ2 @ W2.T) * (Z1 > 0).astype(float)
dW1 = X_tr_s.T @ dZ1
db1 = np.sum(dZ1, axis=0, keepdims=True)
W1 = W1 - 0.1 * dW1
b1 = b1 - 0.1 * db1
W2 = W2 - 0.1 * dW2
b2 = b2 - 0.1 * db2
A1_te = np.maximum(0.0, X_te_s @ W1 + b1)
p_te = 1.0 / (1.0 + np.exp(-np.clip(A1_te @ W2 + b2, -500.0, 500.0)))
mlp_auc = round(float(roc_auc_score(y_te, p_te.ravel())), 4)
return {
"mlp_auc": mlp_auc,
"logistic_auc": log_auc,
"mlp_final_loss": round(final_loss, 5),
}27.8.4 D. Debugging Post-Mortem
- Why Backprop Shape Discipline Beats Guesswork: Ninety percent of pure-NumPy neural network bugs stem from two shape mistakes: forgetting
.reshape(-1, 1)on binary labels (triggering silent(n, n)broadcasting) and forgettingkeepdims=Truewhen summing bias gradients or row maxima. Checking every tensor shape against(n, h)/(d_in, h)eliminates them permanently. - Why Finite-Difference Gradient Checking Matters Even in PyTorch: In Chapter 28, PyTorch’s
autogradwill compute these exact derivatives automatically—yet knowing what happens insideloss.backward()lets you diagnose dead ReLUs, vanishing gradients, exploding logits, and custom loss functions like a deep learning researcher instead of treating frameworks as black boxes. - Honest Tabular Comparisons: Always benchmark any neural model against a strong leak-free classical baseline (
LogisticRegression) on identical stratified splits and train-only scaling. Deep learning is a precision instrument, not a reflex!


