47. Calculus and optimization for ML — Mini-project
Deep learning libraries like PyTorch hide automatic differentiation and adaptive optimizers behind two lines (loss.backward() and optimizer.step()). To trust those lines — and debug them when gradients explode, vanish, or stall — build them yourself from scratch.
In this mini-project you will create MicroGrad-DS, a NumPy-backed reverse-mode autograd engine (Tensor) and optimizer suite (SGDMomentum and Adam) that handles both scalars and mini-batch matrices. You will verify every gradient of a 2-layer neural network against torch.autograd to 1e-5, train the network on real customer churn data from data/customers.csv, compare SGD-with-momentum against Adam on a convergence plot, and evaluate held-out test ROC-AUC and log loss.
Dataset
Section titled “Dataset”data/customers.csv: 5,000 subscription customers (19.26% churn rate), documented in the data dictionary. Use these 10 numeric features to predict churned:
| Feature | Notes |
|---|---|
age, tenure_months |
customer age (18–80) and tenure in months (0–72) |
monthly_charges, avg_session_minutes |
continuous spend and engagement |
support_tickets, logins_last_30d |
count features strongly linked to churn |
has_autopay |
binary 0/1 indicator |
is_month_to_month, is_two_year |
derived binary indicators from contract (one-year is the reference level) |
is_electronic_check |
derived binary indicator for payment_method == "electronic_check" |
target: churned |
binary 0/1 target |
Requirements
Section titled “Requirements”Your script must:
- Implement a
Tensorclass backed bynp.float64arrays that supports+,-,*,@,**,.exp(),.log(),.tanh(),.relu(),.sigmoid(),.sum(),.mean(), and.backward()using reverse topological order. - Handle NumPy broadcasting properly during backward passes (for example, adding a
(1, hidden)bias to a(batch, hidden)activation must sum incoming gradients along axis 0). - Verify
Tensor.backward()on both a scalar expression (matchingtorch.autogradto1e-12) and on all four parameter tensors (W1,b1,W2,b2) of a 2-layer MLP (10 -> 16 -> 1) on a real batch fromcustomers.csv(asserting max absolute gradient difference< 1e-5againsttorch.autograd). - Implement two optimizer classes —
SGDMomentumandAdam(with bias correction) — sharing a clean.zero_grad()and.step()interface. - Prepare
data/customers.csvwith a leak-free stratified 80/20 train/test split (train_test_split(..., stratify=y, random_state=42)), standardizing features using training statistics only. - Train two identically initialized copies of the 2-layer MLP (
tanhhidden layer,sigmoidoutput, binary cross-entropy loss plus L2 weight decay1e-3) for 40 epochs with batch size 128: one withSGDMomentum, one withAdam. - Plot the epoch-by-epoch training log-loss curves of both optimizers on one figure.
- Report test log loss, test accuracy, and test ROC-AUC for both optimizers, verifying that both achieve test ROC-AUC above
0.80.
Step plan
Section titled “Step plan”-
Write
_unbroadcast(grad, shape). Whenever forward broadcasting expanded a dimension of size 1 (or added leading dimensions), sumgradback down toshapeso every parameter receives a gradient matching its own shape. -
Build
Tensoroperations and.backward(). Implement element-wise+,-,*,**, matrix multiplication@, activations (exp,log,tanh,relu,sigmoid), and reductions (sum,mean). Collect nodes via post-order DFS and run_backward()in reverse topological order. -
Test on a scalar expression first. Verify a small expression with fan-out (reusing the same variable twice) against
torch.autogradin float64. -
Implement
SGDMomentumandAdam. Keep velocity/moment arrays per parameter and updateparam.datain place inside.step(). Include bias correction1 - beta1**tand1 - beta2**tinAdam. -
Prepare
customers.csvwith zero leakage. Split 80/20 first, then compute mean and standard deviation on the training split only and apply them to both splits. -
Verify MLP gradients against PyTorch. Initialize
W1, b1, W2, b2with a fixed seed, run one forward + backward pass on a mini-batch in both MicroGrad-DS andtorch(float64), and assertmax_diff < 1e-5on every parameter. -
Train and compare optimizers. Run 40 mini-batch epochs from identical starting weights with
SGDMomentumandAdam, plot their training curves, and compute held-out test log loss, accuracy, and ROC-AUC.
A starter skeleton to build from:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport torchfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_split
torch.set_num_threads(1)
def unbroadcast(grad: np.ndarray, shape: tuple[int, ...]) -> np.ndarray: """Sum gradient along broadcasted axes so it matches `shape`.""" # TODO: reduce extra leading dims and size-1 dims raise NotImplementedError
class Tensor: def __init__(self, data, children: tuple["Tensor", ...] = ()) -> None: self.data = np.asarray(data, dtype=np.float64) self.grad = np.zeros_like(self.data) self._prev = set(children) self._backward = lambda: None
# TODO: +, -, *, @, **, exp, log, tanh, relu, sigmoid, sum, mean, backward
class SGDMomentum: # TODO: __init__(params, lr, beta), zero_grad(), step() pass
class Adam: # TODO: __init__(params, lr, beta1, beta2, eps), zero_grad(), step() pass
# TODO: load customers.csv, split 80/20, standardize on train only# TODO: verify 2-layer MLP gradients vs torch.autograd (< 1e-5)# TODO: train with SGDMomentum vs Adam, plot curves, print test metricsRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Autograd operations | 4 | All required ops (+, -, *, @, **, exp, log, tanh, relu, sigmoid, sum, mean) work on scalars and 2D arrays |
| Broadcasting & topological backprop | 3 | _unbroadcast handles biases and scalars; shared nodes accumulate with += in reverse topological order |
| PyTorch gradient check | 3 | Every parameter (W1, b1, W2, b2) matches torch.autograd within 1e-5 (float64 reaches 1e-14) |
| Optimizers | 3 | SGDMomentum and bias-corrected Adam implement .zero_grad() and .step() cleanly |
| Leak-free data pipeline | 2 | Split happens before standardization; training mean/std applied to test split |
| Training & convergence plot | 2 | Identical starting weights for both optimizers; clean, labeled loss-curve figure |
| Test evaluation | 2 | Test log loss, accuracy, and ROC-AUC reported on the held-out split (ROC-AUC > 0.80) |
| Code quality | 1 | Type hints, concise functions, no warnings, reproducible seeds |
| Total | 20 | 16 or more: ready for Module 48 |
Stretch goals
Section titled “Stretch goals”- Add a
.log_softmax()/ cross-entropy method toTensorand train a 3-class sentiment MLP ondata/reviews.csv. - Add decoupled weight decay (AdamW) by subtracting
lr * weight_decay * p.datadirectly inAdam.step()instead of adding L2 to the loss, and compare test ROC-AUC. - Implement a cosine annealing learning-rate schedule and check whether lowering
lrin the final 10 epochs smooths test loss. - Add
Dropout(with atraining: boolflag) and a validation split for early stopping. - Add gradient clipping (
clip_grad_norm(params, max_norm)) and test it on a deeper 4-layer network.
Reference solution
Section titled “Reference solution”Try building MicroGrad-DS yourself first. Compare your implementation and numbers with this reference solution afterward.
Reference solution
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport torchfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_split
torch.set_num_threads(1)np.set_printoptions(precision=4, suppress=True)
def unbroadcast(grad: np.ndarray, shape: tuple[int, ...]) -> np.ndarray: """Sum out axes that were expanded by NumPy broadcasting.""" while grad.ndim > len(shape): grad = grad.sum(axis=0) for axis, size in enumerate(shape): if size == 1 and grad.shape[axis] != 1: grad = grad.sum(axis=axis, keepdims=True) return grad
class Tensor: """Scalar and 2D-array reverse-mode autograd node."""
def __init__(self, data, children: tuple["Tensor", ...] = ()) -> None: self.data = np.asarray(data, dtype=np.float64) self.grad = np.zeros_like(self.data) self._prev = set(children) self._backward = lambda: None
@staticmethod def _wrap(other) -> "Tensor": return other if isinstance(other, Tensor) else Tensor(other)
def __add__(self, other) -> "Tensor": other = self._wrap(other) out = Tensor(self.data + other.data, (self, other))
def _backward() -> None: self.grad += unbroadcast(out.grad, self.data.shape) other.grad += unbroadcast(out.grad, other.data.shape)
out._backward = _backward return out
def __neg__(self) -> "Tensor": return self * (-1.0)
def __sub__(self, other) -> "Tensor": return self + (-self._wrap(other))
def __mul__(self, other) -> "Tensor": other = self._wrap(other) out = Tensor(self.data * other.data, (self, other))
def _backward() -> None: self.grad += unbroadcast(other.data * out.grad, self.data.shape) other.grad += unbroadcast(self.data * out.grad, other.data.shape)
out._backward = _backward return out
def __matmul__(self, other) -> "Tensor": other = self._wrap(other) out = Tensor(self.data @ other.data, (self, other))
def _backward() -> None: self.grad += out.grad @ other.data.T other.grad += self.data.T @ out.grad
out._backward = _backward return out
def __pow__(self, power: float) -> "Tensor": out = Tensor(self.data**power, (self,))
def _backward() -> None: self.grad += (power * (self.data ** (power - 1))) * out.grad
out._backward = _backward return out
def exp(self) -> "Tensor": e = np.exp(self.data) out = Tensor(e, (self,))
def _backward() -> None: self.grad += e * out.grad
out._backward = _backward return out
def log(self) -> "Tensor": out = Tensor(np.log(self.data), (self,))
def _backward() -> None: self.grad += (1.0 / self.data) * out.grad
out._backward = _backward return out
def tanh(self) -> "Tensor": t = np.tanh(self.data) out = Tensor(t, (self,))
def _backward() -> None: self.grad += (1.0 - t**2) * out.grad
out._backward = _backward return out
def relu(self) -> "Tensor": out = Tensor(np.maximum(0.0, self.data), (self,))
def _backward() -> None: self.grad += (self.data > 0.0) * out.grad
out._backward = _backward return out
def sigmoid(self) -> "Tensor": s = 1.0 / (1.0 + np.exp(-np.clip(self.data, -500.0, 500.0))) out = Tensor(s, (self,))
def _backward() -> None: self.grad += s * (1.0 - s) * out.grad
out._backward = _backward return out
def sum(self) -> "Tensor": out = Tensor(self.data.sum(), (self,))
def _backward() -> None: self.grad += np.ones_like(self.data) * out.grad
out._backward = _backward return out
def mean(self) -> "Tensor": n = float(self.data.size) out = Tensor(self.data.mean(), (self,))
def _backward() -> None: self.grad += (np.ones_like(self.data) / n) * out.grad
out._backward = _backward return out
def backward(self) -> None: topo: list[Tensor] = [] visited: set[Tensor] = set()
def build(node: Tensor) -> None: if node not in visited: visited.add(node) for child in node._prev: build(child) topo.append(node)
build(self) self.grad = np.ones_like(self.data) for node in reversed(topo): node._backward()
# Scalar autograd sanity check (including fan-out reuse of `a`)a, b = Tensor(1.2), Tensor(-0.7)y_s = ((a * b + a**2).tanh().exp() + a.relu()).log()y_s.backward()
ta = torch.tensor(1.2, dtype=torch.float64, requires_grad=True)tb = torch.tensor(-0.7, dtype=torch.float64, requires_grad=True)ty_s = torch.log(torch.exp(torch.tanh(ta * tb + ta**2)) + torch.relu(ta))ty_s.backward()scalar_err = max( abs(float(a.grad) - ta.grad.item()), abs(float(b.grad) - tb.grad.item()))print(f"scalar check max diff vs torch: {scalar_err:.2e}")assert scalar_err < 1e-12scalar check max diff vs torch: 0.00e+00class SGDMomentum: """Mini-batch SGD with heavy-ball momentum."""
def __init__( self, params: list[Tensor], lr: float = 0.05, beta: float = 0.9 ) -> None: self.params = params self.lr = lr self.beta = beta self.vel = [np.zeros_like(p.data) for p in params]
def zero_grad(self) -> None: for p in self.params: p.grad.fill(0.0)
def step(self) -> None: for i, p in enumerate(self.params): self.vel[i] = self.beta * self.vel[i] + p.grad p.data -= self.lr * self.vel[i]
class Adam: """Adaptive Moment Estimation with bias correction."""
def __init__( self, params: list[Tensor], lr: float = 0.01, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8, ) -> None: self.params = params self.lr = lr self.beta1 = beta1 self.beta2 = beta2 self.eps = eps self.t = 0 self.m = [np.zeros_like(p.data) for p in params] self.v = [np.zeros_like(p.data) for p in params]
def zero_grad(self) -> None: for p in self.params: p.grad.fill(0.0)
def step(self) -> None: self.t += 1 for i, p in enumerate(self.params): self.m[i] = self.beta1 * self.m[i] + (1.0 - self.beta1) * p.grad self.v[i] = self.beta2 * self.v[i] + (1.0 - self.beta2) * (p.grad**2) m_hat = self.m[i] / (1.0 - self.beta1**self.t) v_hat = self.v[i] / (1.0 - self.beta2**self.t) p.data -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)df = pd.read_csv("data/customers.csv")df["is_month_to_month"] = (df["contract"] == "month-to-month").astype(float)df["is_two_year"] = (df["contract"] == "two-year").astype(float)df["is_electronic_check"] = (df["payment_method"] == "electronic_check").astype(float)
FEATURES = [ "age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay", "is_month_to_month", "is_two_year", "is_electronic_check",]X_all = df[FEATURES].to_numpy(dtype=float)y_all = df["churned"].to_numpy(dtype=float)
X_tr_raw, X_te_raw, y_tr_1d, y_te_1d = train_test_split( X_all, y_all, test_size=0.2, stratify=y_all, random_state=42)mu = X_tr_raw.mean(axis=0)sigma = X_tr_raw.std(axis=0)X_train = (X_tr_raw - mu) / sigmaX_test = (X_te_raw - mu) / sigmay_train, y_test = y_tr_1d.reshape(-1, 1), y_te_1d.reshape(-1, 1)print(f"train={X_train.shape}, test={X_test.shape}, churn_rate={y_train.mean():.4f}")
def init_mlp(n_in: int, n_hidden: int, seed: int = 7) -> list[Tensor]: g = np.random.default_rng(seed) W1 = Tensor(g.normal(0.0, np.sqrt(1.0 / n_in), size=(n_in, n_hidden))) b1 = Tensor(np.zeros((1, n_hidden))) W2 = Tensor(g.normal(0.0, np.sqrt(1.0 / n_hidden), size=(n_hidden, 1))) b2 = Tensor(np.zeros((1, 1))) return [W1, b1, W2, b2]
def mlp_forward(params: list[Tensor], X_batch: np.ndarray) -> Tensor: W1, b1, W2, b2 = params h = (Tensor(X_batch) @ W1 + b1).tanh() return (h @ W2 + b2).sigmoid()
def bce_l2_loss( params: list[Tensor], X_batch: np.ndarray, y_batch: np.ndarray, wd: float = 1e-3) -> Tensor: p = mlp_forward(params, X_batch) eps = 1e-12 p_safe = p * (1.0 - 2 * eps) + eps y_t = Tensor(y_batch) neg_term = (Tensor(1.0) - y_t) * (Tensor(1.0) - p_safe).log() bce = -(y_t * p_safe.log() + neg_term).mean() W1, _, W2, _ = params reg = ((W1**2).sum() + (W2**2).sum()) * (0.5 * wd) return bce + reg
# Verify every MLP parameter gradient against PyTorch on a 64-row batchparams_chk = init_mlp(X_train.shape[1], 16, seed=7)xb, yb = X_train[:64], y_train[:64]loss_mg = bce_l2_loss(params_chk, xb, yb, wd=1e-3)loss_mg.backward()
t_params = [ torch.tensor(p.data.copy(), dtype=torch.float64, requires_grad=True) for p in params_chk]tX = torch.tensor(xb, dtype=torch.float64)ty = torch.tensor(yb, dtype=torch.float64)th = torch.tanh(tX @ t_params[0] + t_params[1])tp = torch.sigmoid(th @ t_params[2] + t_params[3])tp_safe = tp * (1.0 - 2e-12) + 1e-12t_bce = -(ty * torch.log(tp_safe) + (1.0 - ty) * torch.log(1.0 - tp_safe)).mean()t_reg = 0.5 * 1e-3 * ((t_params[0] ** 2).sum() + (t_params[2] ** 2).sum())(t_bce + t_reg).backward()
for name, mp, tp_node in zip( ["W1", "b1", "W2", "b2"], params_chk, t_params, strict=True): diff = float(np.max(np.abs(mp.grad - tp_node.grad.numpy()))) print(f"{name} {str(mp.data.shape):8} max |grad diff| vs PyTorch = {diff:.2e}") assert diff < 1e-5train=(4000, 10), test=(1000, 10), churn_rate=0.1925W1 (10, 16) max |grad diff| vs PyTorch = 1.39e-17b1 (1, 16) max |grad diff| vs PyTorch = 1.39e-17W2 (16, 1) max |grad diff| vs PyTorch = 4.86e-17b2 (1, 1) max |grad diff| vs PyTorch = 2.78e-17def train_mlp( opt_cls, opt_kwargs: dict, epochs: int = 40, batch_size: int = 128) -> tuple[list[Tensor], list[float]]: params = init_mlp(X_train.shape[1], 16, seed=7) opt = opt_cls(params, **opt_kwargs) batch_rng = np.random.default_rng(123) history = [] for _ in range(epochs): perm = batch_rng.permutation(len(y_train)) for batch in np.array_split(perm, len(y_train) // batch_size): opt.zero_grad() loss = bce_l2_loss(params, X_train[batch], y_train[batch], wd=1e-3) loss.backward() opt.step() full_loss = float(bce_l2_loss(params, X_train, y_train, wd=0.0).data) history.append(full_loss) return params, history
def evaluate(params: list[Tensor], X_eval: np.ndarray, y_eval: np.ndarray) -> dict: probs = mlp_forward(params, X_eval).data.ravel() y_flat = y_eval.ravel() p_clip = np.clip(probs, 1e-12, 1.0 - 1e-12) ll_terms = y_flat * np.log(p_clip) + (1 - y_flat) * np.log(1 - p_clip) logloss = float(-np.mean(ll_terms)) acc = float(np.mean((probs >= 0.5) == y_flat)) auc = float(roc_auc_score(y_flat, probs)) return {"log_loss": logloss, "acc": acc, "roc_auc": auc}
p_sgd, hist_sgd = train_mlp(SGDMomentum, {"lr": 0.05, "beta": 0.9})p_adam, hist_adam = train_mlp(Adam, {"lr": 0.01})
for label, params in [("SGDMomentum", p_sgd), ("Adam", p_adam)]: m = evaluate(params, X_test, y_test) print( f"{label:12} test log_loss={m['log_loss']:.4f}, " f"acc={m['acc']:.4f}, ROC-AUC={m['roc_auc']:.4f}" ) assert m["roc_auc"] > 0.80
fig, ax = plt.subplots(figsize=(6.8, 4.0))ax.plot(range(1, len(hist_sgd) + 1), hist_sgd, lw=2, label="SGDMomentum (lr=0.05)")ax.plot(range(1, len(hist_adam) + 1), hist_adam, lw=2, label="Adam (lr=0.01)")ax.set_xlabel("epoch")ax.set_ylabel("training binary log loss")ax.set_title("MicroGrad-DS 2-layer MLP on customer churn")ax.legend()fig.tight_layout()plt.show()SGDMomentum test log_loss=0.3725, acc=0.8450, ROC-AUC=0.8265Adam test log_loss=0.3680, acc=0.8440, ROC-AUC=0.8301
How it works:
- Broadcasting in reverse: When forward addition broadcasts a
(1, 16)bias across a(128, 16)mini-batch,unbroadcastsums the(128, 16)upstream gradient over axis0sob1.gradhas shape(1, 16). - PyTorch parity: Comparing all four parameter tensors (
W1,b1,W2,b2) againsttorch.float64confirms errors on the order of1e-16— proving every forward op, backward rule, and topological ordering is exact. - Zero leakage: Both the standardization statistics and the training loops see only the 4,000 training rows; the 1,000 test rows are evaluated only at the end.
- Optimizer comparison: Both
SGDMomentumandAdamconverge cleanly to ~0.82+ ROC-AUC on held-out customers, capturing non-linear churn patterns (such as early tenure and low login counts) directly through our hand-built autograd engine.
Alternative: In production, replace Tensor and Adam with torch.nn.Sequential and torch.optim.AdamW (Module 42) for GPU acceleration and fused kernels — now knowing the exact calculus running underneath every call.