In 1886 Francis Galton published his observations about the height of children compared to their parents.
Regression to the Mean
Defined mid-parent as the average of the heights of the parents.
When parents are taller or shorter than average, their children are more likely to be closer to the average height than their parents.
So called “regression to the mean.”
Galton fit a straight line to this effect, and the fitting of lines or curves to data has come to be called regression as well.
Praise versus Punishment
In the 60s, psychologist Daniel Kahneman studied the effect of praise versus punishment on performance of Israeli Air Force trainees. He was led to believe that praise was more effective than punishment.
Air force trainers disagreed and said that when they praised pilots that did well, they usually did worse the next time, and when they punished pilots that did poorly, they usually did better the next time.
What Khaneman later realised was that this phenomenon could be explained by the idea of regression to the mean.
If a pilot does worse than average on a task, they are more likely to do better the next time, and if they do better than average, they are more likely to do worse the next time.
Clearly, none of these datasets agrees perfectly with the proposed model.
So the question arises:
How do we find the best linear function (or quadratic function, or logarithmic function) given the data?
Framework
Framework
This problem has been studied extensively in the field of statistics.
Certain terminology is used:
Some values are referred to as “independent,” and
Some values are referred to as “dependent.”
The basic regression task is:
given a set of independent variables
and the associated dependent variables,
estimate the parameters of a model (such as a line, parabola, etc) that describes how the dependent variables are related to the independent variables.
The independent variables are collected into a matrix \(X,\) sometimes called the design matrix.
The dependent variables are collected into an observation vector \(\mathbf{y}.\)
The parameters of the model (for any kind of model) are collected into a parameter vector \(\mathbf{\beta}.\)
The first kind of model we’ll study is a linear equation, \(y = \beta_0 + \beta_1 x.\)
Experimental data often produce points \((x_1, y_1), \dots, (x_n, y_n)\) that seem to lie close to a line.
We want to determine the parameters \(\beta_0, \beta_1\) that define a line that is as “close” to the points as possible.
Suppose we have a line \(y = \beta_0 + \beta_1 x\).
For each data point \((x_j, y_j),\) there is a point \((x_j, \beta_0 + \beta_1 x_j)\) that is the point on the line with the same \(x\)-coordinate.
Code
import numpy as npimport matplotlib.pyplot as plt# Generate some data pointsx = np.array([1, 2, 3, 4, 5])y = np.array([3.7, 2.0, 2.1, 0.1, 1.5])# Linear regression parameters (intercept and slope)beta_0 =4# interceptbeta_1 =-0.8# slope# Regression line (y = beta_0 + beta_1 * x)y_line = beta_0 + beta_1 * x# Create the plotfig, ax = plt.subplots()fig.set_size_inches(7, 5)# Plot the data pointsax.scatter(x, y, color='blue', label='Data points', zorder=5)ax.scatter(x, y_line, color='red', label='Predicted values', zorder=5)# Plot the regression lineax.plot(x, y_line, color='cyan', label='Regression line (y = β0 + β1x)', zorder=4)# Add residuals (vertical lines from points to regression line)for i inrange(len(x)): ax.vlines(x[i], y_line[i], y[i], color='blue', linestyles='dashed', label='Residual'if i ==0else"", zorder=2)y_offset = [0.2, -0.2, 0.2, -0.2, 0.2]y_line_offset = [-0.3, 0.3, -0.3, 0.3, -0.2]# Annotate pointsfor i inrange(len(x)): ax.text(x[i], y[i] + y_offset[i], f'({x[i]}, {y[i]})', fontsize=9, ha='center') ax.text(x[i], y_line[i] + y_line_offset[i], f'({x[i]}, {y_line[i]:.1f})', fontsize=9, ha='center')# Remove the box around the plot and show only x and y axis with no tics and numbersax.spines['top'].set_color('none')ax.spines['right'].set_color('none')#ax.spines['left'].set_position('zero')#ax.spines['bottom'].set_position('zero')ax.xaxis.set_ticks([])ax.yaxis.set_ticks([])# Titleax.set_title('Linear Regression with Residuals')# Add legendax.legend()# Show the plotplt.show()
We call
\(y_j\) the observed value of \(y\) and
\(\beta_0 + \beta_1 x_j\) the predicted\(y\)-value.
The difference between an observed \(y\)-value and a predicted \(y\)-value is called a residual.
There are several ways to measure how “close” the line is to the data.
The usual choice is to sum the squares of the residuals.
The least-squares line is the line \(y = \beta_0 + \beta_1x\) that minimizes the sum of squares of the residuals.
The coefficients \(\beta_0, \beta_1\) of the line are called regression coefficients.
A least-squares problem
If the data points were on the line, the parameters \(\beta_0\) and \(\beta_1\) would satisfy the equations
Of course, if the data points don’t actually lie exactly on a line,
… then there are no parameters \(\beta_0, \beta_1\) for which the predicted \(y\)-values in \(X\mathbf{\beta}\) equal the observed \(y\)-values in \(\mathbf{y}\),
… and \(X\mathbf{\beta}=\mathbf{y}\) has no solution.
Now, since the data doesn’t fall exactly on a line, we have decided to seek the \(\beta\) that minimizes the sum of squared residuals, i.e.,
The sum of squares of the residuals is exactly the square of the distance between the vectors \(X\mathbf{\beta}\) and \(\mathbf{y}.\)
Computing the least-squares solution of \(X\beta = \mathbf{y}\) is equivalent to finding the \(\mathbf{\beta}\) that determines the least-squares line.
Another way that the inconsistent linear system is often written is to collect all the residuals into a residual vector.
Then an exact equation is
\[
y = X\mathbf{\beta} + {\mathbf\epsilon},
\]
where \(\mathbf{\epsilon}\) is the residual vector.
Any equation of this form is referred to as a linear model.
In this formulation, the goal is to find the \(\beta\) so as to minimize the norm of \(\epsilon\), i.e., \(\Vert\epsilon\Vert.\)
In some cases, one would like to fit data points with something other than a straight line.
In cases like this, the matrix equation is still \(X\mathbf{\beta} = \mathbf{y}\), but the specific form of \(X\) changes from one problem to the next.
Least-Squares Fitting of Other Models
In model fitting, the parameters of the model are what is unknown.
A central question for us is whether the model is linear in its parameters.
For example, is this model linear in its parameters?
\[
y = \beta_0 e^{-\beta_1 x}
\]
It is not linear in its parameters.
Is this model linear in its parameters?
\[
y = \beta_0 e^{-2 x}
\]
It is linear in its parameters.
For a model that is linear in its parameters, an observation is a linear combination of (arbitrary) known functions.
In other words, a model that is linear in its parameters is
The \(R^2\) value is very good. We can see that the linear model does a very good job of predicting the observations \(y_i\).
Note
The summary uses the uncentered version of \(R^2\) because, as the footnote says, the model does not include a constant to account for an intercept term. You can try uncommenting the line X_with_intercept = sm.add_constant(X) and see that the summary then uses the centered version of \(R^2\).
Aside: Summary Statistics
Here is what all the statistics in the summary table mean:
R-squared (Uncentered):
Definition: Measures the proportion of the variation in the dependent variable that is explained by the model, without subtracting the mean of the dependent variable.
where \(y_i\) is the actual value, and \(\hat{y}_i\) is the predicted value from the regression.
Interpretation: Higher values (closer to 1) indicate a better fit, but this version of \(R^2\) can sometimes be misleading because it doesn’t account for the mean.
Adjusted R-squared (Uncentered):
Definition: Adjusts the uncentered \(R^2\) to account for the number of predictors in the model, preventing overfitting by penalizing for adding more variables.
where \(n\) is the number of observations, and \(p\) is the number of predictors in the model.
Interpretation: It is a more conservative measure of fit than the regular \(R^2\), particularly useful when comparing models with different numbers of predictors.
F-statistic:
Definition: The F-statistic tests whether the overall regression model is significant, i.e., whether at least one of the predictors explains a significant amount of the variance in the dependent variable.
where \(p\) is the number of predictors, and \(n\) is the number of observations.
Interpretation: A high F-statistic suggests that the model is statistically significant.
Prob (F-statistic):
Definition: This is the p-value associated with the F-statistic. It indicates the probability that the observed F-statistic would occur if the null hypothesis (that none of the predictors are significant) were true.
Interpretation: A small p-value (typically less than 0.05) suggests that the model is statistically significant, meaning that at least one predictor is important.
Log-Likelihood:
Definition: The log-likelihood measures the likelihood that the model could have produced the observed data. It is a measure of the fit of the model to the data.
where \(\sigma^2\) is the variance of the residuals.
Interpretation: A higher log-likelihood indicates a better fit of the model.
Akaike Information Criterion (AIC):
Definition: AIC is a measure of the relative quality of a statistical model for a given set of data. It penalizes the likelihood function for adding too many parameters.
where \(p\) is the number of parameters, and \(\mathcal{L}\) is the log-likelihood.
Interpretation: Lower AIC values suggest a better model fit, but it penalizes for overfitting.
Bayesian Information Criterion (BIC):
Definition: Similar to AIC, BIC penalizes models with more parameters, but more strongly than AIC. It is used to select among models.
Formula: \(\text{BIC} = p \log(n) - 2 \log(\mathcal{L})\)
where \(p\) is the number of parameters, \(n\) is the number of observations, and \(\mathcal{L}\) is the log-likelihood.
Interpretation: A lower BIC indicates a better model, with stronger penalties for models with more parameters.
Coefficient Table:
The first two columns are the independent variables and their coefficients. It is the \(m\) in \(y = mx + b\). One unit of change in the variable will affect the variable’s coefficient’s worth of change in the dependent variable. If the coefficient is negative, they have an inverse relationship. As one rises, the other falls.
The std error is an estimate of the standard deviation of the coefficient, a measurement of the amount of variation in the coefficient throughout its data points.
The t is related and is a measurement of the precision with which the coefficient was measured. A low std error compared to a high coefficient produces a high t statistic, which signifies a high significance for your coefficient.
P>|t| is one of the most important statistics in the summary. It uses the t statistic to produce the P value, a measurement of how likely your coefficient is measured through our model by chance. For example, a P value of 0.378 is saying there is a 37.8% chance the variable has no affect on the dependent variable and the results are produced by chance. Proper model analysis will compare the P value to a previously established alpha value, or a threshold with which we can apply significance to our coefficient. A common alpha is 0.05, which few of our variables pass in this instance.
[0.025 and 0.975] are both measurements of values of our coefficients within 95% of our data, or within two standard deviations. Outside of these values can generally be considered outliers.
The coefficient description came from this blog post which also describes the other statistics in the summary table.
Back to the example.
Some of the independent variables may not contribute to the accuracy of the prediction.
Code
ax = ut.plotSetup3d(-2, 2, -2, 2, -200, 200)# try columns of X with large coefficients, or notax.plot(X[:, 1], X[:, 2], 'ro', zs=y, markersize =4)
Note that each parameter of an independent variable has an associated confidence interval.
If a coefficient is not distinguishable from zero, then we cannot assume that there is any relationship between the independent variable and the observations.
In other words, if the confidence interval for the parameter includes zero, the associated independent variable may not have any predictive value.
By eliminating independent variables that are not significant, we help avoid overfitting.
Code
model = sm.OLS(y, Xsignif)results = model.fit()print(results.summary())
OLS Regression Results
=======================================================================================
Dep. Variable: y R-squared (uncentered): 0.965
Model: OLS Adj. R-squared (uncentered): 0.963
Method: Least Squares F-statistic: 437.1
Date: Thu, 24 Oct 2024 Prob (F-statistic): 2.38e-66
Time: 08:12:16 Log-Likelihood: -473.32
No. Observations: 100 AIC: 958.6
Df Residuals: 94 BIC: 974.3
Df Model: 6
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
x1 11.9350 3.162 3.775 0.000 5.657 18.213
x2 90.5841 2.705 33.486 0.000 85.213 95.955
x3 14.3652 2.924 4.913 0.000 8.560 20.170
x4 90.5586 3.289 27.535 0.000 84.028 97.089
x5 8.3185 3.028 2.747 0.007 2.307 14.330
x6 71.9119 3.104 23.169 0.000 65.749 78.075
==============================================================================
Omnibus: 9.915 Durbin-Watson: 2.056
Prob(Omnibus): 0.007 Jarque-Bera (JB): 11.608
Skew: 0.551 Prob(JB): 0.00302
Kurtosis: 4.254 Cond. No. 1.54
==============================================================================
Notes:
[1] R² is computed without centering (uncentered) since the model does not contain a constant.
[2] Standard Errors assume that the covariance matrix of the errors is correctly specified.
Real Data: House Prices in Ames, Iowa
Let’s see how powerful multiple regression can be on a real-world example.
A typical application of linear models is predicting house prices.
Linear models have been used for this problem for decades, and when a municipality does a value assessment on your house, they typically use a linear model.
We can consider various measurable attributes of a house (its “features”) as the independent variables, and the most recent sale price of the house as the dependent variable.
For our case study, we will use the features:
Lot Area (sq ft),
Gross Living Area (sq ft),
Number of Fireplaces,
Number of Full Baths,
Number of Half Baths,
Garage Area (sq ft),
Basement Area (sq ft)
So our design matrix will have 8 columns (including the constant for the intercept):
\[
X\beta = \mathbf{y},
\]
and it will have one row for each house in the data set, with \(y\) the sale price of the house.
We will use data from housing sales in Ames, Iowa from 2006 to 2009:
Note that removing the intercept will cause the \(R^2\) to go up, which is counter-intuitive. The reason is explained here] – but amounts to the fact that the formula for R2 with/without an intercept is different.
Let’s split the data into training and test sets.
Code
from sklearn import utils, model_selectionX_train, X_test, y_train, y_test = model_selection.train_test_split( X_intercept, y, test_size =0.5, random_state =0)
Fit the model to the training data.
Code
model = sm.OLS(y_train, X_train)results = model.fit()print(results.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.759
Model: OLS Adj. R-squared: 0.757
Method: Least Squares F-statistic: 325.5
Date: Thu, 24 Oct 2024 Prob (F-statistic): 1.74e-218
Time: 08:12:16 Log-Likelihood: -8746.5
No. Observations: 730 AIC: 1.751e+04
Df Residuals: 722 BIC: 1.755e+04
Df Model: 7
Covariance Type: nonrobust
===============================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------
const -4.285e+04 5350.784 -8.007 0.000 -5.34e+04 -3.23e+04
LotArea 0.2361 0.131 1.798 0.073 -0.022 0.494
GrLivArea 48.0865 4.459 10.783 0.000 39.332 56.841
Fireplaces 1.089e+04 2596.751 4.192 0.000 5787.515 1.6e+04
FullBath 1.49e+04 3528.456 4.224 0.000 7977.691 2.18e+04
HalfBath 1.56e+04 3421.558 4.559 0.000 8882.381 2.23e+04
GarageArea 98.9856 8.815 11.229 0.000 81.680 116.291
TotalBsmtSF 62.6392 4.318 14.508 0.000 54.163 71.116
==============================================================================
Omnibus: 144.283 Durbin-Watson: 1.937
Prob(Omnibus): 0.000 Jarque-Bera (JB): 917.665
Skew: 0.718 Prob(JB): 5.39e-200
Kurtosis: 8.302 Cond. No. 6.08e+04
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 6.08e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
We see that we have:
\(\beta_0\): Intercept of -$42,850
\(\beta_1\): Marginal value of one square foot of Lot Area: $0.23
but NOTICE - this coefficient is not statistically different from zero!
\(\beta_2\): Marginal value of one square foot of Gross Living Area: $48
\(\beta_3\): Marginal value of one additional fireplace: $10,890
\(\beta_4\): Marginal value of one additional full bath: $14,900
\(\beta_5\): Marginal value of one additional half bath: $15,600
\(\beta_6\): Marginal value of one square foot of Garage Area: $99
\(\beta_7\): Marginal value of one square foot of Basement Area: $62
Is our model doing a good job?
There are many statistics for testing this question, but we’ll just look at the predictions versus the ground truth.
For each house we compute its predicted sale value according to our model:
\[
\hat{\mathbf{y}} = X\hat{\beta}
\]
Code
%matplotlib inlinefrom sklearn.metrics import r2_scorefig, (ax1, ax2) = plt.subplots(1,2,sharey ='row', figsize=(12, 5))y_oos_predict = results.predict(X_test)r2_test = r2_score(y_test, y_oos_predict)ax1.scatter(y_test, y_oos_predict, s =8)ax1.set_xlabel('True Price')ax1.set_ylabel('Predicted Price')ax1.plot([0,500000], [0,500000], 'r-')ax1.axis('equal')ax1.set_ylim([0, 500000])ax1.set_xlim([0, 500000])ax1.set_title(f'Out of Sample Prediction, $R^2$ is {r2_test:0.3f}')#y_is_predict = results.predict(X_train)ax2.scatter(y_train, y_is_predict, s =8)r2_train = r2_score(y_train, y_is_predict)ax2.set_xlabel('True Price')ax2.plot([0,500000],[0,500000],'r-')ax2.axis('equal')ax2.set_ylim([0,500000])ax2.set_xlim([0,500000])ax2.set_title(f'In Sample Prediction, $R^2$ is {r2_train:0.3f}')plt.show()
We see that the model does a reasonable job for house values less than about $250,000.
It tends to underestimate at both ends of the price range.
Note that the \(R^2\) on the (held out) test data is 0.610.
We are not doing as well on test data as on training data (somewhat to be expected).
For a better model, we’d want to consider more features of each house, and perhaps some additional functions such as polynomials as components of our model.
Recap
Linear models are a powerful tool for prediction and inference
The normal equations provide a simple way to compute the model coefficients
The \(R^2\) statistic provides a simple measure of fit
Careful use of the model is required to avoid overfitting