Linear regression as a production baseline
A linear baseline is valuable because its assumptions, errors, and serving cost are easy to see.
Support tickets need explainable routing under a 15 ms latency budget.
This chapter moves from fit a transparent reference to package the full pipeline. We will make the idea concrete in a small code example before placing it back inside a production system with 15 ms batch-one latency.
Persist feature order, imputation/scaling state, coefficients, output units, and a serialized batch-one latency test.
Verify the behavior illustrated in least_squares_line.py, then measure decision utility, slice reliability, and system latency.
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
Linear regression is more than a classroom model. It is a fast, inspectable baseline that tells you how much signal a complex system must beat.
The model predicts a conditional mean as an intercept plus weighted features. Each coefficient describes an additive change only under the model’s assumptions and with other included features held fixed; correlation does not turn that coefficient into a causal effect.
Production value comes from stable preprocessing, regularization, residual analysis, and cheap inference. Check errors by slice and across the feature range because a good average can hide curvature, heteroscedasticity, or dangerous extrapolation.
- regularization
- log odds
- Bayes rule
- feature scaling
Follow the reasoning before touching the code.
- 01
Fit a transparent reference
Begin with an intercept and a small set of defensible features under the same split and metric contract as later models.
- 02
Read the residuals
Plot or summarize error versus prediction, time, and critical slices to find curvature, changing variance, and outliers.
- 03
Package the full pipeline
Persist feature order, imputation/scaling state, coefficients, output units, and a serialized batch-one latency test.
xs = [0.0, 1.0, 2.0, 3.0]
ys = [1.0, 3.0, 5.0, 7.0]
x_mean = sum(xs) / len(xs)
y_mean = sum(ys) / len(ys)
slope = sum((x - x_mean) * (y - y_mean) for x, y in zip(xs, ys))
slope /= sum((x - x_mean) ** 2 for x in xs)
intercept = y_mean - slope * x_mean
predictions = [intercept + slope * x for x in xs]
residuals = [y - prediction for y, prediction in zip(ys, predictions)]
mae = sum(abs(error) for error in residuals) / len(residuals)
print({"intercept": intercept, "slope": slope, "mae": mae})
print("x=4 prediction", intercept + slope * 4)Fit an intercept and slope with the closed-form least-squares solution.
What to notice
- The fitted rule is y = 1 + 2x, so all training residuals and MAE are zero.
- The x=4 result is an extrapolation beyond observed x values even though the arithmetic is simple.
YOUR TURN Pause and predict before revealing the answer.
Change the last target from 7 to 20. What behavior of squared-error fitting should you expect?
Need a hint?
Large residuals are squared, so one distant point has disproportionate influence.
Check your reasoning
The line rotates upward toward the outlier, increasing errors for the first three rows; residual inspection or a robust alternative would expose the issue.
Evaluation, Data & features
Connect the chapter to the course’s quantitative spine.
A linear baseline is valuable because its assumptions, errors, and serving cost are easy to see. The logistic probability below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Logistic probability
| Symbol | Meaning / shape / unit |
|---|---|
x | feature vector |
β | learned coefficients |
xᵀβ | linear log-odds score |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: x, β, xᵀβ.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c04(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Regularization boundary lab
Increase regularization and watch complexity trade against margin violations.
Assumption: Synthetic standardized two-feature classification problem.
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| x=-2 | logit -2.57 | negative |
| x=-1 | logit -1.29 | negative |
| x=0 | logit 0.00 | negative |
| x=1 | logit 1.29 | positive |
| x=2 | logit 2.57 | positive |
Trace the complete operating path.
Carry the chapter’s central idea into the system: A linear baseline is valuable because its assumptions, errors, and serving cost are easy to see. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Fit a transparent reference” into a written invariant and a failing test.
- 02
Promote least_squares_line.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Package the full pipeline” as the release checkpoint: Persist feature order, imputation/scaling state, coefficients, output units, and a serialized batch-one latency test.
- 04
Serve or materialize behind explicit 15 ms batch-one latency.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
Unscaled revenue dominates kNN distance while perfectly separating features destabilize unregularized logistic coefficients. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Explainable ticket-routing baseline
Compare linear/logistic regression, Naive Bayes, kNN, and SVM under one evaluation and serving contract.
- Preprocessing parity
- Model-family comparison
- Calibration and cost policy
- Serialized latency test
Read primary material with a purpose.
Return to the opening failure.
Compare quality, calibration, latency, memory, and interpretability under one stable validation contract.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a justified baseline across regression, naive bayes, knn, and svm.