Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 4.1 — Simple linear regression

This notebook contains the code examples from Section 4.1 Simple linear regression from the No Bullshit Guide to Statistics.

Notebook setup


[notice] A new release of pip is available: 26.2.1 -> 26.2.2
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.
<Figure size 640x480 with 0 Axes>
datasets/ directory already exists.

\def\stderr#1{\mathbf{se}_{#1}} \def\stderrhat#1{\hat{\mathbf{se}}_{#1}} \def\Mean{\textbf{mean}} \def\Var{\textbf{var}} \def\Std{\textbf{std}} \def\Freq{\textbf{freq}} \def\RelFreq{\textbf{relfreq}} \def\CI#1{\textbf{CI}_{#1}} \def\CIL#1{\textbf{L}_{#1}} \def\CIU#1{\textbf{U}_{#1}} \def\ci#1{\textbf{ci}_{#1}} \def\cil#1{\textbf{l}_{#1}} \def\ciu#1{\textbf{u}_{#1}} \def\DMeans{\textbf{dmeans}} \def\Prop{\textbf{prop}} \def\DProps{\textbf{dprops}} \def\Err{ {\Large \varepsilon}} \def\calN{\mathcal{N}} \def\Tdist{\mathcal{T}} \def\Expon{\mathrm{Expon}}

(this cell contains the macro definitions like sex‾\stderr{\overline{\mathbf{x}}}, se^\stderrhat{}, mean\Mean, ...)

Definitions

TODO: add definitions

Linear model

The regression line describes the expected value of the outcome variable Y at different values of x

Example: students score as a function of effort

Loading...
<Figure size 500x300 with 1 Axes>

Compute the correlation

0.8794375135614694

Parameter estimation using least squares

4.504850344209071
32.46580930159963
<Figure size 500x300 with 1 Axes>

Least squares optimization for the parameters

How do we find the parameter estimates of the model?

<Figure size 500x300 with 1 Axes>
<Figure size 500x300 with 1 Axes>

Estimating the standard deviation parameter

0 -6.838969 1 3.387041 2 -4.207522 3 2.155776 dtype: float64
4.929598282660258

Model diagnostics

Scatter plots

<Figure size 500x300 with 1 Axes>

Examples of nonlinear patterns

Examples of scatter plots showing nonlinear patterns.

Residuals plots

Residuals versus the predicted values

<Figure size 500x300 with 1 Axes>

Residuals versus the predictor (bonus)

QQ-plot of the residuals

<Figure size 500x300 with 1 Axes>

Residual plots that show violated assumptions

Examples of residual plots showing violated modeling assumptions.

Sum of squares quantities

Sum of squared residuals

315.9122099692906

Explained sum of squares

1078.2917900307098

Total sum of squares

1394.2040000000002
1394.2040000000004

Coefficient of determination R2R^2

0.7734103402591799

Using linear models to make predictions

Confidence interval for the mean

TODO: add formulas

Confidence interval for observations

TODO: add formulas

Example:predicting students’ scores

Predict the score of a new student who invests 9 hours of effort per week.

73.0

Confidence interval for the mean score

1.2744485881877106
[70.74303643371006, 75.25696356628994]

Prediction band for the mean score

Plot of the 90% confidence interval for the mean

Confidence interval for predicted scores

5.0916754052414435
[63.982981983332934, 82.01701801666707]

Prediction band for scores

Plot of the 90% confidence interval for the outcomes.

Prediction caveats

(5.21, 12.0)

It’s not OK to extrapolate the validity of the model outside of the range of values where we have observed data.

For example, there is no reason to believe in the model’s predictions about an effort of 20 hours per week:

122.5

Indeed, the model predicts the grade will be above 100% which is impossible.

Explanations

Software for fitting linear models

  • scipy

  • statsmodels

  • scikit-learn

Fitting linear models with statsmodels

statsmodels.regression.linear_model.RegressionResultsWrapper

Estimated parameters for the model

Intercept 32.465809 effort 4.504850 dtype: float64
pandas.Series

We often want to extract the intercept and slope parameters for use in subsequent calculations.

(32.46580930159963, 4.504850344209071)

The estimate σ^\widehat{\sigma} is obtained by taking the square root of the .scale attribute.

4.929598282660258

Model fitted values

0 81.838969 1 71.612959 2 71.207522 3 68.144224 4 77.063828 5 81.118193 6 67.648690 7 73.595093 8 55.936080 9 67.198205 10 76.703440 11 84.406734 12 64.450247 13 61.251803 14 86.524013 dtype: float64

Residuals

0 -6.838969 1 3.387041 2 -4.207522 3 2.155776 4 -0.963828 5 -1.318193 6 5.051310 7 1.804907 8 1.063920 9 1.801795 10 -6.303440 11 11.793266 12 -1.550247 13 -3.651803 14 -2.224013 dtype: float64

Sum-of-squared quantities

(315.9122099692906, 1078.2917900307095, 1394.2040000000002, 0.7734103402591798)

Predictions

Predict the score of a new student who invests 9 hours of effort per week.

0 73.009462 dtype: float64
(array([1.27444859]), array([[70.75249883, 75.26642597]]))
<statsmodels.regression._prediction.PredictionResults at 0x1155ffda0>
(array([5.09167541]), array([[63.99244438, 82.02648042]]))

Model summary table

Loading...

Helper functions for plotting linear model results

  • plot_reg(lm): generate a regression plot for the model lm

  • plot_resid(lm): residuals plot for the model lm

  • plot_pred_bands(lm, ...): plot confidence intervals model lm. Use ci_mean=True to plot the predictions for the mean, or ci_obs=True to plot the predictions of the observations variable.

Regression plot

<Figure size 500x300 with 1 Axes>

Residuals plot

False
False
<Figure size 500x300 with 1 Axes>
<Figure size 500x300 with 1 Axes>

Prediction band plots

<Figure size 500x300 with 1 Axes>
<Figure size 500x300 with 1 Axes>

Seaborn functions for plotting linear models

Regression plot

<Figure size 500x300 with 1 Axes>

Residual plot

<Figure size 500x300 with 1 Axes>

Pearson correlation coefficient revisited

0.8794375135614694
0.7734103402591797
0.7734103402591798

Alternative methods for fitting linear models (optional)

Numerical optimization

(32.465809793102544, 4.504850301246796)

Linear algebra

linear algebra solution using numpy

array([[ 1. , 10.96], [ 1. , 8.69], [ 1. , 8.6 ], [ 1. , 7.92], [ 1. , 9.9 ], [ 1. , 10.8 ], [ 1. , 7.81], [ 1. , 9.13], [ 1. , 5.21], [ 1. , 7.71], [ 1. , 9.82], [ 1. , 11.53], [ 1. , 7.1 ], [ 1. , 6.39], [ 1. , 12. ]])

We obtain the least squares solution using the Moore–Penrose inverse formula:

β⃗=(XTX)−1XT  y\vec{\beta} = (X^{\sf T} X)^{-1}X^{\sf T}\; \mathbf{y}
(32.465809301599236, 4.504850344209086)

Fitting linear models using scipy

The helper function scipy.stats.linregress ...

(32.465809301599634, 4.50485034420907)

Fitting linear models using scikit-learn

The class sklearn.linear_model.LinearRegression allows us to fit linear models.

Using the statsmodels low-level matrix API

(32.46580930159963, 4.504850344209071)

Discussion

Maximum likelihood estimation

(32.46581025941632, 4.504850229485637)
-44.139684178072535
-44.139684178072514

Examples of non-linear relationships

Hare are some examples of the different possible relationships between the effort and score variables.

nonlinear relantionships

(BONUS MATERIAL) Formula for standard error of coefficients

Intercept 6.155051 effort 0.676276 dtype: float64

Formula using summations

se(β0)=σ^⋅1n+x‾2∑(xi−x‾)2se(β1)=σ^⋅1∑(xi−x‾)2se(\beta_0) = \hat{\sigma} \cdot \sqrt{ \frac{1}{n} + \frac{\overline{x}^2}{\sum (x_i - \overline{x})^2} } \qquad se(\beta_1) = \hat{\sigma} \cdot \sqrt{\frac{1}{\sum (x_i - \overline{x})^2}}

TODO: show derivation why these formulas are equiv. to matrix formulas below when p=1

(6.155051380977695, 0.6762756464968055)

Alternative formula using design matrix

[se(β0),se(β1)]=σ^⋅diag((XTX)−1)[se(\beta_0), se(\beta_1)] = \hat{\sigma} \cdot \text{diag}\left( \sqrt{ (X^T X)^{-1} } \right)

where XX is the design matrix.

array([6.15505138, 0.67627565])
array([10.96, 8.69, 8.6 , 7.92, 9.9 , 10.8 , 7.81, 9.13, 5.21, 7.71, 9.82, 11.53, 7.1 , 6.39, 12. ])