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.3 — Interpreting linear models

This notebook contains the code examples from Section 4.3 Interpreting linear models from the No Bullshit Guide to Statistics.

Notebook setup


[notice] A new release of pip is available: 26.0.1 -> 26.1.2
[notice] To update, run: /Users/ivan/Projects/Minireference/STATSbook/noBSstats/venv/bin/python3.12 -m 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.

Introduction

Loading...

Model fit metrics

Coefficient of determination

0.8421649167873537
0.8421649167873537

Adjusted coefficient of determination

0.8390497506713147
0.8390497506713147

F-statistic and associated p-value

(270.34350189265837, 1.0512133413866784e-60)

Log-likelihood

-547.6259042117637
-547.651992151218
-547.6259042117637

Information criteria

(1103.2518084235273, 1115.4512324525256)
(1103.2518084235273, 1115.4512324525256)

Other model-fit metrics

The mean squared error (MSE)

(65.56013803717556, 65.56013803717558)

Parameter estimates

Intercept 60.452901 alc -1.800101 weed -1.021552 exrc 1.768289 dtype: float64
8.202768119825622
8.202768119825622

Confidence intervals for model parameters

Intercept 1.289380 alc 0.069973 weed 0.476166 exrc 0.138056 dtype: float64
Loading...

Hypothesis testing for linear models

T-tests for individual parameters

Hypothesis testing for slope coefficient

Is there a non-zero slope coefficient?

Example: t-test for the variable weed

  • Null hypothesis H0H_0: weed has no effect on score, which is equivalent to βweed=0\beta_{\texttt{weed}} = 0:

    H0:S  ∼  N(β0+βalc ⁣⋅ ⁣alc+βexrc ⁣⋅ ⁣exrc, σ)H_0: \quad S \;\sim\; \mathcal{N}( {\color{red} \beta_0 + \beta_{\texttt{alc}}\!\cdot\!\textrm{alc} + \beta_{\texttt{exrc}}\!\cdot\!\textrm{exrc} }, \ \sigma) \qquad \qquad
  • Alternative hypothesis HAH_A: weed has an effect on score, and the slope is not zero, βweed≠0\beta_{\texttt{weed}} \neq 0:

    HA:S  ∼  N(β0+βalc ⁣⋅ ⁣alc+βweed ⁣⋅ ⁣weed+βexrc ⁣⋅ ⁣exrc, σ)H_A: \quad S \;\sim\; \mathcal{N}\left( {\color{blue} \beta_0 + \beta_{\texttt{alc}}\!\cdot\!\textrm{alc} + \beta_{\texttt{weed}}\!\cdot\!\textrm{weed} + \beta_{\texttt{exrc}}\!\cdot\!\textrm{exrc} }, \ \sigma \right)
(-2.1453705454368612, 0.033511561813423206, 152.0)

Calculate the tt statistic:

-2.1453705454368612

Calculate the associated pp-value

0.033511561813423206
Intercept 46.885245 alc -25.725654 weed -2.145371 exrc 12.808529 dtype: float64
(152.0, 152.0)
Intercept 2.756807e-92 alc 2.985013e-57 weed 3.351156e-02 exrc 6.136296e-26 dtype: float64

F-test for the overall model

270.34350189265837
270.34350189265837
1.0512133413866784e-60
1.0512133413866784e-60

F-test for a submodel

(4.602614777228013, 0.03351156181342401)

The F-statistic is the same as the t-statistic

(4.602614777228013, 4.602614777228055, 4.602614777228055)
(0.03351156181342401, 0.033511561813423206, 0.033511561813423206)

Assumptions checks and diagnostics

Are the assumptions for the linear model satisfied?

Residuals plots

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

Linearity checks

Look at residuals plots.

Independence checks

Look at residuals plots.

Normality checks

Look at residuals plots...

QQ plot inspection

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

Skew and kurtosis

(0.18224568453683543, 3.074795238556266)

Homoscedasticity checks

The scale-location plot allows us to see if pattern in the variance of the residuals exists.

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

Collinearity checks

Check the correlation matrix

Loading...

Condition number

31.229721453770157
31.22972145377028

Variance inflation factor

(1.002669215630476, 1.0107031450073227, 1.010048809433661)
1.002669215630476

Perfect multicollinearity example

Intercept 60.452901 alc -0.900051 alc2 -0.900051 weed -1.021552 exrc 1.768289 dtype: float64
/Users/ivan/Projects/Minireference/software/ministats/ministats/linear_models.py:17: RuntimeWarning: divide by zero encountered in scalar divide
  vif = 1. / (1. - r_squared_i)
inf

Outliers and influential observations

TODO: definitions

Examples of outliers, high leverage points, and influential observations.

Leverage and influence metrics

TODO: add definitions of quantities in point form

Leverage plots

<Figure size 500x300 with 1 Axes>

Influence plots

<Figure size 500x300 with 1 Axes>

Model predictions

Prediction on the dataset

0 55.345142 1 32.408174 2 71.030821 3 56.789073 4 57.514154 ... 151 58.867105 152 43.049719 153 57.728460 154 69.617361 155 78.135788 Length: 156, dtype: float64

Prediction for new data

0 68.177355 dtype: float64
array([[54.50324518, 81.85146489]])

In-sample prediction accuracy

65.56013803717556
65.56013803717558

Out-of-sample prediction accuracy

TODO: explain

Leave-one-out cross-validation

69.20054514710952

Compare with the in-sample MSE of the model which is lower.

65.56013803717558

Towards machine learning

The out-of-sample prediction accuracy is a common metric used in machine learning (ML) tasks.

Explanations

Adjusted R2R^2

TODO: show formula

Calculating standard error of parameters (optional)

Intercept 1.289380 alc 0.069973 weed 0.476166 exrc 0.138056 dtype: float64
array([1.28938008, 0.06997301, 0.4761656 , 0.13805557])
(0.06987980522527787, 0.4736376432238543, 0.13736710473639843)

Metrics for influential observations

Leverage score

hi=1−riri(i),h_i = 1 - \frac{r_i}{r_{i(i)}},
array([0.09502413, 0.0129673 , 0.01709783, 0.01465484, 0.00981632])

Studentized residuals

ti=riσ^(i)1−hit_{i} = \frac{r_i}{\hat{\sigma}_{(i)} \sqrt{1-h_i}}
array([ 0.98085317, -2.03409243, -1.61072775, -0.21903275, -1.29094028])

Cook’s distance

Di=ri2p σ^2⋅hi(1−hi)2D_i = \frac{r_i^2}{p \, \widehat{\sigma}^2} \cdot \frac{h_{i}}{(1-h_{i})^2}
array([0.02526116, 0.01331454, 0.01116562, 0.00017951, 0.0041123 ])

DFFITS diagnostic

DFFITSi=y^i−y^i(i)σ^(i)hi.\textrm{DFFITS}_i = \frac{ \widehat{y}_i - \widehat{y}_{i(i)} }{ \widehat{\sigma}_{(i)} \sqrt{h_i} }.
array([ 0.31783554, -0.23314692, -0.21244055, -0.02671194, -0.12853536])

Calculating leverage and influence metrics using statsmodels

Loading...

Hypothesis tests for checking linear model assumptions

{'jb': 0.8999138579592698, 'jbpv': 0.6376556155083217, 'skew': 0.18224568453683543, 'kurtosis': 3.074795238556266, 'omni': 1.140399985281413, 'omnipv': 0.5654123490825875, 'condno': 31.229721453770157, 'mineigval': 40.14996367643264}

Hypothesis test for linearity

TtestResult(statistic=1.4317316989777142, pvalue=0.15427366179829277, df=152)

Normality tests

(1.140399985281413, 0.5654123490825875)
(0.8999138579592698, 0.6376556155083217, 0.18224568453683543, 3.074795238556266)

Independence test (autocorrelation)

1.8284830211766738

Homoskedasticity tests

Breusch-Pagan

Breusch-Pagan test

(6.254809752854332, 0.09985027888796476)
Goldfeld-Quandt test

Goldfeld-Quandt test

(1.5346515257083706, 0.033694730002866664)

Discussion

Maximum likelihood estimate

Fetching long content....
array([60.45288852, -1.80010089, -1.0215511 , 1.76828937])
array([60.45290059, -1.80010132, -1.02155166, 1.76828876])
/var/folders/yp/48zx9brn6mj6vmy50smb844w0000gn/T/ipykernel_57366/3097099034.py:9: Pandas4Warning: Starting with pandas version 4.0 all arguments of sum will be keyword-only.
  scorehats = betas[0] + (betas[1:]*preds).sum(1)
(-547.6259042118089, -547.6259042117637)

Regularization

alc 9.428506 weed 1.391068 exrc 4.796361 dtype: float64
Intercept 60.452901 alc -1.800101 weed -1.021552 exrc 1.768289 dtype: float64

L1 regularization (LASSO)

Set alpha option to the desired value α1\alpha_1 and L1_wt = 1, which means 100%100\% L1 regularization.

Intercept 58.930367 alc -1.763306 weed 0.000000 exrc 1.795228 dtype: float64

L2 regularization (ridge)

Set alpha option to the desired value α2\alpha_2 and L1_wt = 0, which means 0%0\% L1 regularization and 100%100\% L2 regularization.

Intercept 50.694960 alc -1.472536 weed -0.457425 exrc 2.323386 dtype: float64

Statsmodels diagnostics plots (BONUS TOPIC)

TODO: import explanations from .tex

<Figure size 900x260 with 3 Axes>
<Figure size 900x260 with 3 Axes>
<Figure size 900x260 with 3 Axes>

All-in-on convenience method

<Figure size 900x600 with 4 Axes>

Exercises

E4.LOGNORM Non-normal error term

<Figure size 500x300 with 1 Axes>

E4.DEP Dependent error term

E4.NL Nonlinear relationship

Intercept -14.684585 x 11.688188 dtype: float64
<Figure size 500x300 with 1 Axes>
<Figure size 500x300 with 1 Axes>
<Figure size 500x300 with 1 Axes>

E4.H Heteroskedasticity

<Figure size 500x300 with 1 Axes>

E4.v Collinearity

(Intercept 0.220927 x1 1.985774 x2 3.006225 dtype: float64, Intercept 0.253988 x1 0.137253 x2 0.167492 dtype: float64)
24.291898486251153
(17.17244980334442, 17.17244980334442)

CUT MATERIAL

Example dataset

TODO: convert to exercise in Sec 4.1

<Figure size 500x300 with 1 Axes>

Compute the variance/covariance matrix

Loading...