Chapter 1 · Frame and baseline

Linear regression as a production baseline

A linear baseline is valuable because its assumptions, errors, and serving cost are easy to see.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

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.

Decision

Persist feature order, imputation/scaling state, coefficients, output units, and a serialized batch-one latency test.

Evidence

Verify the behavior illustrated in least_squares_line.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

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.

02 · Guided chapter

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.

Keep in view
  • regularization
  • log odds
  • Bayes rule
  • feature scaling
WORKED PATH

Follow the reasoning before touching the code.

  1. 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.

  2. 02

    Read the residuals

    Plot or summarize error versus prediction, time, and critical slices to find curvature, changing variance, and outliers.

  3. 03

    Package the full pipeline

    Persist feature order, imputation/scaling state, coefficients, output units, and a serialized batch-one latency test.

pythonleast_squares_line.py
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.

READ THE EXAMPLE

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.

Bring forward

Evaluation, Data & features

03 · Formal treatment

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.

Formal treatment
p(y=1∣x)=11+exp⁡(−x⊤β)p(y=1 \mid x) = \frac{1}{1 + \exp(-x^\top \beta)}

Logistic probability

Symbol, shape or unit contract
SymbolMeaning / shape / unit
xfeature 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.

  1. Write the named inputs: x, β, xᵀβ.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. 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)
04 · Deterministic lab

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.

Simplified simulation

Regularization boundary lab

Increase regularization and watch complexity trade against margin violations.

Primary3.43 weight norm
Secondary86.4%
DiagnosisBalanced

Assumption: Synthetic standardized two-feature classification problem.

Open nonvisual data table
ItemComputed stateInterpretation
x=-2logit -2.57negative
x=-1logit -1.29negative
x=0logit 0.00negative
x=1logit 1.29positive
x=2logit 2.57positive
05 · Production implications

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.

  1. 01

    Turn “Fit a transparent reference” into a written invariant and a failing test.

  2. 02

    Promote least_squares_line.py from illustration to a versioned implementation with representative fixtures.

  3. 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.

  4. 04

    Serve or materialize behind explicit 15 ms batch-one latency.

  5. 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.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01What is linear in logistic regression?
02Why scale features for kNN?
03Does an SVM margin score equal probability?
07 · Apply in production

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
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

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.