Week 8 Checkpoint: Linear Regression by Hand
- Reproduce the week's core machinery from memory: dot products, matmul-as-transformation, SVD truncation, gradients, the chain rule, GD regimes
- Derive the MSE gradient for linear regression by hand and verify it with gradcheck
- Train w and b with your own gradient descent and read the loss curves
- Produce a learning-rate ablation table and defend the chosen rate
- Write the intuition paragraph connecting this week to embeddings, backprop, and LoRA
| Closed-book recall drills over Days 50β55 | 25 min |
| Derive + gradcheck the MSE gradient | 15 min |
| Explain-out-loud rehearsal | 10 min |
| Build: train, ablate, and write the report | 55 min |
| Cumulative quiz + flashcard deck drill | 15 min |
Builds on: Day 50 β Vectors & dot products Β· Day 53 β Derivatives & gradients Β· Day 54 β Chain rule Β· Day 55 β Gradient descent lab
Seven days ago, vectors were arrows and derivatives were a shower dial. Today they conspire: you will teach a line to fit data, using nothing but this week's parts. The model is one dot product (wΒ·x + b β Day 50). The loss is a bowl whose height is squared error. The gradient β derived by you, with Day 54's chain rule, checked by Day 53's checker β tells each parameter which way to nudge. And Day 55's descent loop rolls the parameters downhill until the line lies snugly through the cloud of points. Machine learning, complete, with no library and no mystery.
Why spend a checkpoint on the simplest model in the field? Because linear regression is the hydrogen atom of ML: every phenomenon you will ever debug β loss curves, learning rates, divergence, convergence β appears here in its purest form, small enough to inspect every number. The recall drills come first, as always: what you can rebuild from an empty file is what you actually own. When Day 71 shows you sklearn fitting this same model in one line, and Day 85 stacks these dot-product neurons into networks, you will know exactly what is inside the box β because you built the box.
"Implement linear regression with gradient descent" is a real screening question for ML-adjacent roles β asked precisely because it composes vectors, gradients, and optimization into twenty lines and exposes whether the candidate owns the parts. It is also your first end-to-end training run: initialize β forward β loss β gradient β step β loss curve, the exact skeleton of every PyTorch loop you will write from Day 88 to the capstone. When a training run misbehaves in month six, you will debug it by shrinking the problem back toward today's transparent twenty lines β the hydrogen atom is also the diagnostic instrument.
Guided practice
Closed-book recall drills β Week 8 edition
25 minEditor closed. Write from memory, then diff against your notes and lab files; score each solid / shaky / gone.
- Day 50: cosine similarity formula; typical cosine of random unit vectors in ββ·βΆβΈ and why; the reason pipelines normalize embeddings.
- Day 51: what a matrix's columns tell you; is AB = BA?; the shape story of (1000Γ768)@(768Γ512) and why batching = matmul matters.
- Day 52: eigenvector in one line; SVD's three-move anatomy; the LoRA bet in one sentence.
- Day 53: central-difference formula; why h has a floor; what direction βf points and what is perpendicular to it.
- Day 54: compute by graph-walk: dL/dw for L = (wΒ·x β y)Β² at w=2, x=3, y=5. (Answer: 2(6β5)Β·3 = 6. No peeking.)
- Day 55: the three LR regimes; why canyons zig-zag; the momentum update from memory.
Shaky/gone items β revisit list; re-read ONLY those sections before building.
Derive, check, and dry-run the regression gradient
15 min- On paper: derive βL/βw and βL/βb for MSE from scratch, showing the chain rule and the add-across-points step. Compare against the tech section only when done.
- Generate the data (starter): 200 points, x ~ N(0, 2), y = 3x β 2 + noise(Ο=1). Note the ground truth you will hunt: w=3, b=β2, and a loss floor near ΟΒ² = 1.
- Implement
mse_loss(w, b)andmse_grad(w, b)vectorized (two reductions, no loops), then verify the gradient with your Day 53gradcheckat three points, e.g. (0,0), (3,β2), (β1, 4). All must pass at 1e-6 BEFORE training β never descend an unchecked gradient. - Sanity dry-run: at (w,b) = (0,0), state the SIGNS of both gradient components from the formulas alone (residuals are mostly negative where y is positiveβ¦), then confirm numerically.
On your own
Explain it like a colleague is watching
10 minBefore the build, rehearse the understanding: set a 6-minute timer and explain out loud, as if pair-programming, (1) why the b-gradient is the mean residual (what the line does when it is uniformly too low), (2) why the w-gradient is a residual-input correlation (what tilting fixes), and (3) what the loss floor will be and why no amount of training goes below it.
Goal: no formula recited without its geometric reading. If any explanation stalls, that is your weakest link β reinforce it before training, because the write-up (and one day an interviewer) will ask exactly these three.
Linear regression by hand β the Week 8 build
Create linreg_by_hand.py + linreg_report.md. The build: import your Day 55 gd (or reimplement), train (w, b) from (0, 0) on the generated data, logging loss per step. Produce: (1) the loss-curve table (or matplotlib plot if you prefer) for the chosen Ξ·; (2) an LR ablation over Ξ· β {0.001, 0.01, 0.05, 0.2, 0.5}: final loss, steps to within 1% of floor, verdict (creep/converged/oscillated/diverged); (3) recovered w, b vs ground truth 3, β2, and the loss floor vs ΟΒ² = 1; (4) a momentum bonus run (Ξ²=0.9) with its speedup; (5) the intuition paragraph β 8β12 sentences telling the whole story (dot product β residuals β chain-rule gradient β downhill loop β noise floor) with zero formulas, as if to a smart PM. Commit everything; Day 71 will rerun this exact fit with sklearn and your numbers must match.
Common mistakes & misconceptions
- Training on an unchecked gradient. A sign error still descends β just to the wrong place, slowly and confusingly. Gradcheck first is a two-second insurance policy; make it a permanent habit (Day 86 depends on it).
- Expecting loss β 0. The data contains noise ΟΒ²; the best possible line floors there. Chasing zero means chasing noise β your first encounter with the overfitting boundary (Day 76 formalizes it).
- Reviewing by re-reading lab files instead of rebuilding from an empty buffer. The checkpoint's recall drills exist because retrieval, not recognition, is what sticks β same rule as Day 49.
- Forgetting to average (or consistently sum) the loss and gradient. Mixing mean-loss with sum-gradient silently scales your effective learning rate by N β a classic "why does Ξ·=0.01 diverge here?" bug.
- Sweeping Ξ· in tiny increments. Regimes live decades apart; scan powers of ten first (Day 55's rule), then refine. Your ablation table should SHOW the regimes, not five flavors of convergence.
- Writing the intuition paragraph with formulas. The point is the FDE muscle: if you cannot tell the story without symbols, the understanding is still borrowed. Rewrite until a PM could repeat it.
Q1. For MSE linear regression, βL/βb = (2/N)Β·Ξ£(Ε·α΅’ β yα΅’). If the line currently sits uniformly BELOW the data, this gradient isβ¦
Q2. Your regression loss curve plunges, then flattens at β 1.02 and never improves. The injected noise had Ο = 1. The right conclusion isβ¦
Q3. The MSE loss surface in (w, b) is convex. What does this guarantee that will NOT hold for the neural networks of Phase 5?
Go deeper β curated resources
- The closed-form ending β Convex + quadratic means calculus can skip the loop: setting the gradient to zero gives the normal equations, solvable directly (np.linalg.lstsq β which runs on Day 52's SVD). Fit your data with it and confirm it matches your GD answer; then note why closed forms die the moment models go nonlinear.
- Recall drills scored; weak sections restudied from the revisit list
- Gradient derived on paper and gradcheck-passed before training
- Model recovers (3, β2) within tolerance; floor explained via ΟΒ²
- Ablation table + loss curve + intuition paragraph committed
- Cumulative quiz β₯ 2/3 (follow revisit pointers for misses)
β Back: The whole week fit in twenty lines: Day 50's dot product is the model, Day 54's chain rule derived the gradient, Day 53's checker certified it, Day 55's loop trained it β and even Day 52 lurks in why the (w, b) valley is mildly canyon-shaped. Phase 2 shows too: the report habit comes from Day 49's design-doc-first discipline.
Forward β: Day 57 starts probability β the second pillar of ML math. Day 71 refits today's model with sklearn in one line (and your numbers must agree); Day 72 swaps the loss and gets classification; Day 85 stacks these neurons into networks; Day 86 automates today's hand gradient into backprop. The intuition paragraph is your first artifact in the Day 105 explainer lineage.
Unlocks: D57 Probability Fundamentals Β· D71 ML Framing & Linear Regression