InterviewsVector
Arc 3
Build labIntermediate110 min estimateOriginal publication

Linear Models as Debugging Instruments

A linear baseline is not merely a weak competitor; it is an executable probe of whether the learning problem behaves as claimed.

Authorship
InterviewsVector
Published / updated
2026-08-20 / 2026-08-20
Review status
Artifact tests passing · primary sources recorded

Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.

The decision in one pass

Fit a regularized linear or logistic baseline before a complex model, but use it diagnostically: compare it with an intercept-only predictor on a causally valid split, inspect coefficients only in the declared feature units, measure train-to-evaluation change, and examine residual behavior on required slices. Near-perfect fit may reveal a target proxy; no improvement may reveal a broken target or missing signal; unstable coefficients may reveal collinearity or scale; and a small catastrophic slice must block the aggregate verdict. Bind the target, features, solver, tolerance, data, rows, thresholds, and evidence digest so the diagnosis is reproducible.

Why this matters

Complex models can hide basic problem-definition errors behind training machinery. A simple baseline makes direction, scale, residual pattern, and shortcut strength inspectable. It also establishes whether additional complexity earns measurable out-of-sample value. When the baseline behaves strangely, debugging data and measurement is usually cheaper and more informative than tuning a larger architecture.

You will be able to

  • Derive linear regression and logistic regression as transparent mappings from named features to a target or log-odds.
  • Use an intercept-only comparator, evaluation improvement, residuals, slices, and conditioning as complementary diagnostics.
  • Interpret coefficients only after accounting for feature units, transformations, regularization, and correlation.
  • Build a bounded content-addressed linear diagnostic with explicit solver and acceptance conventions.
  • Decide whether results establish a baseline, expose leakage, or require target and data investigation.

Your Vector Loop for this lab

  1. 01

    Model

    Name target units, feature units, allowable transformations, split identities, and the intercept-only comparator.

  2. 02

    Derive

    Derive linear predictions, residual loss, logistic log-odds, and regularization effects.

  3. 03

    Build

    Fit a bounded baseline and report evidence identity, coefficients, aggregate error, slice error, and conditioning.

  4. 04

    Stress

    Inject target proxies, redundant features, scale explosions, slice failures, provenance swaps, and row reuse.

  5. 05

    Operate

    Run the baseline on every data revision and require complex models to earn scoped incremental value.

  6. 06

    Defend

    Explain what each diagnostic implies, which claims remain unsupported, and the next cheapest test.

Model the baseline as a probe

A baseline should be easy to fit, reproduce, and falsify. Start with an intercept-only predictor that encodes no feature signal. Then add a small, named feature set under a fixed split and loss. The comparison asks whether the data contains stable additive signal. It does not decide that linearity is true, causal, fair, or sufficient for the product.

Observed resultPossible diagnosisNext test
near-perfect train and evaluation fittarget proxy, duplicate, or genuinely simple ruleremove suspect fields and replay lineage
train fit strong, evaluation weakoverfit, shift, identity leak, or scale instabilityinspect split and residuals by time/group
no gain over interceptweak features, noisy target, wrong horizon, or nonlinear signalaudit measurement before expanding model
one huge coefficientunit mismatch, rare indicator, correlation, or proxystandardize for diagnosis and perturb feature
small aggregate error, bad sliceheterogeneous relationship or thin evidencegate slice and collect targeted data

Derive the two baseline interfaces

ŷ = β₀ + xᵀβ

Linear regression predicts in target units. Holding other encoded features fixed, βⱼ changes the prediction by βⱼ target units per one unit of xⱼ; correlation and transformations limit any causal interpretation.

β̂ = arg min_β Σᵢ(yᵢ − β₀ − xᵢᵀβ)² + λ‖β‖₂²

Ridge regularization stabilizes some correlated or weakly determined directions by adding a versioned penalty. It changes the estimator, so λ belongs in the evidence contract.

log(p/(1−p)) = β₀ + xᵀβ

Logistic regression is linear in log-odds, not probability. Exponentiating βⱼ gives a conditional odds multiplier for a one-unit feature change under the model and encoding.

QuestionLinear regressionLogistic regression
outputunbounded target estimateprobability through a sigmoid
common fit objectivesquared residual losslog loss
transparent quantitytarget-unit coefficientlog-odds coefficient
common pathologyheteroscedastic or structured residualsseparation and poor calibration
baseline comparatortrain-target meantrain event prevalence

Run the cheapest discriminating tests first

  1. 01Confirm the interceptReproduce the train mean or prevalence and its evaluation loss. If this fails, the target, weights, metric, or split plumbing is already inconsistent.
  2. 02Fit one feature at a timeLook for implausibly strong proxies, reversed direction, unit mistakes, and features that work only in one time or source slice.
  3. 03Fit the named small setTrack rank, conditioning, coefficient changes, and evaluation improvement under an explicitly versioned solver and penalty.
  4. 04Inspect residual structureBucket residuals by prediction, time, target magnitude, entity group, and protected slices; random-looking aggregate residuals can hide a coherent subgroup failure.
  5. 05Challenge with a richer modelRequire incremental value on the same causally valid evidence, then diagnose where it improves rather than accepting a single aggregate delta.

Residuals are observations about where a mapping misses, not automatic proof of why. A curved residual pattern can suggest a missing transform; time drift can suggest process change; a few influential points can suggest data errors or a legitimate rare regime. Each pattern proposes a next experiment that keeps target and split definitions fixed.

Build a versioned linear diagnostic

The reference artifact implements a deliberately small standard-library regression path. Its frozen contract binds target identity and unit, named features, dataset and feature snapshots, split IDs, required evaluation slices, solver convention, singular-pivot tolerance, ridge penalty, workload limits, aggregate and slice acceptance limits, and owners. It rejects mutable or duck-typed evidence, duplicate identities, non-finite numbers, wrong shapes and provenance, singular systems, arithmetic overflow, thin slices, and unbounded workloads. The entire dataset—including rows—receives a content identity that the report preserves.

linear_model_diagnostic.py
1def format_example() -> str:
2 result = diagnose_linear_baseline(ILLUSTRATIVE_CONTRACT, ILLUSTRATIVE_DATASET)
3 coefficients = ",".join(f"{value:.3f}" for value in result.coefficients)
4 return "\n".join(
5 (
6 "example=illustrative_only",
7 f"contract_version={ILLUSTRATIVE_CONTRACT.contract_version}",
8 f"dataset={result.dataset_id}",
9 f"evidence_id={result.evidence_id}",
10 f"coefficients=intercept,{ILLUSTRATIVE_CONTRACT.feature_names[0]}:{coefficients}",
11 f"train_rmse={result.train_rmse:.3f}",
12 f"evaluation_rmse={result.evaluation_rmse:.3f}",
13 f"mean_baseline_rmse={result.mean_baseline_rmse:.3f}",
14 f"evaluation_improvement={result.evaluation_improvement:.3f}",
15 f"lowest_improvement_slice={result.lowest_improvement_slice_id}:{result.lowest_slice_improvement:.3f}",
16 f"highest_rmse_slice={result.highest_rmse_slice_id}:{result.highest_slice_rmse:.3f}",
17 f"decision={result.decision}",
18 )
19 )

Expected output

example=illustrative_only
contract_version=linear-diagnostic-v1
dataset=linear-baseline-run-0042
evidence_id=linear-diagnostic-evidence-v1@sha256:a88115a8fc3d8964e1994b25755cbba991de78ad0d6bfb6741eb9eeec44971fd
coefficients=intercept,queue-age-hours:1.000,2.000
train_rmse=0.000
evaluation_rmse=0.000
mean_baseline_rmse=6.083
evaluation_improvement=1.000
lowest_improvement_slice=established:1.000
highest_rmse_slice=new-account:0.000
decision=BASELINE_ESTABLISHED

Verify: Run python3 -m unittest discover courses/ai-engineering/reference-impl/linear_debugger.

Stress the baseline until the problem speaks

InjectionExpected evidenceLikely diagnosis
post-outcome featureimplausibly strong evaluation fittarget leakage
duplicate featuresingular or unstable coefficientscollinearity and ill-posed attribution
feature × 10⁹conditioning or solver sensitivityunit and scaling contract
target unit swaplarge residual and coefficient changesemantic mismatch
one failed required sliceslice gate returns investigateaggregate hides heterogeneity
same dataset name, changed rownew evidence digestdecision input changed
  1. 01Remove each suspicious featureA dramatic collapse after removing one identifier-like field is evidence to inspect lineage, not a reason to keep the shortcut.
  2. 02Shuffle the target inside the training boundaryPerformance should collapse toward the comparator. Persistent signal suggests leakage through preprocessing, duplicates, or evaluation logic.
  3. 03Perturb units and encodingConfirm predictions transform as expected and coefficient narratives do not survive a semantic unit change without revision.
  4. 04Replay later and unseen groupsCompare residual distribution and slice error without changing the fitted model; this separates fit from transfer evidence.
  5. 05Force arithmetic extremesReject NaN, infinity, booleans, overflow, and unsupported workload sizes instead of emitting plausible coefficients.

Operate the baseline as a permanent control

  • Re-run the intercept and linear baselines on every target, feature, split, and data-pipeline revision before training expensive candidates.
  • Store coefficients with units, encoding, centering, solver, penalty, split digest, and uncertainty; never publish a bare coefficient leaderboard.
  • Compare complex models with the baseline on identical content-addressed evidence and required slices, including latency and operating cost.
  • Monitor residual distribution, comparator improvement, slice gaps, conditioning, missingness, and feature range drift after launch.
  • Treat a sudden baseline improvement as a possible leakage alarm and a sudden collapse as a possible data or target incident.
DecisionEvidence requiredWhat it does not claim
baseline establishedscoped improvement plus slice and numeric gatescausality or production sufficiency
investigate data or targetfailed transfer, slice, or conditioning gatethat nonlinear models cannot help
advance complex candidateincremental valid-split valueautomatic launch authority
retain linear production modelutility, calibration, operations, and risk evidencesimplicity alone guarantees safety

Operate at three altitudes

Production lens

  • Bind target identity and unit, feature order and snapshot, data revision, split digest, solver, tolerance, penalty, and row evidence into every diagnostic.
  • Gate required-slice error and relative improvement in addition to aggregate improvement and train-to-evaluation change.
  • Reject singular, ill-conditioned, non-finite, mutable, identity-reused, or oversized evidence before presenting coefficients.
  • Keep a baseline dashboard beside complex-model metrics so shared data and target incidents remain visible.

Staff lens

  • Make a tested baseline and comparator mandatory for new learning systems, with explicit exceptions for tasks where the interface does not apply.
  • Standardize target units, feature naming, split identities, and evidence digests so diagnostics remain comparable across teams.
  • Reward evidence that disproves a modeling path early; baseline-driven cancellation can be a high-value engineering result.

Interview defense

A gradient-boosted model beats your linear baseline by eight points offline. What would you check before accepting the improvement?

I would first verify both models used the same causally valid, content-addressed rows and fitted preprocessing only on training. I would reproduce the intercept and linear results, inspect whether the baseline is suspiciously strong or weak, compare train and evaluation loss, condition and coefficient stability, and examine residuals and deltas by time, identity group, target range, and required slices. I would remove likely proxies, run a target shuffle, quantify uncertainty, and require the complex model's incremental utility and operational cost to hold on decision-independent evidence.

Expect the interviewer to press on

  • What can an extreme coefficient mean?
  • Why is logistic regression linear if its probability curve is not?
  • How would you use residuals to choose the next feature?
  • When should a slice block an aggregate improvement?

Misconceptions to remove

Linear models are useful only when they win production accuracy.

They also validate target plumbing, reveal shortcut signal, establish comparators, expose residual structure, and quantify the value of complexity.

The largest coefficient is the most important feature.

Coefficient magnitude depends on feature units, encoding, correlation, and regularization; predictive association is not causal importance.

A good aggregate residual score means the baseline is healthy everywhere.

Offsetting groups and uneven sample sizes can hide coherent failures. Required slices need their own support, comparator, and gate.

Check your model

1. Why compare linear regression with a train-mean predictor on evaluation data?

The train mean establishes the error available without feature signal. Improvement over it shows what the named linear features add under the same split.

2. What does a high condition proxy tell you in this diagnostic?

The normal-equation solve has weakly determined directions under the recorded convention. Coefficients may be unstable, prompting scale, redundancy, solver, or regularization investigation.

3. Why must target units be part of the evidence identity?

Changing hours to minutes changes targets, coefficients, errors, and thresholds while leaving row IDs intact. Without the unit, the diagnostic is semantically incomplete.

Prove the mechanism

Add a logistic diagnostic with a content-addressed prevalence comparator, bounded Newton updates, log-loss, calibration bins, separation detection, and slice gates. Reject per-call solver overrides that are absent from the contract.

Add a production constraint

Add influence diagnostics and a leave-one-group-out stability report, then identify whether a candidate gain survives removal of the most influential dependency group.

Artifact: Linear baseline diagnostic

courses/ai-engineering/reference-impl/linear_debugger/linear_model_diagnostic.py

Download reference implementation

Primary references and next links

References

  1. 1. Ridge Regression: Biased Estimation for Nonorthogonal Problems

    Hoerl and Kennard. Primary Technometrics paper introducing ridge estimation for correlated predictors.

  2. 2. Detection of Influential Observation in Linear Regression

    R. Dennis Cook. Primary paper developing influence diagnostics for linear regression.

  3. 3. Logistic Regression Diagnostics

    Daryl Pregibon. Primary Annals of Statistics paper developing diagnostic methods for logistic regression.

  4. 4. LinearRegression

    scikit-learn. Official documentation defining the ordinary least-squares objective and exposing rank and singular-value diagnostics.

Continue through the graph

Glossary: intercept · coefficient · ordinary least squares · ridge regression · log-odds · residual · conditioning · influence