Linear regression as a complete learning experiment
Fit a transparent numerical model, derive its gradient, and diagnose what residuals reveal.
On this page
The question for today
What you’ll understand
- Interpret weights and intercept with units.
- Derive and apply the squared-error gradient.
- Distinguish numerical fitting from causal explanation.
Predicting latency from payload size is a useful first learning problem because every part can be inspected. A line has few parameters, but choosing a loss, fitting only on training data, handling units, and checking held-out residuals already form the core of a serious workflow. A small model also provides a reference against which a larger system must justify its additional complexity.
A line is a hypothesis with units
For one feature, predict . If is payload size in megabytes and is latency in milliseconds, has units of milliseconds per megabyte and has units of milliseconds. The intercept is the predicted value at zero input, which may lie outside observed data. Do not force it to be physically meaningful without checking whether the linear relationship is sensible near zero. A line is a local statistical hypothesis, not a law of the service.
With multiple features, each weight describes a conditional change while the other model inputs stay fixed. Correlated inputs make this interpretation fragile: request size and compressed size may carry nearly the same information, so many coefficient combinations predict similarly. A predictive coefficient does not establish the effect of an intervention. Changing payload size may also change cache behavior, routing, or client type, all of which can break an observational interpretation.
Derive an update instead of memorizing it
A residual is prediction minus observed target. Increasing a weight changes each prediction in proportion to that example's feature value, so its gradient is an average of residual times feature. Gradient descent subtracts a small multiple of that gradient. At a stationary point the residual vector is orthogonal to every column of the design matrix: no small move along an available feature direction can lower squared error. This geometric condition is more informative than treating the optimizer as a black box.
A unique least-squares coefficient vector requires independent columns. When columns are dependent, fitted predictions may still be unique while coefficients are not. Solve least squares using stable numerical methods such as QR or singular-value decomposition rather than explicitly forming a matrix inverse. Standardizing features can improve optimization conditioning, but its mean and scale must come from training data. Rescaling does not add predictive information or repair a poorly specified task.
Read the residuals and the evaluation context
Plot residuals against prediction, feature values, and time. A curved pattern suggests missing nonlinearity; widening spread suggests changing noise variance; a time trend suggests drift. One extreme target can dominate squared loss. Absolute-error or robust losses express different priorities, and they should be chosen with the problem rather than used to hide inconvenient examples. A log target may help multiplicative noise but changes what errors mean when predictions are transformed back.
Evaluate on a held-out partition using units people understand, such as mean absolute latency error, alongside the training objective. Compare against predicting the training mean. A small training residual is not evidence of useful extrapolation: a line fit between one and ten megabytes may fail at a gigabyte when a storage threshold changes. Record the input range and intended use. The best lesson from a linear baseline is often exactly where its assumptions stop describing the system.
Work it through
One gradient step you can audit
Use examples (1,2) and (2,4), start with w=0 and b=0, and use half the mean squared error with learning rate 0.1.
Predictions are 0 and 0, so residuals are −2 and −4. The objective is (4+16)/4=5.
The weight gradient is [1(−2)+2(−4)]/2=−5; the intercept gradient is (−2−4)/2=−3.
Subtract 0.1 times each gradient: w becomes 0.5 and b becomes 0.3. New predictions are 0.8 and 1.3; the objective becomes (1.44+7.29)/4=2.1825.
The first step lowers training loss from 5 to 2.1825. It demonstrates the update, not convergence or held-out predictive quality.
The living notebook
Explore the model
Interactive lab · function
Inspect the slope of a quadratic
The function lab plots y=ax² with controls for a and x, a tangent of slope 2ax, and accumulated area. Read this as a simple objective whose derivative drives an update; it does not fit the regression examples or plot an arbitrary prediction model.
- y at chosen x
- 0.608
- Tangent slope · 2ax
- 1.35
- Signed area · ax³/3
- 0.182
This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forA quadratic objective has a local slope that changes with parameter position, making a gradient direction inspectable.
Pause & reason
Check your understanding
Your turn
Try it yourself
For targets 2, 4, and 6, find the best constant predictor under squared loss and its mean squared error.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Differentiate the average squared distance from a constant c, or balance the residuals.
Compare with the solution
The mean is c=4. Residuals are 2, 0, and −2, whose squares average to 8/3. This is the baseline a feature-based model should improve on held-out examples; computing the mean from test targets would leak evaluation information.
Keep the idea
Take it with you
- Weights need units and a clearly stated input range.
- The gradient is a residual-feature correlation.
- Residual structure reveals assumptions a single score can hide.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.