Lawfare Group → Knowledge Institute → Lawfare Academy
← Regression and Business Forecasting
Unit 2
Least squares and residuals
Learning objectives
- Explain least squares and residuals in your own words.
- Apply the principle to the worked business case.
- Evaluate the answer and identify an assumption that could change it.
Least squares and residuals
Least squares chooses coefficients minimizing squared residuals. A residual is observed outcome minus fitted outcome. Residual plots reveal patterns that numerical fit summaries can hide; large errors may reflect data problems, unusual cases, or model limitations.
Worked example
Actual job time is seven hours and fitted time five hours. The residual is positive two hours.
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 least squares and residuals 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
Residual equals: 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.
Advanced investigation: Derive least squares, sampling uncertainty and a future observation
Let S(b0,b1)=Σ[yi−b0−b1xi]². At an interior minimum, setting the derivative with respect to b0 to zero gives Σei=0 and b0=ybar−b1xbar. Substituting that relation into the derivative with respect to b1 gives b1=Sxy/Sxx, provided Sxx>0. If all x values are identical, slope is not identified by these data. This is a geometric fitting result; it does not require normal errors to calculate the line.
Inference requires additional assumptions. In the classical fixed-design model, the conditional error mean is zero and errors are independent with common variance σ². Then Var(b1|X)=σ²/Sxx. Estimate σ² using s²=SSE/(n−2) when there are two fitted coefficients. The lost degrees of freedom reflect estimating the intercept and slope from the same observations. Normal conditional errors supply an exact Student-t reference for the usual small-sample intervals; asymptotic or robust approaches make different claims. Serial dependence, heteroskedasticity or selection can invalidate a naive standard error even when the fitted coefficients were computed correctly.
For an input x0, the fitted mean has estimated standard error s√[1/n+(x0−xbar)²/Sxx]. A new individual outcome adds its own unexplained variability, producing s√[1+1/n+(x0−xbar)²/Sxx] under the same independent-error model. The extra 1 distinguishes prediction of a future observation from estimation of an average. A narrower confidence interval for the mean cannot honestly be presented as a range for every new job.
Distance from the observed center increases both intervals through the leverage term. This mathematical widening does not account for every extrapolation risk: a structurally wrong linear relationship outside the observed range can fail more severely. Report the predictor support, sampling design and intended use. A precise coefficient is not permission to make a causal claim; the zero-conditional-error assumption must be defended in the context of how the predictor and outcome were generated.
Worked investigation
Use x=(1,2,3,4,5,6) and y=(2,4,3,4,7,7). The means are 3.5 and 4.5; Sxx=17.5 and Sxy=17.5, giving slope 1 and intercept 1. Predictions are 2,3,4,5,6,7, with residuals 0,1,−1,−1,1,0. SSE=4 and s²=4/4=1. At x0=3.5 the fitted mean is 4.5. Its standard error is √(1/6)=0.408248; a new observation has standard error √(1+1/6)=1.080123. Using the supplied two-sided 95% critical multiplier 2.776 for four degrees of freedom, margins are about 1.1333 and 2.9984. The multiplier is stipulated for this exercise, not estimated from six observations.
Independent transfer
Calculate the fitted mean and both standard errors at x0=7 using the same record. Explain which assumptions the larger prediction interval still does not test.
Transfer reasoning
The fitted mean is 8. The leverage term is (7−3.5)²/17.5=0.7. Mean standard error is √(1/6+0.7) = 0.930949; prediction standard error is √(1+1/6+0.7) = 1.366260. The intervals do not establish linearity beyond x=6, independence, constant variance or a causal interpretation.
Original Academy expansion: deriving and checking least squares
Least squares chooses coefficients to minimize the sum of squared residuals: SSE = sum of (yi - b0 - b1 xi) squared. Squaring prevents positive and negative errors from canceling and penalizes large misses more heavily. It is a choice of loss function, not a universal definition of a good decision. Absolute-error loss is less sensitive to large deviations. A business with asymmetric shortage costs may need asymmetric loss. Select the estimation and decision criteria with the intended use in mind.
For simple regression with an intercept and variation in X, define xbar and ybar as sample means. Let Sxx = sum of (xi - xbar) squared and Sxy = sum of (xi - xbar)(yi - ybar). The least-squares slope is b1 = Sxy/Sxx, and the intercept is b0 = ybar - b1 xbar. One way to understand these formulas is through the normal equations. Differentiating SSE with respect to b0 makes the residual sum zero. Differentiating with respect to b1 makes the sum of xi times its residual zero. Thus the fitted component and residual component are orthogonal in the sample. These algebraic properties do not prove causal validity or correct specification.
Worked investigation: fit a small dataset by hand
Consider four fictional jobs with X values 1, 2, 3, 4 and Y values 2, 4, 5, 7. The means are xbar = 2.5 and ybar = 4.5. The deviations in X are -1.5, -0.5, 0.5, 1.5; the deviations in Y are -2.5, -0.5, 0.5, 2.5. Their squared X deviations sum to 5. Their cross-products sum to 8. Therefore b1 = 8/5 = 1.6 and b0 = 4.5 - 1.6(2.5) = 0.5.
The fitted values are 2.1, 3.7, 5.3, 6.9. Residuals are -0.1, 0.3, -0.3, 0.1. They sum to zero, and their squared sum is 0.20. The total variation around ybar is SST = 6.25 + 0.25 + 0.25 + 6.25 = 13. R squared is 1 - SSE/SST = 1 - 0.2/13, approximately 0.9846. This is an in-sample description of explained variation for this fit, not a statement that future predictions will be 98.46% accurate.
Two coefficients were estimated, leaving n - 2 = 2 residual degrees of freedom. Under the usual correctly specified independent constant-variance model, estimate error variance by s squared = SSE/(n - 2) = 0.10 and error standard deviation by s = about 0.3162. The slope's standard error is s/sqrt(Sxx), about 0.1414. An approximate 95% interval using the t distribution with 2 degrees of freedom is 1.6 plus or minus 4.303(0.1414), or roughly 0.991 to 2.209. A visually close line can still leave appreciable parameter uncertainty in a tiny sample.
For X0 = 2.5, fitted Y is 4.5. The standard error for the estimated mean response is s sqrt(1/n + (X0 - xbar) squared/Sxx), approximately 0.1581. For a new individual outcome, include an additional 1 inside the square root: approximately 0.3536. The resulting t-based prediction interval is wider because it includes both estimation uncertainty and the individual outcome's unexplained variation. It still depends on the model assumptions and is not reliable merely because the arithmetic is correct.
A p-value for a zero-slope test assesses compatibility with a specific null model and its assumptions. It is not the probability the null is true, the probability an observed association is causal, or the economic importance of the effect. A large dataset can identify a very small association precisely. A small dataset can leave an important effect uncertain. Report estimated magnitude, units, uncertainty, and the decision context together.
Progressive practice
- Foundation: verify the four fitted values and calculate SSE without rounding the residuals first.
- Application: add 10 to every Y value. Determine the new intercept, slope, residuals, and R squared without repeating the entire calculation.
- Transfer: multiply Y by 100. Explain how the slope, intercept, residual standard deviation, and R squared change.
- Critique: the sample contains four jobs from one unusual day. Explain why a narrow formal interval would not repair unrepresentative sampling.
Worked reasoning for the practice
The squared residuals are 0.01, 0.09, 0.09, and 0.01, totaling 0.20. Adding 10 to all outcomes shifts the intercept from 0.5 to 10.5 while leaving slope, residuals, SSE, and R squared unchanged. Multiplying outcomes by 100 multiplies intercept, slope, and residual standard deviation by 100; both SSE and SST multiply by 10,000, so their ratio and R squared remain unchanged. A probability interval conditional on an assumed sampling process does not measure how different the target population is from the observed day. Expand the sampling frame and evaluate performance on representative later jobs.
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.
Complete current conceptual preparation
Least squares, uncertainty and a reproducible output table
Fit is an optimization result; inference is a model result
For observed pairs, minimize S(a,b)=sum((yi-a-bxi)^2). Differentiating in a gives sum(ei)=0 and a=ybar-b*xbar. Substituting into the slope equation gives b=Sxy/Sxx when Sxx>0. The second derivative in the centered slope is 2*Sxx>0, so this stationary point is the unique slope minimum. The fitted line passes through the two sample means. With an intercept, its residuals sum to zero and their inner product with x is zero. Those identities hold for this optimizer even when the conditional mean is wrong; they cannot certify that the population errors are independent or have zero conditional mean.
Use the existing Academy four-, five- and six-point records as separate investigations. For this studio use the four-branch record x=(1,2,3,4), y=(2,4,5,7). Sxx=5, Sxy=8, Syy=13, giving b=1.6, a=.5, predictions (2.1,3.7,5.3,6.9) and residuals (-.1,.3,-.3,.1). SSE=.2. The fitted centered component and residual component are orthogonal, so SST=SSR+SSE=12.8+.2=13. R-squared=12.8/13. An intercept is essential to this centered decomposition; do not apply the same interpretation to a forced-zero fit without checking its definition.
For classical conditional inference write Y=Xbeta+epsilon with E(epsilon|X)=0 and Var(epsilon|X)=sigma² I. Treat the predictor design as fixed or condition on it. These assumptions give E(bhat|X)=beta and Var(bhat|X)=sigma²(X'X)^-1 for a full-rank model. Normal errors supply exact finite-sample t and F distributions. Constant variance and independence alone do not establish an exact normal-reference test, and a coefficient computed by least squares needs no normal assumption merely to exist. Time dependence and clustered measurements demand an appropriate covariance structure. A robust covariance estimate can change standard errors without repairing a wrong mean or a causal identification problem.
Build the coefficient table instead of trusting labels
Here n=4 and p=2 estimated coefficients. The unbiased residual variance estimate under the model is s²=SSE/(n-p)=.1. Thus s=sqrt(.1), slope SE=s/sqrt(Sxx)=sqrt(.02)=.141421356 and intercept SE=s*sqrt(1/n+xbar²/Sxx)=sqrt(.15)=.387298335. The coefficient covariance is -xbar*s²/Sxx=-.05. Its sign reflects the way estimated intercept and slope compensate around the observed center. At x=0 the intercept extrapolates beyond the observed range; its mathematical SE does not make that point operationally plausible.
Testing beta 1=0 gives t=1.6/sqrt(.02)=11.313708499 with df=2. For a two-sided 95% interval use the supplied t critical value 4.302652730. The slope margin is approximately .6084870, giving approximately [.991513,2.208487]. With one added slope, the regression ANOVA F is (SSR/1)/(SSE/2)=128=t². State the assumptions and degrees of freedom with the statistic. A very high R-squared in four synthetic observations says little about transportability; a significance result is not permission to spend money.
For a coefficient hypothesis beta 1=c, replace the numerator with b-c. If c=1.5, t=.1/sqrt(.02)=.707106781. The data's apparent rejection of zero does not imply precision sufficient to distinguish 1.6 from 1.5. A practical threshold and a statistical null are different questions. Construct the relevant contrast before reading a p-value column.
Predictions and intervals answer different questions
At x 0=2.5, yhat=4.5 and h 0=1/n+(x 0-xbar)^2/Sxx=.25. The estimated fitted-mean variance is s²h 0=.025 and new-individual prediction variance is s²(1+h 0)=.125. Under the same exact classical model, multiply their square roots by 4.302652730 to obtain margins approximately .68031 and 1.52122. The second is wider because a new individual's unexplained error remains even if coefficients are accurately estimated. An average of m independent new comparable observations instead adds s²/m, not s², to coefficient uncertainty. Dependence among those observations changes that term.
At x 0=5, h 0=.25+2.5²/5=1.5 and fitted outcome=8.5. Mean variance=.15 and individual variance=.25. This larger geometric uncertainty still omits the risk that the relationship changes beyond x=4. Never interpret the expanded interval as an automatic extrapolation safeguard. These intervals are pointwise; selecting many targets or a favorable target after looking at results changes simultaneous coverage and selection claims.
Optional Excel reproduction, with complete manual alternative
Enter x in A 2:A 5 and y in B 2:B 5. Preserve the unrounded original cells. In an empty region, use =LINEST(B 2:B 5,A 2:A 5,TRUE,TRUE). A supported dynamic-array Excel version spills a five-row, two-column result for one predictor. Older versions may require selecting the output block and entering an array formula. The first row is slope/intercept; row two their standard errors; row three R-squared/residual standard error; row four F/residual df; row five regression and residual sums of squares. Confirm labels against the manual values above rather than assuming row order is arbitrary. Do not let the spill overwrite the dataset.
For an independent worksheet check, calculate =AVERAGE(A 2:A 5), centered products, =SLOPE(B 2:B 5,A 2:A 5), =INTERCEPT(B 2:B 5,A 2:A 5), fitted values and residuals. Sum squared residuals, divide by COUNT(A 2:A 5)-2 and square-root. Use =T.INV.2 T(0.05,2) for the supplied two-sided critical value if that function is available. =CORREL(A 2:A 5,B 2:B 5)^2 should agree with this intercept-model R-squared. Preserve paired rows when sorting or filtering; deleting one missing cell without removing its paired row changes the observation definition. Menus, localization and decimal separators vary. These are optional procedures; all required learning and hand calculations are on site, and execution in a particular Excel installation is not claimed.
Optional practice
Guided model: a variance denominator changes
Dividing SSE=.2 by four gives .05, half the conventional residual estimate .1, because it ignores the two fitted coefficients. The resulting slope SE would be .1 instead of sqrt(.02). Changed fact: there are six independent observations and still two fitted coefficients, with SSE=.2. Then df=4 and s²=.05 is the correct model-based estimate. The denominator depends on the actual design and estimated parameter count, not on a rule that every sum must be divided by the number of rows.
Independent model: a future average
At x 0=2.5, an average of 100 independent new comparable outcomes has estimated prediction variance .025+.1/100=.026, SE=sqrt(.026). The fitted mean alone has variance .025. Changed fact: the 100 outcomes share a common shock. Their average's new-outcome variance need not be .001; include covariance terms or state that this reduction is unsupported. Increasing row count does not remove a common component.
Transfer model: a smaller p-value is an incomplete decision
The zero-slope t is 11.3137, but the slope-versus-1.5 t is .7071. A manager requiring an incremental effect clearly above 1.5 cannot use rejection of zero to assert the stronger threshold. Moreover these are observational records. Changed fact: a later randomized design justifies a causal contrast at the relevant scale. Recalculate its effect, uncertainty and actual costs using that design; do not transfer this tiny fixture's coefficients into the new study.
Unit rubric: 20 points
Award four points each for correct normal equations/fit, coefficient table and df, matched hypothesis and assumptions, mean/individual/average prediction distinction, and reproducible paired-data workflow with changed facts. Complete model: report (.5,1.6), SSE=.2, df 2, s²=.1, slope SE=sqrt(.02), intercept SE=sqrt(.15), t 0=11.3137 and t 1.5=.7071. At the center use variances .025 and .125; name pointwise, model and support limits. The optional worksheet is a reproducibility aid, not independent human review or a claim of device execution.
Optional source summary: NIST linear least squares was read for the distinction between linearity in parameters, estimation and extrapolation limitations. The branch data, calculations, workflow and practice here are original Academy teaching.
Optional software provenance: Microsoft LINEST documents the returned coefficient/statistics layout. It was consulted for this optional reproduction procedure; the manual derivation and numerical teaching are complete on site.
Developed study chapters
Original explanation, worked analysis and progressive optional practice.
Apply the idea
Actual job time is seven hours and fitted time five hours. The residual is positive two hours.
Residual equals: Explain your reasoning, then identify one changed fact that could alter the conclusion.
Advanced worked record — a separate fictional scenario: Use x=(1,2,3,4,5,6) and y=(2,4,3,4,7,7). The means are 3.5 and 4.5; Sxx=17.5 and Sxy=17.5, giving slope 1 and intercept 1. Predictions are 2,3,4,5,6,7, with residuals 0,1,−1,−1,1,0. SSE=4 and s²=4/4=1. At x0=3.5 the fitted mean is 4.5. Its standard error is √(1/6)=0.408248; a new observation has standard error √(1+1/6)=1.080123. Using the supplied two-sided 95% critical multiplier 2.776 for four degrees of freedom, margins are about 1.1333 and 2.9984. The multiplier is stipulated for this exercise, not estimated from six observations.
Independent transfer: Calculate the fitted mean and both standard errors at x0=7 using the same record. Explain which assumptions the larger prediction interval still does not test.
Expanded transfer investigation: At the same predictor value, why is a classical interval for one new response wider than an interval for the mean response?
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
2 hours. Observed minus fitted is 7-5=2. 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.
Advanced transfer reasoning: The fitted mean is 8. The leverage term is (7−3.5)²/17.5=0.7. Mean standard error is √(1/6+0.7) = 0.930949; prediction standard error is √(1+1/6+0.7) = 1.366260. The intervals do not establish linearity beyond x=6, independence, constant variance or a causal interpretation.
Expanded transfer reasoning: The prediction variance includes an additional error-variance term under the stated model.
Progressive practice reasoning: The squared residuals are 0.01, 0.09, 0.09, and 0.01, totaling 0.20. Adding 10 to all outcomes shifts the intercept from 0.5 to 10.5 while leaving slope, residuals, SSE, and R squared unchanged. Multiplying outcomes by 100 multiplies intercept, slope, and residual standard deviation by 100; both SSE and SST multiply by 10,000, so their ratio and R squared remain unchanged. A probability interval conditional on an assumed sampling process does not measure how different the target population is from the observed day. Expand the sampling frame and evaluate performance on representative later jobs.
Check understanding
For X=[1,2,3,4] and Y=[2,4,5,7], Sxx=5 and Sxy=8. What is the fitted slope?
- 0.625
Feedback
Incorrect. This reverses numerator and denominator.
- 8
Feedback
Incorrect. Divide the cross-product sum by the predictor squared-deviation sum.
- 1.6
Feedback
Correct. The simple-regression slope is Sxy/Sxx=8/5.
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.