core26 min studyLesson 12 in Engineering

Linear regression as a complete learning experiment

Fit a transparent numerical model, derive its gradient, and diagnose what residuals reveal.

On this page

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 y^=wx+b\widehat y=wx+b. If xx is payload size in megabytes and yy is latency in milliseconds, ww has units of milliseconds per megabyte and bb 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.

y^=Xθ,J(θ)=12n∥Xθ−y∥22\widehat{\mathbf y}=X\theta,\qquad J(\theta)=\frac{1}{2n}\lVert X\theta-\mathbf y\rVert_2^2
Rows of X are training examples and may include a column of ones for the intercept. Squared loss weights large residuals strongly; the factor one-half simplifies differentiation.↔ Scroll wide equations horizontally.

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.

∇θJ=1nXT(Xθ−y),θt+1=θt−η∇J(θt)\nabla_\theta J=\frac{1}{n}X^\mathsf{T}(X\theta-\mathbf y),\qquad \theta_{t+1}=\theta_t-\eta\nabla J(\theta_t)
This gradient assumes the stated smooth squared objective. The learning rate eta must be compatible with the curvature; an arbitrarily large step can increase loss even in this convex problem.↔ Scroll wide equations horizontally.

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.

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.

  1. Predictions are 0 and 0, so residuals are −2 and −4. The objective is (4+16)/4=5.

  2. The weight gradient is [1(−2)+2(−4)]/2=−5; the intercept gradient is (−2−4)/2=−3.

  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.

J(0.5,0.3)=(0.8−2)2+(1.3−4)24=2.1825J(0.5,0.3)=\frac{(0.8-2)^2+(1.3-4)^2}{4}=2.1825
The denominator is twice the number of training examples, matching the declared loss normalization.↔ Scroll wide equations horizontally.
The result

The first step lowers training loss from 5 to 2.1825. It demonstrates the update, not convergence or held-out predictive quality.

Explore the model

Interactive lab

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.

Inspect the slope of a quadraticThis 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. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

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.

Check your understanding

Two identical feature columns appear in X. What follows for unregularized least squares?

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.

ddc13∑i=13(c−yi)2=2(c−4)=0\frac{d}{dc}\frac{1}{3}\sum_{i=1}^3(c-y_i)^2=2(c-4)=0
The constant minimizes a strictly convex quadratic. This calculation is on training targets only.↔ Scroll wide equations horizontally.

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.