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.
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.
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.
| Observation | X | Y | X² | XY |
|---|---|---|---|---|
| 1 | 2 | 20 | 4 | 40 |
| 2 | 3 | 28 | 9 | 84 |
| 3 | 5 | 40 | 25 | 200 |
| 4 | 4 | 45 | 16 | 180 |
| 5 | 3 | 37 | 9 | 111 |
| 6 | 5 | 52 | 25 | 260 |
| 7 | 7 | 54 | 49 | 378 |
| 8 | 6 | 43 | 36 | 258 |
| 9 | 7 | 65 | 49 | 455 |
| 10 | 8 | 56 | 64 | 448 |
| Total | 50 | 440 | 286 | 2414 |
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.
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.
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.
| Condition | Mathematical statement | Why it matters |
|---|---|---|
| Linear conditional mean | Yᵢ = β₀ + β₁Xᵢ + uᵢ | The parameters enter linearly. |
| Predictor variation | Sxx > 0 | The data must contain more than one X value. |
| Conditional mean zero | E(uᵢ | X₁,…,Xₙ) = 0 | The regressors do not systematically predict the omitted disturbance. |
| Constant conditional variance | Var(uᵢ | X) = σ² | The usual homoskedastic standard-error formula applies. |
| No conditional error correlation | Cov(uᵢ,uⱼ | X) = 0 for i ≠ j | Different observations do not share correlated disturbances. |
| Joint normal errors for exact small-sample inference | u | 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.
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/∂b1 = −2ΣXi(Yi − b0 − b1Xi) = 0
Σ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.
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.
b0 = 44 − (107/18) × 5 = 257/18 = 14.277777…
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).
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.
| Observation | X | Y | Fitted Y | Residual e | e² |
|---|---|---|---|---|---|
| 1 | 2 | 20 | 26.1667 | -6.1667 | 38.0278 |
| 2 | 3 | 28 | 32.1111 | -4.1111 | 16.9012 |
| 3 | 5 | 40 | 44.0000 | -4.0000 | 16.0000 |
| 4 | 4 | 45 | 38.0556 | 6.9444 | 48.2253 |
| 5 | 3 | 37 | 32.1111 | 4.8889 | 23.9012 |
| 6 | 5 | 52 | 44.0000 | 8.0000 | 64.0000 |
| 7 | 7 | 54 | 55.8889 | -1.8889 | 3.5679 |
| 8 | 6 | 43 | 49.9444 | -6.9444 | 48.2253 |
| 9 | 7 | 65 | 55.8889 | 9.1111 | 83.0123 |
| 10 | 8 | 56 | 61.8333 | -5.8333 | 34.0278 |
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̄) = 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.
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(b0) = √[s²(1/n + X̄²/Sxx)] = 6.109653
| Quantity | Unrounded-calculation result | Interpretation |
|---|---|---|
| s² | 46.986111 | Estimated common disturbance variance |
| s | 6.854642 | Residual standard deviation |
| Estimated Var(b₀) | 37.327855 | Squared standard error of the intercept |
| SE(b₀) | 6.109653 | Intercept uncertainty |
| Estimated Var(b₁) | 1.305170 | Squared standard error of the slope |
| SE(b₁) | 1.142440 | Slope 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.
tj = (bj − 0)/SE(bj)
| Coefficient | Estimate | Standard error | t statistic | Two-sided p-value | Decision at 5% |
|---|---|---|---|---|---|
| Intercept | 14.2778 | 6.1097 | 2.3369 | 0.047644 | Reject the zero-intercept null |
| Slope | 5.9444 | 1.1424 | 5.2033 | 0.000819 | Reject 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%.
β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.
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
| Source | Sum of squares | Degrees of freedom | Mean square | F |
|---|---|---|---|---|
| Regression | 1272.111111 | 1 | 1272.111111 | 27.074195 |
| Residual | 375.888889 | 8 | 46.986111 | |
| Total | 1648.000000 | 9 |
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.
| Observation | X | Y | Rank of X | Rank of Y |
|---|---|---|---|---|
| 1 | 2 | 20 | 1 | 1 |
| 2 | 3 | 28 | 2.5 | 2 |
| 3 | 5 | 40 | 5.5 | 4 |
| 4 | 4 | 45 | 4 | 6 |
| 5 | 3 | 37 | 2.5 | 3 |
| 6 | 5 | 52 | 5.5 | 7 |
| 7 | 7 | 54 | 8.5 | 8 |
| 8 | 6 | 43 | 7 | 5 |
| 9 | 7 | 65 | 8.5 | 10 |
| 10 | 8 | 56 | 10 | 9 |
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.
| Property | Meaning | Necessary qualification |
|---|---|---|
| Linear | The 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. |
| Unbiased | Its conditional expectation equals the true coefficient. | Requires the relevant exogeneity and specification conditions. |
| Best | No other linear unbiased estimator has smaller conditional variance. | Requires spherical errors, including homoskedasticity and no error correlation. |
| Consistent | The 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.
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 MSE | Formula | What the quantity measures |
|---|---|---|
| Estimator risk | E[(bⱼ − βⱼ)²] = Var(bⱼ) + Bias(bⱼ)² | Repeated-sampling error in a coefficient estimate |
| Residual mean square | SSE/(n − 2) | An estimate of the disturbance variance under the model |
| Training prediction loss | SSE/n | Average 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.
| Couple | Children wanted (X) | Children had (Y) |
|---|---|---|
| 1 | 3 | 4 |
| 2 | 3 | 3 |
| 3 | 0 | 0 |
| 4 | 2 | 4 |
| 5 | 2 | 4 |
| 6 | 3 | 3 |
| 7 | 0 | 0 |
| 8 | 3 | 4 |
| 9 | 2 | 3 |
| 10 | 1 | 1 |
| 11 | 3 | 3 |
| 12 | 2 | 1 |
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.
Sxy = 76 − 24 × 30/12 = 16
Syy = 102 − 30²/12 = 27
b1 = 16/14 = 1.142857
b0 = 2.5 − 1.142857 × 2 = 0.214286
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
s² = 8.714286/(12 − 2) = 0.871429
R² = 1 − 8.714286/27 = 0.677249
| Coefficient | Estimate | SE | t statistic | Two-sided p-value | 95% confidence interval |
|---|---|---|---|---|---|
| Intercept | 0.214286 | 0.567097 | 0.377865 | 0.713428 | [−1.0493, 1.4779] |
| Slope | 1.142857 | 0.249489 | 4.580787 | 0.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.
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.
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.
PInew(x0) = ŷ0 ± t* s √[1 + 1/n + (x0 − X̄)²/Sxx]
| At X = 5 | Point estimate | 95% interval |
|---|---|---|
| Conditional mean response | 44 | [39.0014, 48.9986] |
| New individual response | 44 | [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.
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.
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.
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
| Mistake | Better practice |
|---|---|
| Rounding the slope before calculating residuals | Keep full precision internally and round only the displayed results. |
| Calling R² prediction accuracy | Describe it as the proportion of centered sample variation explained by the fitted model. |
| Treating significance as causation | Separate sampling evidence about a coefficient from identification of a causal effect. |
| Using n rather than n − 2 for the unbiased error-variance estimate | Account for both estimated coefficients. |
| Applying the no-ties Spearman shortcut automatically | Correlate averaged ranks when ties occur. |
| Calling every OLS estimator minimum-MSE | Specify the linear unbiased comparison class and relevant assumptions. |
| Interpreting an intercept outside the observed range literally | Check the predictor support or center X at a meaningful value. |
| Using a mean confidence interval for an individual forecast | Include 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.
- NIST/SEMATECH. Least Squares. Coefficient estimation and residual standard deviation.
- Penn State. SLR Model Assumptions. Conditions underlying simple linear regression.
- Penn State. SLR Estimation and Prediction. Mean-response and individual prediction intervals.
- SciPy documentation. Spearman rank-order correlation. Rank correlation and computational implementation.
- Duke University. Gauss–Markov and Predictive Distributions. Estimator comparisons and the variance–bias decomposition.
- NIST/SEMATECH. Testing for missing or misspecified model terms. Lack-of-fit testing with replicate observations.

