Learn OLS regression with 14 solved exercises, clear formulas, charts, confidence intervals, and checks beyond the textbook answers.

OLS Regression: 14 Solved Exercises and Formulas

OLS Regression: 14 Solved Exercises and Formulas

ECONOMETRICS · WORKED STUDY GUIDE

OLS regression turns a scatter of observations into an equation you can interpret, test, and use for prediction. However, a convincing analysis needs more than a fitted line: it also needs transparent calculations, defensible assumptions, and an honest account of uncertainty.

This guide solves exercises 6.31 through 6.44 from the supplied pages using two small datasets. Along the way, you will calculate coefficients, standard errors, hypothesis tests, confidence intervals, correlation, and elasticity. Moreover, you will see where rounded textbook answers differ from calculations that retain full precision.

The main result: For the ten-observation dataset, Ŷ = 14.2778 + 5.9444X and R² = 0.7719. The slope has a two-sided p-value of 0.000819 under the classical normal-error model. Nevertheless, neither result establishes causation.

Data provenance: the numerical observations come from Tables 6.12 and 6.13 in the three reader-supplied photographs. All tables of results and graphs below use independent calculations from those observations. The pages do not provide enough bibliographic information to verify the book’s author, title, or edition.

Start with the data and a consistent notation

Simple linear regression uses one predictor, X, and one response, Y. In econometrics, the phrase “two-variable model” usually refers to these two variables, rather than two predictors. Therefore, the model still estimates just one slope and one intercept.

Yi = β0 + β1Xi + ui    →    Ŷi = b0 + b1Xi

Here, β denotes an unknown population parameter, while b denotes its sample estimate. Also, u is the unobserved population disturbance, whereas e = Y − Ŷ is a computed residual. Keeping these symbols separate prevents a common mistake: treating a fitted residual as if it were the true error.

Table 1. Working data from the supplied Table 6.12
ObservationXYX²XY
1220440
2328984
354025200
444516180
53379111
655225260
775449378
864336258
976549455
1085664448
Total504402862414

The first dataset does not identify measurement units or a real-world population. Consequently, all interpretations below refer to generic X units and Y units. Attaching income, prices, or spending labels would invent information that the source does not supply.

Build the three centered sums

First, calculate the means: X̄ = 50/10 = 5 and Ȳ = 440/10 = 44. Next, remove the contribution of those means from the raw sums. This gives the quantities that drive nearly every result in the guide.

Sxx = ΣXi² − (ΣXi)²/n = 286 − 50²/10 = 36
Sxy = ΣXiYi − (ΣXi)(ΣYi)/n = 2414 − 2200 = 214
Syy = ΣYi² − (ΣYi)²/n = 21008 − 19360 = 1648

Throughout the article, SSE means the residual sum of squares, SSR means the explained regression sum of squares, and SST means the total centered sum of squares. However, some books use SSR to mean “sum of squared residuals.” Always read the definition before copying a formula.

Exercise 6.31: inspect the scatterplot

Plot X horizontally and Y vertically. The points show an upward association: observations with larger X generally have larger Y. For example, the observation at X = 2 has Y = 20, while the two observations at X = 7 have Y values of 54 and 65.

A straight line offers a reasonable first summary. Nevertheless, the scatterplot alone cannot prove linearity, constant variance, independent errors, or a causal mechanism. With only ten observations, subtle departures may remain difficult to detect.

2026-10-22T21:23:43.439131 image/svg+xml Matplotlib v3.10.8, https://matplotlib.org/ 2 3 4 5 6 7 8 X 20 30 40 50 60 70 Y A positive relationship, with visible uncertainty 95% confidence band for the mean OLS fitted line Observed values Sample means (5, 44)
Figure 1. The original observations, the fitted line, and a pointwise 95% confidence band under the classical normal-error assumptions. All visual elements come from the supplied data.

Answer: The relationship looks approximately linear and positive. Moreover, repeated X values reveal meaningful vertical dispersion, so a perfect fit would misrepresent the data.

Exercise 6.32: state the classical regression assumptions

The classical framework makes assumptions about the population process, not merely the line drawn through the sample. In particular, a useful formulation conditions on the observed predictor values. This separates the assumptions needed for unbiasedness from those needed for efficient estimation and exact inference.

ConditionMathematical statementWhy it matters
Linear conditional meanYᵢ = β₀ + β₁Xᵢ + uᵢThe parameters enter linearly.
Predictor variationSxx > 0The data must contain more than one X value.
Conditional mean zeroE(uᵢ | X₁,…,Xₙ) = 0The regressors do not systematically predict the omitted disturbance.
Constant conditional varianceVar(uᵢ | X) = σ²The usual homoskedastic standard-error formula applies.
No conditional error correlationCov(uᵢ,uⱼ | X) = 0 for i ≠ jDifferent observations do not share correlated disturbances.
Joint normal errors for exact small-sample inferenceu | X ~ N(0, σ²I)The usual finite-sample t and F reference distributions hold.

Normality is not necessary for the Gauss–Markov efficiency result. Instead, it supplies the familiar exact small-sample inference when combined with the other conditions. Likewise, zero correlation between X and u alone does not generally guarantee the conditional mean-zero assumption.

The supplied page writes a compact set of moment and normality conditions. For practical use, the conditional formulation above makes the statistical claims more explicit. Also, no scatterplot can verify exogeneity: that judgment requires information about sampling, measurement, and the mechanism that generated the data.

Method reference: Penn State, SLR Model Assumptions.

Exercise 6.33: derive the OLS regression formulas

Ordinary least squares chooses the line that minimizes the sum of squared vertical residuals. Squaring prevents positive and negative discrepancies from canceling. In addition, the squared loss gives larger discrepancies more influence on the objective.

Q(b0, b1) = Σ(Yi − b0 − b1Xi)² = Σei²

Set the two derivatives equal to zero

Differentiating Q with respect to the intercept and the slope produces two normal equations. Therefore, the fitted residuals sum to zero and have zero sample inner product with X when the model includes an intercept.

∂Q/∂b0 = −2Σ(Yi − b0 − b1Xi) = 0
∂Q/∂b1 = −2ΣXi(Yi − b0 − b1Xi) = 0
ΣYi = nb0 + b1ΣXi
ΣXiYi = b0ΣXi + b1ΣXi²

Solving this pair gives the familiar slope and intercept formulas. Because Sxx is positive here, the squared-error objective has a unique minimum. Thus, the normal equations identify the unique OLS line for these observations.

b1 = Sxy/Sxx = [nΣXY − (ΣX)(ΣY)] / [nΣX² − (ΣX)²]
b0 = Ȳ − b1X̄

Method reference: NIST/SEMATECH, Least Squares.

Exercise 6.34: calculate the fitted equation

Insert the centered sums into the slope formula. Next, use the sample means to recover the intercept. Retaining full precision until the final presentation keeps later residuals, tests, and intervals consistent.

b1 = 214/36 = 107/18 = 5.944444…
b0 = 44 − (107/18) × 5 = 257/18 = 14.277777…
Ŷ = 14.2778 + 5.9444X

For example, setting X = 6 gives Ŷ = 49.9444. The observed value at that X is 43, so the model overpredicts that observation by 6.9444 units. Conversely, at observation 6, X = 5 and Y = 52, which places the observation eight units above the fitted line.

The short display Ŷ = 14.28 + 5.94X is convenient for reading. However, it should not replace the unrounded coefficients inside a calculation script. Rounding each intermediate result can produce a chain of small discrepancies.

Exercise 6.35: verify the mean point and calculate residuals

An OLS line with an intercept passes through the pair of sample means. Substituting X̄ into the fitted equation demonstrates why. In this example, the exact line passes through (5, 44).

Ŷ(X̄) = b0 + b1X̄ = (Ȳ − b1X̄) + b1X̄ = Ȳ = 44

The rounded display equation gives 14.28 + 5.94 × 5 = 43.98. Therefore, the difference of 0.02 reflects rounding, rather than a failure of OLS. This simple identity provides a useful audit check whenever coefficients come from different sources.

Table 2. Fitted values and residuals using unrounded coefficients
ObservationXYFitted YResidual ee²
122026.1667-6.166738.0278
232832.1111-4.111116.9012
354044.0000-4.000016.0000
444538.05566.944448.2253
533732.11114.888923.9012
655244.00008.000064.0000
775455.8889-1.88893.5679
864349.9444-6.944448.2253
976555.88899.111183.0123
1085661.8333-5.833334.0278
2026-10-22T21:23:43.659681 image/svg+xml Matplotlib v3.10.8, https://matplotlib.org/ 2 3 4 5 6 7 8 X −6 −4 −2 0 2 4 6 8 Residual: observed minus fitted Y Residuals from the fitted line
Figure 2. Positive residuals identify observations above the line; negative residuals identify observations below it.
Σei = 0    and    ΣXiei = 0    apart from floating-point roundoff

These sample identities follow from minimization. However, they do not prove that the population disturbance has mean zero conditional on X. In particular, a badly specified regression can satisfy both identities perfectly.

Exercise 6.36: interpret the coefficients and elasticity

What the intercept means

The intercept predicts Y = 14.2778 when X = 0. However, the observed X range runs from 2 to 8. Consequently, the intercept describes an extrapolation beyond the sample rather than an observed baseline.

What the slope means

A one-unit increase in X corresponds to a 5.9444-unit increase in fitted Y. This is a change in units, not a percentage change. Moreover, an observational association does not tell us what would happen if an intervention forced X to change.

Elasticity at the means

For a linear fitted relationship, point elasticity equals the slope multiplied by X/Ŷ. At the sample means, the fitted response equals Ȳ, which simplifies the calculation. Thus, the elasticity at (5, 44) is approximately 0.676.

η(X) = (dŶ/dX)(X/Ŷ) = b1X/(b0 + b1X)
η(X̄) = 5.944444 × 5/44 = 0.675505

Near the means, a 1% increase in X corresponds to about a 0.676% increase in fitted Y. By contrast, the slope remains 5.9444 at every X value. Elasticity varies along this straight line because the ratio X/Ŷ changes.

Exercise 6.37: estimate error variance and standard errors

The residual sum of squares measures the total unexplained squared deviation. Since the model estimates two coefficients, the residual degrees of freedom equal 10 − 2 = 8. Therefore, the usual unbiased estimator of the common error variance divides SSE by eight.

SSE = Syy − Sxy²/Sxx = 1648 − 214²/36 = 375.888889
s² = SSE/(n − 2) = 375.888889/8 = 46.986111
s = √s² = 6.854642

Notice the units: s² uses squared Y units, while s returns to the original Y scale. In addition, the coefficient standard errors measure uncertainty about the estimated parameters, not the spread of individual responses.

SE(b1) = √(s²/Sxx) = 1.142440
SE(b0) = √[s²(1/n + X̄²/Sxx)] = 6.109653
QuantityUnrounded-calculation resultInterpretation
s²46.986111Estimated common disturbance variance
s6.854642Residual standard deviation
Estimated Var(b₀)37.327855Squared standard error of the intercept
SE(b₀)6.109653Intercept uncertainty
Estimated Var(b₁)1.305170Squared standard error of the slope
SE(b₁)1.142440Slope uncertainty

The page reports s² near 46.97 and intercept variance near 37.31. Recomputing from the displayed observations gives the figures above. Although these small differences do not change the conclusions, an auditable article should distinguish its recomputed values from the printed answer key.

Method reference: NIST, residual standard deviation and degrees of freedom.

Exercise 6.38: test both coefficients at the 5% level

For each coefficient, test a two-sided null hypothesis of zero against a nonzero alternative. Under the classical normal-error assumptions, compare the statistic with a Student t distribution with eight degrees of freedom. The 5% two-sided critical value is 2.3060.

H0: βj = 0   versus   H1: βj ≠ 0
tj = (bj − 0)/SE(bj)
CoefficientEstimateStandard errort statisticTwo-sided p-valueDecision at 5%
Intercept14.27786.10972.33690.047644Reject the zero-intercept null
Slope5.94441.14245.20330.000819Reject the zero-slope null

Both coefficients pass the 5% threshold, but their evidence differs substantially. In particular, the intercept barely clears that cutoff, while the slope clears the 1% threshold as well. Therefore, describing both coefficients simply as “significant” hides a useful distinction.

A p-value does not give the probability that the null hypothesis is true. Instead, it measures how incompatible the observed test statistic is with that null under the assumed sampling model. Practical relevance still depends on the response scale and the decision at hand.

Exercise 6.39: construct 95% coefficient intervals

Use the same standard errors and t critical value to construct confidence intervals. As a result, the interval and test decisions agree: a two-sided 95% interval excludes zero exactly when the corresponding two-sided test rejects at 5%.

95% CI for βj: bj ± t0.975,8SE(bj)
β0: 14.277778 ± 2.306004 × 6.109653 = [0.1889, 28.3667]
β1: 5.944444 ± 2.306004 × 1.142440 = [3.3100, 8.5789]

The slope interval covers positive associations ranging from about 3.31 to 8.58 Y units per X unit. Meanwhile, the wide intercept interval reflects uncertainty at X = 0, away from the observed range. This makes the slope more useful for describing variation within the sample.

A 95% confidence procedure captures the fixed population coefficient in 95% of repeated samples under its assumptions. However, the particular interval does not assign a frequentist 95% probability to the fixed parameter. Nor does it describe the likely range of a future individual Y value.

Exercise 6.40: calculate R² and Pearson correlation

The total centered variation equals the explained variation plus the residual variation. Consequently, R² compares the fitted model with the intercept-only prediction Ȳ. For this dataset, the line reduces the in-sample squared error by about 77.19% relative to that baseline.

SST = SSR + SSE = 1272.111111 + 375.888889 = 1648
R² = 1 − SSE/SST = 0.771912
r = Sxy/√(SxxSyy) = 214/√(36 × 1648) = 0.878585

In simple OLS regression with an intercept, R² equals r². Also, the sign of r matches the sign of the estimated slope. Taking only the positive square root of R² would give the wrong sign if the slope were negative.

The figure 77.19% concerns variation around the sample mean. It does not mean that the model predicts every observation with 77.19% accuracy. Similarly, it does not establish that X causes 77.19% of Y.

Verify the result through the ANOVA table

SourceSum of squaresDegrees of freedomMean squareF
Regression1272.11111111272.11111127.074195
Residual375.888889846.986111
Total1648.0000009

The overall F statistic equals the squared slope t statistic in this one-predictor model: 5.203287² = 27.074195. Therefore, the F test and the two-sided slope t test produce the same p-value. This identity gives another independent check on the output.

Exercise 6.41: calculate Spearman rank correlation

Pearson correlation uses the original numerical values, whereas Spearman correlation uses their ranks. Consequently, Spearman measures monotonic association and does not require a straight-line pattern. Here, both measures indicate a strong positive association.

However, X contains ties at 3, 5, and 7. Assign each tied pair its average rank before calculating the Pearson correlation of the ranks. The ordinary shortcut based on squared rank differences assumes no ties and needs care in this dataset.

ObservationXYRank of XRank of Y
122011
23282.52
35405.54
444546
53372.53
65525.57
77548.58
864375
97658.510
10856109
ρs = Corr(rank(X), rank(Y)) = 0.899120

The result rounds to 0.90, which agrees with the page’s reported answer. Interestingly, applying the no-ties shortcut to the averaged ranks gives exactly 0.9000 here. The rounded agreement hides a small methodological difference rather than validating the shortcut in general.

Method reference: SciPy, Spearman rank-order correlation.

Exercise 6.42: explain BLUE, unbiasedness, and consistency

Under the Gauss–Markov conditions, OLS is the best linear unbiased estimator, or BLUE. Each word restricts the claim. In particular, “best” means minimum variance within the class of estimators that are linear in the observed responses and unbiased.

PropertyMeaningNecessary qualification
LinearThe estimator is a weighted sum of the observed Y values, conditional on X.Linearity refers to the estimator, not a requirement that all variables enter without transformations.
UnbiasedIts conditional expectation equals the true coefficient.Requires the relevant exogeneity and specification conditions.
BestNo other linear unbiased estimator has smaller conditional variance.Requires spherical errors, including homoskedasticity and no error correlation.
ConsistentThe estimator converges in probability to the true coefficient as n grows.Requires an appropriate sampling sequence, exogeneity, finite moments, and persistent predictor variation.

For the slope, write the estimation error explicitly. This expression shows how sample covariance between the predictor and the disturbance drives the difference between the estimate and the true parameter.

b1 = β1 + Σ(Xi − X̄)ui/Sxx

Conditional mean-zero disturbances make the expectation of the extra term zero. Furthermore, suitable large-sample conditions make that term converge to zero. However, adding more observations cannot automatically repair omitted-variable bias or systematic measurement problems.

The textbook’s short answers are affirmative within its intended classical setup. A fuller answer should state those conditions rather than claim that OLS always has these properties. Also, unbiasedness alone does not ensure consistency without additional restrictions on how the estimator behaves as sample size grows.

Method reference: Duke University, Gauss–Markov and Predictive Distributions.

Exercise 6.43: distinguish three meanings of MSE

The phrase “mean squared error” appears in several places in regression. Unfortunately, the same abbreviation can describe different objects. Keeping them separate prevents an overly broad claim about what OLS optimizes.

Use of MSEFormulaWhat the quantity measures
Estimator riskE[(bⱼ − βⱼ)²] = Var(bⱼ) + Bias(bⱼ)²Repeated-sampling error in a coefficient estimate
Residual mean squareSSE/(n − 2)An estimate of the disturbance variance under the model
Training prediction lossSSE/nAverage squared residual on the fitted sample

For an unbiased coefficient estimator, the bias term vanishes. Therefore, MSE(b₀) = Var(b₀) and MSE(b₁) = Var(b₁), with the appropriate conditional formulation when treating X as fixed. Under Gauss–Markov, OLS minimizes this risk within the linear unbiased class.

However, OLS does not universally minimize coefficient MSE among every possible estimator. A biased estimator can sometimes reduce variance enough to lower total MSE. Consequently, the page’s “yes” answer needs the linear-unbiased qualification.

For the first dataset, the training average squared residual is 375.888889/10 = 37.588889. By contrast, the residual mean square is 46.986111 because it divides by eight. Neither number is an observed out-of-sample prediction error.

Exercise 6.44: regress children had on children wanted

The second table describes 12 couples. Here, X records the number of children wanted at marriage, while Y records the number of children they had. Accordingly, the requested regression puts children had on the left side and children wanted on the right.

Table 3. Observations from the supplied Table 6.13
CoupleChildren wanted (X)Children had (Y)
134
233
300
424
524
633
700
834
923
1011
1133
1221

Compute the centered sums and coefficients

The totals are ΣX = 24, ΣY = 30, ΣX² = 62, ΣY² = 102, and ΣXY = 76. Therefore, X̄ = 2 and Ȳ = 2.5. Substituting these figures gives the following exact calculation.

Sxx = 62 − 24²/12 = 14
Sxy = 76 − 24 × 30/12 = 16
Syy = 102 − 30²/12 = 27
b1 = 16/14 = 1.142857
b0 = 2.5 − 1.142857 × 2 = 0.214286
Ŷ = 0.2143 + 1.1429X

A one-child increase in the desired family size corresponds to about 1.143 additional children in the fitted outcome. However, this small observational sample cannot establish that preferences caused the difference. Age, marriage duration, fertility constraints, income, and later preference changes could matter.

Calculate uncertainty and goodness of fit

SSE = 27 − 16²/14 = 8.714286
s² = 8.714286/(12 − 2) = 0.871429
R² = 1 − 8.714286/27 = 0.677249
CoefficientEstimateSEt statisticTwo-sided p-value95% confidence interval
Intercept0.2142860.5670970.3778650.713428[−1.0493, 1.4779]
Slope1.1428570.2494894.5807870.001009[0.5870, 1.6988]

With ten residual degrees of freedom, the slope differs from zero at both 5% and 1%. Meanwhile, the intercept does not differ significantly from zero at either threshold. These are the classical model-based tests requested by the exercise, not a guarantee that a normal-error model suits a count response.

Precision check: The printed summary shows an intercept near 0.22 and t statistics near 0.39 and 4.56. Direct calculation from the displayed observations gives 0.214286, 0.377865, and 4.580787. The significance conclusions remain the same, but 0.214286 conventionally rounds to 0.21, not 0.22.
2026-10-22T21:23:43.826241 image/svg+xml Matplotlib v3.10.8, https://matplotlib.org/ 0 1 2 3 Children wanted at marriage (X) 0 1 2 3 4 Children had (Y) Marker area reflects the number of couples Twelve couples: overlapping observations matter
Figure 3. Larger markers represent repeated observations at the same pair of values. The graph displays all 12 couples without pretending overlapping points are distinct locations.

Why a fractional fitted number of children is meaningful

At X = 2, the line predicts 2.5 children. A particular couple cannot have half a child, but a conditional average can be fractional. Therefore, a fractional fitted value does not by itself invalidate a regression for a count outcome.

Nevertheless, counts have a restricted support and may exhibit nonconstant variance. A substantive analysis could consider a count model and assess the sampling process. For this exercise, OLS remains a transparent descriptive starting point.

Beyond the answer key: five insights from the same data

The following extensions connect the arithmetic to decisions an analyst actually faces. Importantly, each numerical result below comes from the supplied observations, rather than an unrelated headline statistic. This gives the article an auditable contribution beyond a generic list of formulas.

1. Repeated X values allow a lack-of-fit calculation

The first dataset contains seven distinct X values. At X = 3, 5, and 7, there are two responses each. Consequently, under the usual independent, equal-variance normal-error setup, we can separate residual variation within repeated predictor settings from variation between their means and the fitted line.

SSpure error = 40.5 + 72 + 60.5 = 173
SSlack of fit = 375.888889 − 173 = 202.888889
dfpure error = 10 − 7 = 3;   dflack of fit = 7 − 2 = 5
Flack of fit = (202.888889/5)/(173/3) = 0.703661

The upper-tail p-value is approximately 0.6596. Thus, this test does not detect a departure from a straight conditional mean. However, three pure-error degrees of freedom offer limited information, so a nonsignificant test does not prove linearity.

The interpretation also assumes that observations at a shared X are comparable independent draws from the same conditional response distribution. In observational data, unmeasured differences may contribute to their spread. Therefore, repeated X values support a calculation without resolving every design concern.

Method reference: NIST, testing functional-form lack of fit with replicates.

2. A precise mean prediction can coexist with a wide individual interval

At X = 5, the estimated conditional mean is 44. To quantify its uncertainty, use the confidence interval for the mean response. By contrast, a prediction interval for a new individual observation must also include the new observation’s disturbance.

CImean(x0) = ŷ0 ± t* s √[1/n + (x0 − X̄)²/Sxx]
PInew(x0) = ŷ0 ± t* s √[1 + 1/n + (x0 − X̄)²/Sxx]
At X = 5Point estimate95% interval
Conditional mean response44[39.0014, 48.9986]
New individual response44[27.4217, 60.5783]

The individual interval has approximately 3.32 times the width of the mean interval at the sample center. Consequently, a strong estimated slope can coexist with considerable uncertainty about one future outcome. The two statements answer different questions.

2026-10-22T21:23:44.023863 image/svg+xml Matplotlib v3.10.8, https://matplotlib.org/ 2 3 4 5 6 7 8 X 10 20 30 40 50 60 70 80 Y Predicting a person is harder than estimating a mean 95% prediction interval 95% mean confidence interval
Figure 4. Pointwise intervals under the classical normal-error model. The outer band includes individual response variation; the inner band concerns the conditional mean.

Method reference: Penn State, SLR Estimation and Prediction.

3. Centering X changes the intercept test without changing the fit

Define Z = X − 5. The same fitted relationship becomes Ŷ = 44 + 5.944444Z. Thus, the new intercept describes the fitted response at the observed center rather than at X = 0.

Its standard error equals √(46.986111/10) = 2.1676, much smaller than 6.1097 for the original intercept. Nevertheless, the slope, fitted values, residuals, and R² remain identical. Centering changes which baseline question the intercept answers, not the model’s explanatory performance.

This helps explain why intercept significance often depends on a coding choice. A different origin for X creates a different intercept hypothesis. Therefore, interpreting that p-value requires more than comparing it with 0.05.

4. The largest residual is not automatically the most influential point

Observation 9 has the largest absolute residual, about 9.1111. However, influence also depends on leverage, which measures how far a predictor value sits from the sample center. The endpoint observations at X = 2 and X = 8 each have leverage 0.35.

hii = 1/n + (Xi − X̄)²/Sxx
h(X = 2) = h(X = 8) = 0.1 + 9/36 = 0.35
h(X = 5) = 0.10

For comparison, average leverage equals 2/10 = 0.20 because the model estimates two parameters. Thus, an endpoint can pull the slope more strongly than a central observation with a comparable residual. A careful analyst investigates influential observations before deciding whether they reflect mistakes or legitimate variation.

5. Testing a zero slope differs from testing a slope of one

In the couples example, the slope strongly differs from zero. However, a one-for-one relationship poses a different hypothesis: H₀: β₁ = 1. Using the same standard error gives a much smaller test statistic.

t = (1.142857 − 1)/0.249489 = 0.5726

The two-sided p-value is about 0.580. Consequently, these observations do not establish that the slope differs from one. Describing the estimated slope as “greater than one” is numerically accurate, but describing it as statistically greater than one would overstate the evidence.

Common mistakes that change the interpretation

MistakeBetter practice
Rounding the slope before calculating residualsKeep full precision internally and round only the displayed results.
Calling R² prediction accuracyDescribe it as the proportion of centered sample variation explained by the fitted model.
Treating significance as causationSeparate sampling evidence about a coefficient from identification of a causal effect.
Using n rather than n − 2 for the unbiased error-variance estimateAccount for both estimated coefficients.
Applying the no-ties Spearman shortcut automaticallyCorrelate averaged ranks when ties occur.
Calling every OLS estimator minimum-MSESpecify the linear unbiased comparison class and relevant assumptions.
Interpreting an intercept outside the observed range literallyCheck the predictor support or center X at a meaningful value.
Using a mean confidence interval for an individual forecastInclude the additional disturbance variance in a prediction interval.

Reproduce the OLS regression calculations in Python

The following script rebuilds both models from the original observations. It also calculates the rank correlation and lack-of-fit test. Therefore, readers can inspect every input and reproduce the key results without relying on the printed answers.

import numpy as np
from scipy import stats

def ols(x, y):
    x, y = np.asarray(x, dtype=float), np.asarray(y, dtype=float)
    n = len(x)
    dx, dy = x - x.mean(), y - y.mean()
    sxx, sxy, syy = dx @ dx, dx @ dy, dy @ dy
    slope = sxy / sxx
    intercept = y.mean() - slope * x.mean()
    fitted = intercept + slope * x
    residual = y - fitted
    sse = residual @ residual
    s2 = sse / (n - 2)
    se = np.sqrt([s2 * (1/n + x.mean()**2/sxx), s2/sxx])
    estimates = np.array([intercept, slope])
    t_values = estimates / se
    p_values = 2 * stats.t.sf(np.abs(t_values), df=n-2)
    critical = stats.t.ppf(0.975, df=n-2)
    intervals = np.column_stack((estimates-critical*se,
                                 estimates+critical*se))
    return dict(estimates=estimates, se=se, t=t_values,
                p=p_values, ci95=intervals, sse=sse, s2=s2,
                r2=1-sse/syy, residuals=residual)

x = np.array([2, 3, 5, 4, 3, 5, 7, 6, 7, 8])
y = np.array([20, 28, 40, 45, 37, 52, 54, 43, 65, 56])
print(ols(x, y))
print("Spearman rho:", stats.spearmanr(x, y).statistic)

wanted = [3, 3, 0, 2, 2, 3, 0, 3, 2, 1, 3, 2]
had = [4, 3, 0, 4, 4, 3, 0, 4, 3, 1, 3, 1]
print(ols(wanted, had))

levels = np.unique(x)
pure_error = sum(np.sum((y[x == v] - y[x == v].mean())**2)
                 for v in levels)
df_pure = len(x) - len(levels)
df_lack = len(levels) - 2
lack_error = ols(x, y)["sse"] - pure_error
f_lack = (lack_error / df_lack) / (pure_error / df_pure)
print("Lack-of-fit F and p:", f_lack,
      stats.f.sf(f_lack, df_lack, df_pure))

For a spreadsheet check, place the first dataset’s X values in A2:A11 and Y values in B2:B11. Then use SLOPE(B2:B11,A2:A11), INTERCEPT(B2:B11,A2:A11), and RSQ(B2:B11,A2:A11). Verify that the response range comes first, because reversing the arguments fits a different regression.

Frequently asked questions about OLS regression

What does ordinary least squares actually minimize?

OLS minimizes the sum of squared in-sample vertical residuals over the specified coefficient values. However, minimizing that training objective does not guarantee the smallest future prediction error. Model choice and validation remain separate tasks.

Does OLS require a normally distributed X variable?

No. The classical normality assumption concerns the disturbances conditional on X, not the marginal distribution of the predictor. Also, calculating the OLS coefficients does not require any normality assumption.

Can a regression have a significant slope and a nonsignificant intercept?

Yes. The couples example shows exactly that result. Moreover, the two tests concern different population quantities, so their conclusions need not match.

Why does the fitted line pass through the sample means?

The intercept normal equation forces the residuals to sum to zero. Therefore, the average fitted response equals the average observed response. Substituting the sample mean of X into a straight fitted line reproduces that same average.

Is a high R² enough to trust the model?

No. A high R² cannot rule out confounding, nonconstant variance, dependence, influential points, or poor performance on new observations. Consequently, fit statistics should accompany diagnostics and knowledge of the data-generating process.

How should regression results appear in a report?

State the fitted equation, sample size, coefficient uncertainty, and relevant fit measures. In addition, label the numbers beneath coefficients explicitly as standard errors or t statistics. Unlabeled parentheses can make an otherwise correct result ambiguous.

Do these small samples establish a general population relationship?

Only under a defensible sampling and modeling framework. The first dataset lacks substantive context, while the couples example provides little detail about its sampling design. Therefore, treat the calculations as educational demonstrations unless additional evidence supports a broader interpretation.

Conclusion: connect the equation to its assumptions

The first dataset produces a positive fitted slope of 5.9444 and an R² of 0.7719. Its classical slope test supplies strong evidence against a zero association, although individual predictions remain much less precise than the fitted mean. Meanwhile, the couples dataset gives a slope of 1.1429 and an R² of 0.6772, with a significant slope and a nonsignificant intercept.

The deeper lesson is to keep estimation, inference, and interpretation connected. Verify the arithmetic first; then ask which assumptions support each claim. Finally, distinguish a good sample fit from a useful forecast or a credible causal explanation.

References and data notes

The supplied photographs provide the two numerical datasets and exercise identifiers. All numerical extensions, figures, and precision comparisons are calculations for this article. The following primary educational and technical sources support the methods and offer further reading.

  1. NIST/SEMATECH. Least Squares. Coefficient estimation and residual standard deviation.
  2. Penn State. SLR Model Assumptions. Conditions underlying simple linear regression.
  3. Penn State. SLR Estimation and Prediction. Mean-response and individual prediction intervals.
  4. SciPy documentation. Spearman rank-order correlation. Rank correlation and computational implementation.
  5. Duke University. Gauss–Markov and Predictive Distributions. Estimator comparisons and the variance–bias decomposition.
  6. NIST/SEMATECH. Testing for missing or misspecified model terms. Lack-of-fit testing with replicate observations.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *