Sub topic 13
Estimating the Line with Ordinary Least Squares
Assume you know the mean, variance, and standard deviation; basic algebra; and the idea of a sample. This chapter shows how ordinary least squares (OLS) estimates a simple linear regression line.
The regression line
A simple regression explains a dependent variable \(y\) with one independent variable \(x\):
\hat{y}_i = b_0 + b_1x_iHere, \(\hat{y}i\) is the predicted value, \(b0\) is the intercept, and \(b_1\) is the slope. The residual is the difference between the observed and predicted values:
e_i = y_i - \hat{y}_iOLS chooses \(b0\) and \(b1\) to minimize the sum of squared residuals:
SSE = \sum_{i=1}^{n}(y_i-\hat{y}_i)^2Squaring prevents positive and negative residuals from canceling. It also gives larger errors more weight.
Calculating the slope and intercept
The OLS slope is:
b_1=\frac{\sum (x_i-\bar{x})(y_i-\bar{y})}{\sum (x_i-\bar{x})^2}The intercept is:
b_0=\bar{y}-b_1\bar{x}Consider these observations:
| x | y |
|---|---|
| 1 | 2.1 |
| 2 | 3.9 |
| 3 | 6.2 |
| 4 | 7.8 |
| 5 | 10.1 |
The means are \(\bar{x}=3\) and \(\bar{y}=6.02\). The numerator for the slope is 19.9, and the denominator is 10. Therefore:
- \(b_1=19.9/10=1.99\)
- \(b_0=6.02-(1.99)(3)=0.05\)
The estimated line is:
\hat{y}=0.05+1.99xThe slope means that a one-unit increase in \(x\) is associated with an estimated 1.99-unit increase in \(y\). The intercept is the predicted value of \(y\) when \(x=0\). Interpret it only when \(x=0\) is meaningful and within the relevant data range.
import numpy as np
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([2.1, 3.9, 6.2, 7.8, 10.1])
x_bar = x.mean()
y_bar = y.mean()
b1 = np.sum((x - x_bar) * (y - y_bar)) / np.sum((x - x_bar) ** 2)
b0 = y_bar - b1 * x_bar
y_hat = b0 + b1 * x
print(f"intercept = {b0:.2f}")
print(f"slope = {b1:.2f}")
print("predictions =", np.round(y_hat, 2))Common errors
Do not reverse the numerator and denominator in the slope formula. The denominator uses only deviations of \(x\), because it measures the variation available to explain \(y\). Also distinguish an observed \(y\) from a predicted \(\hat{y}\). Their difference is the residual.
Exercise
If b0 = 2 and b1 = 3, what value does the OLS line predict when x = 4?
Show answer
The prediction is y-hat = 2 + 3(4) = 14.