Lawfare Group → Knowledge Institute → Lawfare Academy
← Regression and Business Forecasting
Unit 5
Diagnostics and validation
Learning objectives
- Explain diagnostics and validation in your own words.
- Apply the principle to the worked business case.
- Evaluate the answer and identify an assumption that could change it.
Diagnostics and validation
Check residual structure, influential observations, collinearity, and whether predictions extrapolate beyond the data. Evaluate performance on observations not used to fit the model. High in-sample R-squared can coexist with poor prediction.
Worked example
A model memorizes past jobs but performs poorly on later jobs.
Current on-site learning
Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.
Work through the reasoning
Define the population, sampling or assignment process, variables, estimator, and intended inference. For this unit, connect the explanation of diagnostics and validation to the worked example before answering the practice question.
Check the limits
Check dependence, selection, uncertainty, and whether the evidence supports description, prediction, or causation. If the source model and the practical example use different assumptions, state the difference rather than applying the formula or rule mechanically.
Apply it independently
What is the strongest warning sign? Write an answer before opening the model response. Show the calculation or explain the causal or logical steps. Change one material assumption and say whether your conclusion changes. This practice is optional; you can read every part of the course without submitting work.
Original Academy expansion: diagnostics and honest validation
Model diagnostics investigate whether the fitted representation is adequate for its intended use. Begin with residual plots against fitted values, individual predictors, and observation order. A curve in residuals suggests the mean function misses systematic structure. A funnel suggests changing residual variability. Runs of positive or negative residuals in time order suggest dependence or a shifting mean. A plot is evidence to interpret, not an automatic instruction to delete observations until the picture looks tidy.
Different assumptions support different claims. The zero-conditional-mean condition is central to interpreting coefficients as the proposed conditional relationship. Constant variance and independence support familiar standard-error formulas. Normal error assumptions support exact small-sample t inference in the classical model; least-squares coefficients can be calculated without normally distributed outcomes. Robust standard errors can address certain variance misspecifications asymptotically, but they do not fix an omitted causal factor, an incorrect mean function, or a sample with no support for the desired comparison.
Leverage describes how unusual an observation's predictor combination is relative to the design. A large residual describes an unusual outcome conditional on the fitted model. Influence combines position and mismatch: an observation may substantially move the fitted coefficients when included. An unusual X value with a small residual can still deserve attention because future conclusions may depend heavily on it. Investigate data entry, real process differences, and sensitivity. Preserve a documented reason for exclusion. A genuine difficult job is not an error merely because it damages the model's appearance.
Worked investigation: performance changes outside training
Suppose two models predict a later four-job holdout set whose actual hours are 4, 6, 8, 10. Model A predicts 5, 5, 9, 9. Errors, defined as actual minus prediction, are -1, 1, -1, 1. Its mean absolute error is 1 and root mean squared error is 1. Model B predicts 4, 6, 8, 14. Its absolute errors are 0, 0, 0, 4, giving the same mean absolute error of 1 but root mean squared error of 2. The metric choice changes how severely one large miss is penalized.
If a costly staffing shortage occurs when actual hours exceed forecast, the signs also matter. Model B's one large error is an overprediction. Model A underpredicts two jobs. Equal MAE does not mean equal business value. Evaluate a predeclared decision loss alongside statistical errors. For an asymmetric absolute loss with underprediction cost Cu and overprediction cost Co, the optimal target quantile under the relevant conditional distribution is Cu/(Cu + Co). If Cu = 3 and Co = 1, the target is the 0.75 quantile, not necessarily the mean. This statement assumes the simple linear-per-unit loss structure; fixed penalties or capacity constraints require a different optimization.
Separate model building, model selection, and final evaluation. A training set estimates coefficients; a validation process compares candidate specifications and tuning choices; an untouched test set estimates performance after those choices. Repeatedly checking the test set and revising the model makes it part of training in a broader sense. Cross-validation can use scarce observations more efficiently, but its splits must respect groups and time. Rows from the same customer can leak customer-specific information across random splits. Future records must not help train a model evaluated as though it existed earlier.
Preprocessing is part of fitting. Estimate imputation values, scaling constants, category encodings, and feature selection using training data within each split. Applying a transformation learned from the entire dataset before splitting can disclose evaluation information. A high R squared on training observations may reflect flexibility rather than generalization. Compare against a simple baseline and inspect errors across important subgroups, job sizes, and periods. An average error can hide a consistent failure on the jobs where the tool is most needed.
Progressive practice
- Foundation: independently compute MAE and RMSE for both holdout models.
- Application: give a concrete reason a customer-level split could be more demanding than a row-level split.
- Transfer: an analyst replaces missing values using the overall mean before cross-validation. Repair the procedure.
- Critique: explain what heteroskedasticity-robust standard errors can and cannot accomplish when a key severity measure is omitted.
Worked reasoning for the practice
Model A has squared-error total 4, divided by four and square-rooted to 1. Model B has squared-error total 16, producing RMSE 2. Both have absolute-error total 4. A row split may allow the model to learn a repeat customer's distinctive practices before predicting another job for that customer; a customer split tests transfer to unseen customers. Fit the missing-value replacement on each training fold and apply that fitted replacement to its validation fold. Robust standard errors can adjust certain uncertainty calculations under appropriate conditions. They do not remove omitted-variable bias or create the missing severity information.
Reading alignment for this expansion
The earlier introductory links remain background reading. Use the complete current on-site studios; publisher links are optional provenance. The original Academy worked records above are not quotations from those sources.
Extended text lesson
Continue with Validate the rule using only information available at the forecast origin for the full worked case, source readings and optional progressive practice.
Complete current conceptual preparation
Diagnostics, validation and a defensible model-selection pipeline
Diagnose distinct failures rather than deleting difficult rows
A residual-versus-fitted curve challenges the conditional mean. A funnel challenges constant residual variance. Residual runs in observation order challenge independence or a stable mean. A quantile plot investigates the distribution relevant to small-sample inference and tails; normally distributed outcomes are not a general requirement of least-squares fitting. Inspect the collection process, units and time boundary before choosing a mathematical remedy. A transformed mean, a variance model, group-cluster covariance and a new data collection answer different problems. Heteroskedasticity-robust errors cannot correct an omitted cause or a predictor unavailable at deployment.
For full-rank X, H=X(X'X)^-1 X' maps outcomes to fitted values. Diagonal h_i measures leverage, lies between 0 and 1 and sums to p. Residual variance under a classical common-variance model is sigma²(1-h_i). An internally standardized residual is e_i/[s*sqrt(1-h_i)]. This is a diagnostic, not a universal normal tail test: s was estimated using the same outcomes and model selection changes the reference. External studentization refits the error scale leaving the observation out. Leverage is a design property; changing an outcome leaves h unchanged.
Cook's distance can be computed as D_i=[e_i²/(p*s²)]*[h_i/(1-h_i)²], when the stated fit and nonzero residual scale exist. It measures the combined coefficient/prediction movement in a defined geometry after deletion. A rule such as 4/n can prompt examination but is not an evidence-based automatic deletion policy for every design. Preserve the all-record fit, the sensitivity result, provenance findings and the selection rule. If rank disappears after deleting a sole category observation, a standard deleted-fit calculation may be undefined; that itself exposes weak design support.
Worked diagnostic: a small ordinary residual hides sensitivity
The preserved five-record application has x=(1,2,3,4,20), y=(2,4,6,8,0), slope-.24, intercept 5.44, SSE 25.6 and p 2. Its fifth residual is-.64 and h 5=.984. The residual variance estimate is 25.6/3=8.533333333. Its standardized residual is-.64/sqrt((25.6/3)*.016)=-sqrt(3), approximately-1.73205. That is not an innocuous observation simply because an ordinary residual threshold is small.
The deleted residual is e 5/(1-h 5)=-40; refitting the first four gives y=2 x and a prediction 40 atx 20. Cook's distance is[.4096/(2*(25.6/3))]*[.984/.016²]=92.25. This large sensitivity does not prove which observation is invalid. The four-record sensitivity fit extrapolates fromx 1 through 4 tox 20, and its zero residual scale cannot support an ordinary noisy-process confidence claim. Changing onlyy 5 to 40 keeps leverage.984 while every point lies on y=2 x; residual influence vanishes for that exact fixture. Preserve this distinction between geometric potential and actual outcome disagreement.
Investigate whether 0 was a valid processing time, a canceled job or a failed-timer sentinel. If an original log proves the timer failed, document recoding and missingness rather than erasing the original. If the measurement is valid, revisit the intended process model and collect reliable large-batch observations. A desired positive slope cannot be the exclusion rule. A robust fit or ridge changes an optimization objective; it does not adjudicate provenance or turn a coefficient into a causal effect.
Explain variance and dependence remedies at their actual scope
Weighted least squares minimizes sum(w_i*e_i²). If Var(e_i|X)=sigma²/w_i and the mean is correctly specified, this can reflect known relative precision. Multiplying all weights by a common constant leaves coefficients unchanged. Estimated weights add estimation choices and must be learned within training. A row weighted 10 times as heavily has ten times its residual-squared contribution; it is not necessarily ten independent observations. Survey inclusion weights target representation and inverse-variance weights target precision; do not swap them because both are called weights.
With covariance Omega, the least-squares coefficient covariance is (X'X)^-1 X'Omega X(X'X)^-1. The familiar sigma²(X'X)^-1 is a special case. A heteroskedasticity-consistent sandwich replaces Omega using residual-based terms with finite-sample variants; clustered and time-dependent estimators need group or lag structures. Their asymptotic approximations can be unreliable with few independent groups. The point estimator, error covariance, design and causal target should all be named. Full numerical implementation of every robust estimator is outside this introductory/intermediate course's accepted scope; understanding why a naive standard error fails is required here.
A pipeline is more than the final regression equation
Freeze an observation eligibility rule and an issue-time information ledger. Reserve a final chronological block appropriate to the operational horizon. Inside earlier history, choose expanding or sliding origins. At each origin fit imputation, scaling, feature construction and penalty selection using only the permitted training history. Compute candidates on common future targets with a common loss. A scaler fitted on the whole dataset leaks distributional information even without reading future labels. A physical conversion fixed by definition does not have that learned-data defect.
For an explicit comparison use the preserved holdout actuals(4,6,8,10). A predicts(5,5,9,9), B predicts(4,6,8,14). Both MAE 1; RMSE is 1 forAand 2 forB. Let underforecasting cost 3 perunit and overforecasting cost 1. A errors(-1,1,-1,1) give losses(1,3,1,3), total 8. B errors(0,0,0,-4) give total 4. Thus squared-error preferenceA and declared asymmetric-cost preferenceB can differ. Do not choose the cost after seeing which candidate wins. If a hard capacity or service constraint is the actual decision, evaluate that constraint explicitly rather than assuming a linear error cost.
Compare final-test and subsequent production errors with the frozen method version, not a hindsight refit. A sample RMSE is not the uncertainty of the estimated RMSE, and overlapping multi-step errors are dependent. Report the number of origins, horizon, subgroup support and the range of conditions. Monitor bias, calibration and data changes. If a threshold triggers retraining, preserve the trigger, old forecasts and new method version. The new model needs its own future evaluation; overwriting old forecasts hides the very evidence needed to judge improvement.
Optional practice
Guided model: diagnose, do not discard
For the fifth preserved record, residual-.64,leverage.984,deleted residual-40 andCookD 92.25 quantify different aspects of sensitivity. Changed fact: source logs prove a wrong unit conversion. Correct with a documented mapping, preserve the raw record and rerun all affected fits and evaluations. Do not retain only the favorable model while hiding the verified correction.
Independent model: tuning uses the test twice
Choosing a ridge penalty by the final four outcomes makes those outcomes part of development. Refit preprocessing and tuning within earlier folds, lock the procedure and seek a new untouched evaluation. Changed fact: a calculation typo in reporting is fixed without changing frozen predictions or selection. Document it; a clerical correction need not be model tuning. Reconstruct the actual action rather than applying a label automatically.
Transfer model: a loss reversal
A beatsBunderRMSE 1 versus 2, but BbeatsAunder declared shortage 3/surplus 1 loss 4 versus 8. Changed fact: shortage and surplus both cost 1. Both total absolute loss 4; this record no longer identifies a winner under that loss. Prefer a justified simpler process or collect more evidence rather than claiming superiority from a tied metric.
Unit rubric: 20 points
Four points each for distinct diagnostic meanings and provenance; correct influence arithmetic; variance/dependence remedy boundaries; complete training-only selection with frozen final evaluation; and declared decision-loss/monitoring response. Complete model retains the original difficult record, exposes its 92.25 CookD, gives both holdout metric and loss comparisons and proposes relevant future collection. It claims neither independent human review nor future performance from fitting identities.
Developed study chapters
Original explanation, worked analysis and progressive optional practice.
Apply the idea
A model memorizes past jobs but performs poorly on later jobs.
What is the strongest warning sign? Explain your reasoning, then identify one changed fact that could alter the conclusion.
Expanded transfer investigation: An analyst estimates imputation values using the whole dataset before cross-validation. What is the repair?
Show the calculation or argument, identify the information available at the decision time, and state which assumption supports your conclusion. The four progressive tasks in the Learn stage provide additional practice.
Read the worked reasoning
Poor out-of-sample performance. Generalization requires evidence beyond the fitting data. In an independent response, state the given facts, identify the governing relationship, work through the calculation or comparison, and distinguish the conclusion from assumptions that still need evidence.
Expanded transfer reasoning: Preprocessing is part of model fitting and must respect the evaluation boundary.
Progressive practice reasoning: Model A has squared-error total 4, divided by four and square-rooted to 1. Model B has squared-error total 16, producing RMSE 2. Both have absolute-error total 4. A row split may allow the model to learn a repeat customer's distinctive practices before predicting another job for that customer; a customer split tests transfer to unseen customers. Fit the missing-value replacement on each training fold and apply that fitted replacement to its validation fold. Robust standard errors can adjust certain uncertainty calculations under appropriate conditions. They do not remove omitted-variable bias or create the missing severity information.
Check understanding
On actual values [4,6,8,10], predictions [4,6,8,14] have MAE 1. What is RMSE?
- 1
Feedback
Incorrect. Equal MAE does not imply equal RMSE.
- 4
Feedback
Incorrect. Four is the largest absolute error, not root mean squared error.
- 2
Feedback
Correct. Squared errors total 16; divide by four and take the square root.
Further reading
Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.
- Complete on-site teaching — Diagnostics, validation and a defensible model-selection pipeline
- NIST — Regression Diagnostics
- Penn State — STAT 501 Regression Methods
- Academy — Runnable business data investigations
- Introductory Business Statistics 2e — 13.5 Interpretation of Regression Coefficients: Elasticity and Logarithmic Transformation
- Validate the rule using only information available at the forecast origin