library(reticulate)
library(readr)
library(tidymodels)
library(tidyverse)
library(rsample)
library(caret)
library(h2o)
library(here)
library(dunnr)
library(dunnr)
library(broom)
library(visreg)
library(DHARMa)
#py_install("mlxtend")SUPERVISED LEARNING WITH SCIKIT-LEARN AND TIDYMODELS
AI and Machine Learning for Public Health Practioners
2026-01-02
Library Setup
use_python("C:/Users/r1953/AppData/Local/Programs/Python/Python313/python.exe", required = TRUE)
use_virtualenv("~/.virtualenvs/r-reticulate", required = TRUE)
#py_config()
#py_install("scikit-learn")
#py_install("pandas")
#py_install("numpy")
#py_install("matplotlib")import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from mlxtend.plotting import plot_labeled_decision_regions
#> ImportError: cannot import name 'plot_labeled_decision_regions' from 'mlxtend.plotting' (C:\Users\r1953\OneDrive\DOCUME~1\VIRTUA~1\R-RETI~1\Lib\site-packages\mlxtend\plotting\__init__.py)Data Preparation
housing_df = pd.read_csv("house.csv")
print(housing_df.head())
#> CRIM ZN INDUS CHAS ... PT B LSTAT Price
#> 0 0.00632 18.0 2.31 0 ... 15.300000 396.899994 4.98 24.000000
#> 1 0.02731 0.0 7.07 0 ... 17.799999 396.899994 9.14 21.600000
#> 2 0.02729 0.0 7.07 0 ... 17.799999 392.829987 4.03 34.700001
#> 3 0.03237 0.0 2.18 0 ... 18.700001 394.630005 2.94 33.400002
#> 4 0.06905 0.0 2.18 0 ... 18.700001 396.899994 5.33 36.200001
#>
#> [5 rows x 14 columns]url = "house.csv"
housing_df<-read_csv(url)
housing_df |>
head()| CRIM | ZN | INDUS | CHAS | NOX | RM | AGE | DIS | RAD | TAX | PT | B | LSTAT | Price |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.00632 | 18 | 2.31 | 0 | 0.538 | 6.575 | 65.2 | 4.0900 | 1 | 296 | 15.3 | 396.90 | 4.98 | 24.0 |
| 0.02731 | 0 | 7.07 | 0 | 0.469 | 6.421 | 78.9 | 4.9671 | 2 | 242 | 17.8 | 396.90 | 9.14 | 21.6 |
| 0.02729 | 0 | 7.07 | 0 | 0.469 | 7.185 | 61.1 | 4.9671 | 2 | 242 | 17.8 | 392.83 | 4.03 | 34.7 |
| 0.03237 | 0 | 2.18 | 0 | 0.458 | 6.998 | 45.8 | 6.0622 | 3 | 222 | 18.7 | 394.63 | 2.94 | 33.4 |
| 0.06905 | 0 | 2.18 | 0 | 0.458 | 7.147 | 54.2 | 6.0622 | 3 | 222 | 18.7 | 396.90 | 5.33 | 36.2 |
| 0.02985 | 0 | 2.18 | 0 | 0.458 | 6.430 | 58.7 | 6.0622 | 3 | 222 | 18.7 | 394.12 | 5.21 | 28.7 |
Data dimension
housing_df.shape
#> (506, 14)dim(housing_df)
#> [1] 506 14Check Missing data
housing_df.isna()
#> CRIM ZN INDUS CHAS NOX ... TAX PT B LSTAT Price
#> 0 False False False False False ... False False False False False
#> 1 False False False False False ... False False False False False
#> 2 False False False False False ... False False False False False
#> 3 False False False False False ... False False False False False
#> 4 False False False False False ... False False False False False
#> .. ... ... ... ... ... ... ... ... ... ... ...
#> 501 False False False False False ... False False False False False
#> 502 False False False False False ... False False False False False
#> 503 False False False False False ... False False False False False
#> 504 False False False False False ... False False False False False
#> 505 False False False False False ... False False False False False
#>
#> [506 rows x 14 columns]is.na(housing_df) |>
as_tibble() |>
head()| CRIM | ZN | INDUS | CHAS | NOX | RM | AGE | DIS | RAD | TAX | PT | B | LSTAT | Price |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
| FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE |
Sum of missing data in each column
housing_df.isna().sum()
#> CRIM 0
#> ZN 0
#> INDUS 0
#> CHAS 0
#> NOX 0
#> RM 0
#> AGE 0
#> DIS 0
#> RAD 0
#> TAX 0
#> PT 0
#> B 0
#> LSTAT 0
#> Price 0
#> dtype: int64colSums(is.na(housing_df))
#> CRIM ZN INDUS CHAS NOX RM AGE DIS RAD TAX PT B LSTAT
#> 0 0 0 0 0 0 0 0 0 0 0 0 0
#> Price
#> 0Data description
housing_df.info()
#> <class 'pandas.core.frame.DataFrame'>
#> RangeIndex: 506 entries, 0 to 505
#> Data columns (total 14 columns):
#> # Column Non-Null Count Dtype
#> --- ------ -------------- -----
#> 0 CRIM 506 non-null float64
#> 1 ZN 506 non-null float64
#> 2 INDUS 506 non-null float64
#> 3 CHAS 506 non-null int64
#> 4 NOX 506 non-null float64
#> 5 RM 506 non-null float64
#> 6 AGE 506 non-null float64
#> 7 DIS 506 non-null float64
#> 8 RAD 506 non-null int64
#> 9 TAX 506 non-null int64
#> 10 PT 506 non-null float64
#> 11 B 506 non-null float64
#> 12 LSTAT 506 non-null float64
#> 13 Price 506 non-null float64
#> dtypes: float64(11), int64(3)
#> memory usage: 55.5 KBhousing_df.describe()
#> CRIM ZN INDUS ... B LSTAT Price
#> count 506.000000 506.000000 506.000000 ... 506.000000 506.000000 506.000000
#> mean 3.613524 11.363636 11.136779 ... 356.674030 12.653063 22.532806
#> std 8.601545 23.322453 6.860353 ... 91.294863 7.141062 9.197104
#> min 0.006320 0.000000 0.460000 ... 0.320000 1.730000 5.000000
#> 25% 0.082045 0.000000 5.190000 ... 375.377487 6.950000 17.025000
#> 50% 0.256510 0.000000 9.690000 ... 391.440002 11.360000 21.200001
#> 75% 3.677083 12.500000 18.100000 ... 396.225006 16.954999 25.000000
#> max 88.976196 100.000000 27.740000 ... 396.899994 37.970001 50.000000
#>
#> [8 rows x 14 columns]str(housing_df)
#> spc_tbl_ [506 × 14] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
#> $ CRIM : num [1:506] 0.00632 0.02731 0.02729 0.03237 0.06905 ...
#> $ ZN : num [1:506] 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
#> $ INDUS: num [1:506] 2.31 7.07 7.07 2.18 2.18 ...
#> $ CHAS : num [1:506] 0 0 0 0 0 0 0 0 0 0 ...
#> $ NOX : num [1:506] 0.538 0.469 0.469 0.458 0.458 ...
#> $ RM : num [1:506] 6.57 6.42 7.18 7 7.15 ...
#> $ AGE : num [1:506] 65.2 78.9 61.1 45.8 54.2 ...
#> $ DIS : num [1:506] 4.09 4.97 4.97 6.06 6.06 ...
#> $ RAD : num [1:506] 1 2 2 3 3 3 5 5 5 5 ...
#> $ TAX : num [1:506] 296 242 242 222 222 222 311 311 311 311 ...
#> $ PT : num [1:506] 15.3 17.8 17.8 18.7 18.7 ...
#> $ B : num [1:506] 397 397 393 395 397 ...
#> $ LSTAT: num [1:506] 4.98 9.14 4.03 2.94 5.33 ...
#> $ Price: num [1:506] 24 21.6 34.7 33.4 36.2 ...
#> - attr(*, "spec")=
#> .. cols(
#> .. CRIM = col_double(),
#> .. ZN = col_double(),
#> .. INDUS = col_double(),
#> .. CHAS = col_double(),
#> .. NOX = col_double(),
#> .. RM = col_double(),
#> .. AGE = col_double(),
#> .. DIS = col_double(),
#> .. RAD = col_double(),
#> .. TAX = col_double(),
#> .. PT = col_double(),
#> .. B = col_double(),
#> .. LSTAT = col_double(),
#> .. Price = col_double()
#> .. )
#> - attr(*, "problems")=<externalptr>summary(housing_df)
#> CRIM ZN INDUS CHAS
#> Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
#> 1st Qu.: 0.08205 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
#> Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
#> Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
#> 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
#> Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
#> NOX RM AGE DIS
#> Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
#> 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
#> Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
#> Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
#> 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
#> Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
#> RAD TAX PT B
#> Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
#> 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
#> Median : 5.000 Median :330.0 Median :19.05 Median :391.44
#> Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
#> 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
#> Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
#> LSTAT Price
#> Min. : 1.73 Min. : 5.00
#> 1st Qu.: 6.95 1st Qu.:17.02
#> Median :11.36 Median :21.20
#> Mean :12.65 Mean :22.53
#> 3rd Qu.:16.95 3rd Qu.:25.00
#> Max. :37.97 Max. :50.00Correlations matrix
housing_df.corr()
#> CRIM ZN INDUS ... B LSTAT Price
#> CRIM 1.000000 -0.200469 0.406583 ... -0.385064 0.455621 -0.388305
#> ZN -0.200469 1.000000 -0.533828 ... 0.175520 -0.412995 0.360445
#> INDUS 0.406583 -0.533828 1.000000 ... -0.356977 0.603800 -0.483725
#> CHAS -0.055892 -0.042697 0.062938 ... 0.048788 -0.053929 0.175260
#> NOX 0.420972 -0.516604 0.763651 ... -0.380051 0.590879 -0.427321
#> RM -0.219247 0.311991 -0.391676 ... 0.128069 -0.613808 0.695360
#> AGE 0.352734 -0.569537 0.644779 ... -0.273534 0.602339 -0.376955
#> DIS -0.379670 0.664408 -0.708027 ... 0.291512 -0.496996 0.249929
#> RAD 0.625505 -0.311948 0.595129 ... -0.444413 0.488676 -0.381626
#> TAX 0.582764 -0.314563 0.720760 ... -0.441808 0.543993 -0.468536
#> PT 0.289946 -0.391679 0.383248 ... -0.177383 0.374044 -0.507787
#> B -0.385064 0.175520 -0.356977 ... 1.000000 -0.366087 0.333461
#> LSTAT 0.455621 -0.412995 0.603800 ... -0.366087 1.000000 -0.737663
#> Price -0.388305 0.360445 -0.483725 ... 0.333461 -0.737663 1.000000
#>
#> [14 rows x 14 columns]cor(housing_df)
#> CRIM ZN INDUS CHAS NOX RM
#> CRIM 1.00000000 -0.20046922 0.40658343 -0.055891582 0.4209717 -0.21924670
#> ZN -0.20046922 1.00000000 -0.53382819 -0.042696719 -0.5166037 0.31199059
#> INDUS 0.40658343 -0.53382819 1.00000000 0.062938027 0.7636515 -0.39167586
#> CHAS -0.05589158 -0.04269672 0.06293803 1.000000000 0.0912028 0.09125123
#> NOX 0.42097173 -0.51660371 0.76365146 0.091202805 1.0000000 -0.30218816
#> RM -0.21924670 0.31199059 -0.39167586 0.091251227 -0.3021882 1.00000000
#> AGE 0.35273425 -0.56953734 0.64477851 0.086517774 0.7314701 -0.24026491
#> DIS -0.37967009 0.66440822 -0.70802699 -0.099175778 -0.7692301 0.20524620
#> RAD 0.62550515 -0.31194783 0.59512930 -0.007368241 0.6114406 -0.20984667
#> TAX 0.58276431 -0.31456332 0.72076020 -0.035586518 0.6680232 -0.29204784
#> PT 0.28994564 -0.39167853 0.38324764 -0.121515169 0.1889327 -0.35550150
#> B -0.38506395 0.17552031 -0.35697654 0.048788489 -0.3800506 0.12806863
#> LSTAT 0.45562148 -0.41299458 0.60379972 -0.053929297 0.5908789 -0.61380826
#> Price -0.38830461 0.36044534 -0.48372517 0.175260178 -0.4273208 0.69535994
#> AGE DIS RAD TAX PT B
#> CRIM 0.35273425 -0.37967009 0.625505147 0.58276431 0.2899456 -0.38506395
#> ZN -0.56953734 0.66440822 -0.311947826 -0.31456332 -0.3916785 0.17552031
#> INDUS 0.64477851 -0.70802699 0.595129296 0.72076020 0.3832476 -0.35697654
#> CHAS 0.08651777 -0.09917578 -0.007368241 -0.03558652 -0.1215152 0.04878849
#> NOX 0.73147011 -0.76923012 0.611440565 0.66802321 0.1889327 -0.38005064
#> RM -0.24026491 0.20524620 -0.209846669 -0.29204784 -0.3555015 0.12806863
#> AGE 1.00000000 -0.74788054 0.456022454 0.50645560 0.2615150 -0.27353397
#> DIS -0.74788054 1.00000000 -0.494587929 -0.53443158 -0.2324706 0.29151167
#> RAD 0.45602245 -0.49458793 1.000000000 0.91022819 0.4647413 -0.44441282
#> TAX 0.50645560 -0.53443158 0.910228189 1.00000000 0.4608531 -0.44180801
#> PT 0.26151502 -0.23247057 0.464741268 0.46085312 1.0000000 -0.17738334
#> B -0.27353397 0.29151167 -0.444412818 -0.44180801 -0.1773833 1.00000000
#> LSTAT 0.60233853 -0.49699583 0.488676336 0.54399341 0.3740444 -0.36608690
#> Price -0.37695457 0.24992874 -0.381626232 -0.46853594 -0.5077867 0.33346082
#> LSTAT Price
#> CRIM 0.4556215 -0.3883046
#> ZN -0.4129946 0.3604453
#> INDUS 0.6037997 -0.4837252
#> CHAS -0.0539293 0.1752602
#> NOX 0.5908789 -0.4273208
#> RM -0.6138083 0.6953599
#> AGE 0.6023385 -0.3769546
#> DIS -0.4969958 0.2499287
#> RAD 0.4886763 -0.3816262
#> TAX 0.5439934 -0.4685359
#> PT 0.3740444 -0.5077867
#> B -0.3660869 0.3334608
#> LSTAT 1.0000000 -0.7376627
#> Price -0.7376627 1.0000000Introduction to Statistical learning
Statistical learning refers to a vast set of tools for understanding data. These tools can be classified as supervised or unsupervised.
Simple Linear Regression
A straightforward approach of predicting a quantitative \(Y\) from a single predictor \(X\), assuming an approximately linear relationship: Mathematically, we can write this linear relationship as
\[ Y \approx \beta_0 + \beta_1 X \]
Estimating the Coefficients
- In the above equation ,\(\beta_0\) and \(\beta_1\) are two unknown constants that represent the intercept and slope terms in the linear model.
- Our goal is to obtain estimates of the coefficients \(\hat{\beta}_0\) and \(\hat{\beta}_1\) such that the linear model fits the data well.
- There are a number of ways of evaluating fit to data, but by far the most common approach is the least squares criterion. We define the residual sum of squares (RSS) as
\[ \text{RSS} = e_1^2 + e_2^2 + \dots + e_n^2 \]
where \(e_i = y_i - \hat{y}\) is the \(i\)th (out of \(n\)) residual. The least squares approach chooses \(\hat{\beta}_0\) and \(\hat{\beta}_1\) to minimize the RSS. Using some calculus, one can show that
\[\begin{align} \hat{\beta}_1 &= \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum (x_i - \bar{x})^2}\\ \hat{\beta}_0 &= \bar{y} - \hat{\beta}_1 \bar{x} \end{align}\]
Illustration
Running a simple linear model
instantiate model
linear_model<- linear_reg() |>
set_engine("lm") |>
set_mode("regression")
linear_model
#> Linear Regression Model Specification (regression)
#>
#> Computational engine: lmfit the model
fit_model<- linear_model |>
fit(sales ~ TV, data = advertising)Extract results
fit_model |>
tidy()| term | estimate | std.error | statistic | p.value |
|---|---|---|---|---|
| (Intercept) | 7.0325935 | 0.4578429 | 15.36028 | 0 |
| TV | 0.0475366 | 0.0026906 | 17.66763 | 0 |
model performance
glance(fit_model)| r.squared | adj.r.squared | sigma | statistic | p.value | df | logLik | AIC | BIC | deviance | df.residual | nobs |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0.6118751 | 0.6099148 | 3.258656 | 312.145 | 0 | 1 | -519.0457 | 1044.091 | 1053.986 | 2102.531 | 198 | 200 |
Separate dependent and independent variables
from sklearn.linear_model import LinearRegression
advertising = pd.read_csv("Advertising.csv")
Xs = advertising[['TV']]
ys = advertising['sales']instantiate model
ols_reg = LinearRegression()fit the model
ols_reg.fit(Xs, ys)LinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
Get results
from sklearn.metrics import root_mean_squared_error
ols_reg.intercept_
#> np.float64(7.032593549127695)
ols_reg.coef_
#> array([0.04753664])
# Compute R-squared
r_squared = ols_reg.score(Xs ,ys)
y_pred = ols_reg.predict(Xs)
# Compute RMSE
rmse = root_mean_squared_error(ys ,y_pred)
# Print the metrics
print("R^2: {}".format(r_squared))
#> R^2: 0.611875050850071
print("RMSE: {}".format(rmse))
#> RMSE: 3.2423221486546887import pandas as pd
import statsmodels.formula.api as smf
# get data
url = "advertising.csv"
advertising = pd.read_csv(url)
# define model
model = smf.ols(formula = 'sales ~ TV', data = advertising)
# fit model
advertising_model = model.fit()
# see results summary
print(advertising_model.summary())
#> OLS Regression Results
#> ==============================================================================
#> Dep. Variable: sales R-squared: 0.612
#> Model: OLS Adj. R-squared: 0.610
#> Method: Least Squares F-statistic: 312.1
#> Date: Mon, 08 Dec 2025 Prob (F-statistic): 1.47e-42
#> Time: 03:11:59 Log-Likelihood: -519.05
#> No. Observations: 200 AIC: 1042.
#> Df Residuals: 198 BIC: 1049.
#> Df Model: 1
#> Covariance Type: nonrobust
#> ==============================================================================
#> coef std err t P>|t| [0.025 0.975]
#> ------------------------------------------------------------------------------
#> Intercept 7.0326 0.458 15.360 0.000 6.130 7.935
#> TV 0.0475 0.003 17.668 0.000 0.042 0.053
#> ==============================================================================
#> Omnibus: 0.531 Durbin-Watson: 1.935
#> Prob(Omnibus): 0.767 Jarque-Bera (JB): 0.669
#> Skew: -0.089 Prob(JB): 0.716
#> Kurtosis: 2.779 Cond. No. 338.
#> ==============================================================================
#>
#> Notes:
#> [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.Strategy
- The same derivation gives simple linear regression fit to the Advertising data , where \(\beta_0\) = 7.03 and \(\beta_1\) = 0.048.
To compute the standard errors associated with \(\hat{\beta}_0\) and \(\hat{\beta}_1\), we use the following formulas:
\[ \begin{align} \text{SE}(\hat{\beta}_0)^2 &= \sigma^2 \left[ \frac{1}{n} + \frac{\bar{x}^2}{\sum (x_i - \bar{x})^2}\right] \\ \text{SE}(\hat{\beta}_1)^2 &= \frac{\sigma^2}{\sum (x_i - \bar{x})^2} \end{align} \]
where \(\sigma^2 = \text{Var}(\epsilon)\).
In general, \(\sigma^2\) is not known, but can be estimated from the data. This estimate of \(\sigma\) is known as the residual standard error, and is given by the formula \(\text{RSE} = \sqrt{\text{RSS}/(n-2)}\).
For linear regression, we get approximate 95% confidence intervals for the coefficients as:
\[ \begin{align} \hat{\beta}_1 \pm 2 \text{SE}(\hat{\beta}_1) \\ \hat{\beta}_0 \pm 2 \text{SE}(\hat{\beta}_0). \end{align} \]
Assessing the Accuracy of the Model
The quality of a linear regression fit is typically assessed using two related quantities: the residual standard error (RSE) and the \(R^2\) statistic.
Residual Standard Error
The residual standard error (RSE) is sigma, variance explained \(R^2\) is r.squared, and the \(F\)-statistic is statistic.
library(gt)
glance(lm_sales_tv) %>%
transmute(`Residual standard error` = round(sigma, 2),
`R2` = round(r.squared, 3), `F-statistic` = round(statistic, 1)) %>%
mutate(across(everything(), as.character)) %>%
pivot_longer(everything(), names_to = "Quantity", values_to = "Value") %>%
gt()| Quantity | Value |
|---|---|
| Residual standard error | 3.26 |
| R2 | 0.612 |
| F-statistic | 312.1 |
\(R^2\) Statistic
The \(R^2\) statistic provides an alternative measure of fit. It always takes on a value between 0 and 1, and is independent of the scale of \(Y\).
\[ R^2 = \frac{\text{TSS} - \text{RSS}}{\text{TSS}} = 1 - \frac{\text{RSS}}{\text{TSS}} \]
where \(\text{TSS} = \sum (y_i - \bar{y})^2\) is the total sum of squares.
Multiple Linear Regression
Simple linear regression is a useful approach for predicting a response on the basis of a single predictor variable. However, in practice we often have more than one predictor.
The model with \(p\) predictors takes the form:
\[ Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \dots + \beta_p X_p + \epsilon. \]
We interpret the slope \(\beta_j\) as the average effect on \(Y\) by a one unit increase in \(X_j\) while holding all other predictors fixed.
Estimating the Regression Coefficients
The parameters are estimated using the same least squares approach as simple linear regression: choose \(\beta_0 \dots \beta_p\) to minimize RSS.
Some Important Questions
(1): Is There a Relationship Between the Response and Predictors?
We begin by testing whether the predictors are related to the response. Formally:
\[ H_0: \beta_1 = \beta_2 = \dots = \beta_p = 0 \quad \text{vs.} \quad H_a: \text{at least one } \beta_j \neq 0 \]
This is assessed using the F-statistic:
\[ F = \frac{(\text{TSS} - \text{RSS})/p}{\text{RSS}/(n - p - 1)} \]
If \(F \approx 1\), there is little evidence against \(H_0\). Large values of \(F\) indicate that the predictors collectively improve model fit and that at least one is associated with the response.
(2): Deciding on Important Variables
The next question is which predictors matter most. This is known as variable selection.
Common criteria include:
- Adjusted \(R^2\)
- Akaike Information Criterion (\(AIC\))
- Bayesian Information Criterion (\(BIC\))
- Mallow’s \(C_p\)
Stepwise procedures (forward, backward, mixed) exist but can be unstable and lead to overfitting. More robust methods include penalized regression (e.g., LASSO, ridge) or cross-validation approaches.
(3): Model Fit
Model fit is typically quantified by:
- Residual Standard Error (RSE) – the average size of the residuals.
- \(R^2\) – proportion of variance in the response explained by the predictors.
In multiple regression:
\[ R^2 = \text{Cor}(Y, \hat{Y})^2 \]
However, \(R^2\) always increases as more variables are added, even if they are uninformative. Thus, adjusted \(R^2\) or information criteria are preferred when comparing models.
(4): Predictions
With a fitted regression model, predictions of the response can be made. The uncertainty in predictions comes from three main sources:
- Sampling variability in the estimated coefficients (\(\hat{\beta}\)).
- Model bias if the assumed linearity does not hold.
- Irreducible error \(\epsilon\).
Prediction intervals are always wider than confidence intervals since they incorporate both reducible and irreducible error.
There are several metrics we can choose from to assess the error of a supervised machine learning model. The most common include:
Regression models
MSE: Mean squared error is the average of the squared eorr (\(MSE = \frac{1}{n}\Sigma_{i=1}^n(y_i-\hat{y})^2\)). The squared component results in larger errors having larger penalties. This (along with RMSE) is the most common error metric to use. Objective: minimize
RMSE: Root Root mean squared error. This simply takes the square root of the MSE metric (RMSE=\(\sqrt{\frac{1}{n}\Sigma_{i=1}^n(y_i-\hat{y})^2}\)) so that your error is in the same units as your response variable. If your response variable units are dollars, the units of MSE are dollars-squared, but the RMSE will be in dollars. Objective: minimize
Deviance: Short for mean residual deviance. In essence, it provides a measure of goodness-of-fit of the model being evaluated when compared to the null model (intercept only). If the response variable distribution is gaussian, then it is equal to MSE. When not, it usually gives a more useful estimate of error. Objective: minimize
MAE: Mean absolute error. Similar to MSE but rather than squaring, it just takes the mean absolute difference between the actual and predicted values (\(MAE=\frac{1}{n}\Sigma_{i=1}^n|(y_i-\hat{y})|\)) Objective: minimize
RMSLE: Root Mean Squared Logarithmic Error. Similar to RMSE, but it applies a
log()transformation to both the actual and predicted values before computing the difference:\[ \text{RMSLE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n} \left[\log(y_i + 1) - \log(\hat{y}_i + 1)\right]^2} \]
RMSLE is useful when the response variable spans a wide range. In such cases, large values with large errors can dominate the RMSE or MSE. RMSLE reduces this effect, allowing errors on smaller values to contribute more meaningfully to the metric.
Objective: minimize.\(R^2\): This is a popular metric that represents the proportion of the variance in the dependent variable that is predictable from the independent variable. Unfortunately, it has several limitations. For example, two models built from two different data sets could have the exact same RMSE but if one has less variability in the response variable then it would have a lower \(R^2\) than the other. You should not place too much emphasis on this metric.
What is machine learning?
- Machine learning is the process whereby:
Computers are given the ability to learn to make decisions from data without being explicitly programmed!
Machine learning is a very iterative process. If performed and interpreted correctly, we can have great confidence in our outcomes. If not, the results will be useless. Approaching machine learning correctly means approaching it strategically by spending our data wisely on learning and validation procedures, properly pre-processing variables, minimizing data leakage, tuning parameters and assessing model performance.
Splitting Dataset into Train-Test Sets
Spending our data wisely
A major goal of the machine learning process is to find an algorithm \(f(x)\) that most accurately predicts future values \((y)\) based on a set of inputs \((x)\). In other words, we want an algorithm that not only fits well to our past data, but more importantly, one that predicts a future outcome accurately. This is called the generalizability of our algorithm. How we “spend??? our data will help us understand how well our algorithm generalizes to unseen data.
To provide an accurate understanding of the generalizability of our final optimal model, we split our data into training and test data sets.
- Training set : these data are used to train our algorithms and tune hyper-parameters.
- Test set : having chosen a final model, these data are used to estimate its prediction error (generalization error). These data should not be used during model training
Given a fixed amount of data, typical recommendations for splitting your data into training-testing splits include 60% (training) - 40% (testing), 70%-30%, or 80%-20%. Generally speaking, these are appropriate guidelines to follow; however, it is good to keep in mind that as your overall data set gets smaller,
- Spending too much in training (\(>80%\)) won’t allow us to get a good assessment of predictive performance. We may find a model that fits the training data very well, but is not generalizable (overfitting),
- sometimes too much spent in testing (\(>40%\)) won’t allow us to get a good assessment of model parameters.
Typically, we are lacking in the size of our data here, so a 70-30 split is often sufficient. The two most common ways of splitting data include simple random sampling and stratified sampling.
Examples of splitting
Simple random sampling
The simplest way to split the data into training and test sets is to take a simple random sample. This does not control for any data attributes, such as the percentage of data in the quantiles in your response variable (\(y\))
set.seed(123)
ames <- AmesHousing::make_ames()
df <- ames
index <- sample(1:nrow(df), round(nrow(df) * 0.7))
train_1 <- df[index, ]
test_1 <- df[-index, ]
# caret package
set.seed(123)
index2 <- createDataPartition(df$Sale_Price, p = 0.7, list = FALSE)
train_2 <- df[index2, ]
test_2 <- df[-index2, ]
## df |> slice(-index)
## df |> slice(index)
# rsample package
set.seed(123)
split_1 <- initial_split(df, prop = 0.7)
train_3 <- training(split_1)
test_3 <- testing(split_1)Stratified sampling
However, if we want to explictly control our sampling so that our training and test sets have similar \(y\) distributions, we can use stratified sampling. This is more common with classification problems where the response variable may be imbalanced (90% of observations with response “Yes” and 10% with response “No”). However, we can also apply to regression problems for data sets that have a small sample size and where the response variable deviates strongly from normality.
With a continuous response variable, stratified sampling will break y down into quantiles and randomly sample from each quantile. Consequently, this will help ensure a balanced representation of the response distribution in both the training and test sets.
url = "diabetes_data.csv"
diabetes_df = read_csv(url)
table(diabetes_df$Diabetes) %>% prop.table()
#>
#> 0 1
#> 0.8333333 0.1666667
# stratified sampling with the rsample package
set.seed(123)
split_strat <- initial_split(diabetes_df, prop=0.7, strata = "Diabetes")
train_strat <- training(split_strat)
test_strat <- testing(split_strat)
# consistent response ratio between train & test
table(train_strat$Diabetes) %>% prop.table()
#>
#> 0 1
#> 0.8352941 0.1647059
table(test_strat$Diabetes) %>% prop.table()
#>
#> 0 1
#> 0.8288288 0.1711712To fit a model using scikit-learn. We split our data into X, a 2D array of our features, and y, a 1D array of the target values . scikit-learn requires that the features are in an array where each column is a feature and each row a different observation. Similarly, the target needs to be a single column with the same number of observations as the feature data. We use the dot-values attribute to convert X and y to NumPy arrays.
- To do this, we import
train_test_splitfromsklearn.model_selection. - We call
train_test_split, passing our features and targets. - We commonly use 20-30% of our data as the test set. By setting the
test_sizeargument to0.3we use 30% here. - The
random_stateargument sets a seed for a random number generator that splits the data. - Using the same number when repeating this step allows us to reproduce the exact split and our downstream results.
X_df = housing_df.drop(columns=["Price"])
y_df = housing_df["Price"].valuesfrom sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test= train_test_split(X_df, y_df, test_size=0.30)
X_train.shape, X_test.shape
#> ((354, 13), (152, 13))
y_train.shape, y_test.shape
#> ((354,), (152,))house_split <- initial_split(housing_df, prop = 0.7)train_df <- training(house_split)
test_df <- testing(house_split)dim(train_df); dim(test_df)
#> [1] 354 14
#> [1] 152 14A simple Model Training workflow
- scikit-learn follows the same syntax for all supervised learning models which makes the workflow repeatable.
- We import a Model, which is a type of algorithm for our supervised learning problem, from an sklearn module. For example, the
k-Nearest Neighborsmodel uses distance between observations to predict labels or values. - We create a variable named model, and instantiate the Model.
- A model is fit to the data, where it learns patterns about the features and the target variable.
- We fit the model to X, an array of our features, and y, an array of our target variable values.
- We then use the model’s dot-predict method, passing new observations, X_new. For example, if feeding features from six emails to a spam classification model, an array of six values is returned.
from sklearn.linear_model import LinearRegressionols_reg = LinearRegression()
ols_regLinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
ols_reg.fit(X_train, y_train)LinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
ols_reg.intercept_
#> np.float64(34.99250702733449)ols_reg.coef_
#> array([-1.01430088e-01, 4.50431060e-02, 2.38769310e-03, 2.14224858e+00,
#> -1.45877046e+01, 3.63483320e+00, 6.72346823e-03, -1.42309773e+00,
#> 3.14222760e-01, -1.27690875e-02, -9.41074785e-01, 1.29128256e-02,
#> -5.71851608e-01])X_train.columns
#> Index(['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX',
#> 'PT', 'B', 'LSTAT'],
#> dtype='object')r_squared = ols_reg.score(X_test ,y_test)
y_pred = ols_reg.predict(X_test)
# Compute RMSE
rmse = root_mean_squared_error(y_test ,y_pred)
# Print the metrics
print("R^2: {}".format(r_squared))
#> R^2: 0.6608541154006513
print("RMSE: {}".format(rmse))
#> RMSE: 4.7910959982408095lm_spec<-linear_reg() %>%
set_mode("regression")%>%
set_engine("lm")model_ft<-lm_spec |>
fit(Price~., data= train_df)
Recipe <- recipe(Price~., data= train_df)wf <- workflow() |>
add_model(lm_spec) |>
add_recipe(Recipe) |>
fit(train_df)tidy(wf)| term | estimate | std.error | statistic | p.value |
|---|---|---|---|---|
| (Intercept) | 25.3624175 | 6.0818517 | 4.1701802 | 0.0000387 |
| CRIM | -0.0248667 | 0.0627425 | -0.3963293 | 0.6921107 |
| ZN | 0.0337958 | 0.0166671 | 2.0276927 | 0.0433712 |
| INDUS | 0.0253077 | 0.0730912 | 0.3462478 | 0.7293706 |
| CHAS | 3.9155307 | 1.0107778 | 3.8737798 | 0.0001285 |
| NOX | -18.4424052 | 5.0955729 | -3.6192997 | 0.0003403 |
| RM | 5.0922799 | 0.5173204 | 9.8435710 | 0.0000000 |
| AGE | -0.0075674 | 0.0161371 | -0.4689460 | 0.6394088 |
| DIS | -1.4066020 | 0.2354524 | -5.9740408 | 0.0000000 |
| RAD | 0.2635908 | 0.0794143 | 3.3191875 | 0.0010006 |
| TAX | -0.0105848 | 0.0043038 | -2.4594293 | 0.0144132 |
| PT | -0.8364101 | 0.1521709 | -5.4965173 | 0.0000001 |
| B | 0.0108694 | 0.0032830 | 3.3108258 | 0.0010300 |
| LSTAT | -0.4881863 | 0.0650052 | -7.5099526 | 0.0000000 |
DataTestWithPredRidge <- augment(wf, test_df)
metrics(DataTestWithPredRidge, truth=Price, estimate=.pred)| .metric | .estimator | .estimate |
|---|---|---|
| rmse | standard | 5.1165234 |
| rsq | standard | 0.6580574 |
| mae | standard | 3.4947404 |
Classifcation
Introduction
In many situations, the response variable is instead qualitative. For example, eye color is qualitative. Often qualitative variables are referred to as categorical; these terms are interchangeably used. The models we learn include logistic regression (and Poisson regression), linear discriminant analysis, quadratic discriminant analysis, naive Bayes, and \(K\)-nearest neighbors.
Prolems where classification is used
A person arrives at the emergency room with a set of symptoms that could possibly be attributed to one of three medical conditions. Which of the three conditions does the individual have?
An online banking service must be able to determine whether or not a transaction being performed on the site is fraudulent, on the basis of the user’s IP address, past transaction history, and so forth.
On the basis of DNA sequence data for a number of patients with and without a given disease, a biologist would like to figure out which DNA mutations are deleterious (disease-causing) and which are not
Overview of classification
Why Not Linear Regression?
- Linear regression cannot predict un-ordered qualitative responses with more than two levels.
- It is possible to use linear regression to predict a binary (two level) response. For example, if we code stroke and drug overdose as dummy variables:
\[ Y = \begin{cases} 0 & \text{if stroke;} \\ 1 & \text{if drug overdose}\\ \end{cases} \]
Then we predict stroke if \(\hat{Y} <= 0.5\) and overdose if \(\hat{Y} > 0.5\). It turns out that these probability estimates are not unreasonble, but there can be issues:
- However, if we use linear regression, some of our estimates might be outside the [0, 1] interval , making them hard to interpret as probabilities! Nevertheless, the predictions provide an ordering and can be interpreted as crude probability estimates.
Illustration
Misclassification: This is the overall error. For example, say you are predicting 3 classes ( high, medium, low ) and each class has 25, 30, 35 observations respectively (90 observations total). If you misclassify 3 observations of class high, 6 of class medium, and 4 of class low, then you misclassified 13 out of 90 observations resulting in a 14% misclassification rate. Objective: minimize
confusion matrix When applying classification models, we often use a confusion matrix to evaluate certain performance measures.A confusion matrix is simply a matrix that compares actual categorical levels (or events) to the predicted categorical levels. When we predict the right level, we refer to this as a true positive. However, if we predict a level or event that did not happen this is called a false positive (i.e. we predicted a customer would redeem a coupon and they did not). Alternatively, when we do not predict a level or event and it does happen that this is called a false negative (i.e. a customer that we did not predict to redeem a coupon does).
We can extract different levels of performance from these measures. For example, given the classification matrix below, we can assess the following:
Accuracy: Overall, how often is the classifier correct? Opposite of misclassification above. Example: \(\frac{TP+TN}{total} = \frac{100+50}{165}=0.91\). Objective: maximize
Precision: How accurately does the classifier predict events? This metric is concerned with maximizing the true positives to false positive ratio. In other words, for the number of predictions that we made, how many were correct? Example: \(\frac{TP}{TP+FP} = \frac{100}{100+10}=0.91\). Objective: maximize
Sensitivity (aka recall): How accurately does the clasifier classify actual events? This metric is concerned with maximizing the true positives to false negative ratio. In other words, for the events that occured, how many did we predict? Example: \(\frac{TP}{TP+FN} = \frac{100}{100+5}=0.95\). Objective: maximize
Specificity: How accurately does the classifier classify actual events? This metric is concerned with maximizing the true positives to false negatives ratio. In other words, for the events that occurred, how many did we predict? Example: \(\frac{TN}{TN+FP} = \frac{50}{50+10}=0.95\). Objective: maximize
k-Nearest Neighbors: Fit
In order to make a prediction for an observation \(X = x\), the training observations that are closest to x are identified. Then X is assigned to the class to which the plurality of these observations belong. Hence KNN is a completely non-parametric approach: no assumptions are made about the shape of the decision boundary.
For a test observation \(x_0\), KNN involves identifying the \(K\) nearest points in the training data that are closest to \(x_0\), represented by \(\mathcal{N}_0\). It then estimates the conditional probability of the classes using the fraction of the points:
\[ \text{Pr}(Y = j|X = x_0) = \frac{1}{K} \sum_{i \in \mathcal{N}_0} I (y_i = j). \]
KNN classifies\(x_0\) into the class \(k\) with the highest probability.
The choices of \(k\) has a drastic effect on the performance of the classifer. \(K = 1\) is the most flexible, i.e. low bias but high variance. A large value of \(K\) (which is relative to the density of points) is the least flexible, i.e. high bias but low variance.
The target, diabetes, needs to be a single column with the same number of observations as the feature data. The feature data has already been converted into numpy arrays.
url = "diabetes_data.csv"
diabetes_df = read_csv(url)
diabetes_df |>
head()| ID | Residence | Age | Height | Sex | Chol | Stab_Glu | HDL | Ratio | Weight | Frame | SBP | DBP | Waist | Hip | Time_PPN | Diabetes |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Urban | 46 | 62 | Female | 203 | 82 | 56 | 3.6 | 121 | Medium | 118 | 59 | 29 | 38 | 720 | 0 |
| 2 | Urban | 29 | 64 | Female | 165 | 97 | 24 | 6.9 | 218 | Large | 112 | 68 | 46 | 48 | 360 | 0 |
| 3 | Urban | 58 | 61 | Female | 228 | 92 | 37 | 6.2 | 256 | Large | 190 | 92 | 49 | 57 | 180 | 0 |
| 4 | Urban | 67 | 67 | Male | 78 | 93 | 12 | 6.5 | 119 | Large | 110 | 50 | 33 | 38 | 480 | 0 |
| 5 | Urban | 64 | 68 | Male | 249 | 90 | 28 | 8.9 | 183 | Medium | 138 | 80 | 44 | 41 | 300 | 1 |
| 6 | Urban | 34 | 71 | Male | 248 | 94 | 69 | 3.6 | 190 | Large | 132 | 86 | 36 | 42 | 195 | 0 |
url = "diabetes_data.csv"
diabetes_df = pd.read_csv(url)
diabetes_df
#> ID Residence Age Height Sex ... DBP Waist Hip Time_PPN Diabetes
#> 0 1 Urban 46 62 Female ... 59 29 38 720 0
#> 1 2 Urban 29 64 Female ... 68 46 48 360 0
#> 2 3 Urban 58 61 Female ... 92 49 57 180 0
#> 3 4 Urban 67 67 Male ... 50 33 38 480 0
#> 4 5 Urban 64 68 Male ... 80 44 41 300 1
#> .. ... ... ... ... ... ... ... ... ... ... ...
#> 361 362 Rural 89 61 Female ... 90 31 41 210 0
#> 362 363 Rural 53 69 Male ... 94 35 39 210 1
#> 363 364 Rural 51 63 Female ... 100 32 43 180 0
#> 364 365 Rural 29 69 Female ... 70 33 40 20 1
#> 365 366 Rural 41 63 Female ... 78 41 48 255 0
#>
#> [366 rows x 17 columns]we will drop categorical columns for now , to use as illustration in feature engineering
X_df2 = diabetes_df.drop(columns=['ID', 'Diabetes','Residence','Sex','Frame'])
X_df2
#> Age Height Chol Stab_Glu HDL ... SBP DBP Waist Hip Time_PPN
#> 0 46 62 203 82 56 ... 118 59 29 38 720
#> 1 29 64 165 97 24 ... 112 68 46 48 360
#> 2 58 61 228 92 37 ... 190 92 49 57 180
#> 3 67 67 78 93 12 ... 110 50 33 38 480
#> 4 64 68 249 90 28 ... 138 80 44 41 300
#> .. ... ... ... ... ... ... ... ... ... ... ...
#> 361 89 61 301 90 118 ... 218 90 31 41 210
#> 362 53 69 296 369 46 ... 138 94 35 39 210
#> 363 51 63 284 89 54 ... 140 100 32 43 180
#> 364 29 69 194 269 38 ... 120 70 33 40 20
#> 365 41 63 199 76 52 ... 120 78 41 48 255
#>
#> [366 rows x 12 columns]y_df2 = diabetes_df['Diabetes']
y_df2
#> 0 0
#> 1 0
#> 2 0
#> 3 0
#> 4 1
#> ..
#> 361 0
#> 362 1
#> 363 0
#> 364 1
#> 365 0
#> Name: Diabetes, Length: 366, dtype: int64df_sub <- diabetes_df |>
select(-c('ID','Residence','Sex','Frame')) |>
mutate(Diabetes = as.factor(Diabetes))Train Split
- It is best practice to ensure our split reflects the proportion of labels in our data. So if Diabetes occurs in 10% of observations, we want 10% of labels in our training and test sets to represent Diabetes. We achieve this by setting stratify equal to y.
train_test_splitreturns four arrays: the training data, the test data, the training labels, and the test labels
url = "diabetes_data.csv"
diabetes_df = pd.read_csv(url)
X_df2 = diabetes_df.drop(columns=['ID', 'Diabetes','Residence','Sex','Frame']).values()
#> TypeError: 'numpy.ndarray' object is not callable
y_df2 = diabetes_df['Diabetes']
from sklearn.model_selection import train_test_split
X_trains, X_tests, y_trains, y_tests = train_test_split(X_df2, y_df2, test_size=0.20, stratify = y_df2)td_split <-initial_split(df_sub, strata = Diabetes, prop=0.8)
train <- training(td_split)
test <- testing(td_split)Instantiate the model
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
knn = KNeighborsClassifier(n_neighbors=6)Fit the classifier to the data
knn.fit(X_trains, y_trains)KNeighborsClassifier(n_neighbors=6)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| n_neighbors | 6 | |
| weights | 'uniform' | |
| algorithm | 'auto' | |
| leaf_size | 30 | |
| p | 2 | |
| metric | 'minkowski' | |
| metric_params | None | |
| n_jobs | None |
print(knn.score(X_tests,y_tests))
#> Error in knn.score(X_tests, y_tests): could not find function "knn.score"- Larger k = less complex model = can cause underfitting
- smaller k = more complex model = can cause overfitting
Instantiate model in tidymodels
knn_spec<-nearest_neighbor(neighbors = 6)%>%
set_mode("classification") %>%
set_engine("kknn")Fit the model to the data
knn_fit<- knn_spec |>
fit(Diabetes ~., data= train)Get the results
knn_direction_test_pred <- knn_fit %>%
augment(new_data = test)
knn_direction_test_pred %>%
accuracy(truth = Diabetes, estimate = .pred_class)| .metric | .estimator | .estimate |
|---|---|---|
| accuracy | binary | 0.8918919 |
Assessing a diabetes prediction classifier
The goal is to predict whether or not each individual is likely to have diabetes based on the features . Therefore, it is a binary classification problem. A target value of 0 indicates that the individual does not have diabetes, while a value of 1 indicates that the individual does have diabetes.
# Import confusion matrix
from sklearn.metrics import classification_report, confusion_matrix
knn = KNeighborsClassifier(n_neighbors=6)
# Fit the model to the training data
knn.fit(X_trains , y_trains)KNeighborsClassifier(n_neighbors=6)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| n_neighbors | 6 | |
| weights | 'uniform' | |
| algorithm | 'auto' | |
| leaf_size | 30 | |
| p | 2 | |
| metric | 'minkowski' | |
| metric_params | None | |
| n_jobs | None |
# Predict the labels of the test data: y_pred
y_pred = knn.predict(X_tests)
# Generate the confusion matrix and classification report
print(confusion_matrix(y_tests, y_pred))
#> [[62 0]
#> [10 2]]
print(classification_report(y_tests, y_pred))
#> precision recall f1-score support
#>
#> 0 0.86 1.00 0.93 62
#> 1 1.00 0.17 0.29 12
#>
#> accuracy 0.86 74
#> macro avg 0.93 0.58 0.61 74
#> weighted avg 0.88 0.86 0.82 74knn_direction_test_pred %>%
conf_mat(truth = Diabetes, estimate = .pred_class)
#> Truth
#> Prediction 0 1
#> 0 60 7
#> 1 1 6Overfitting and underfitting
Interpreting model complexity is a great way to evaluate supervised learning performance. Your aim is to produce a model that can interpret the relationship between features and the target variable, as well as generalize well when exposed to new observations.
# Create neighbors
neighbors = np.arange(1, 13)
train_accuracies = {}
test_accuracies = {}
for neighbor in neighbors:
# Set up a KNN Classifier
knn = KNeighborsClassifier(n_neighbors=neighbor)
# Fit the model
knn.fit(X_trains, y_trains)
# Compute accuracy
train_accuracies[neighbor] = knn.score(X_trains, y_trains)
test_accuracies[neighbor] = knn.score(X_tests, y_tests)KNeighborsClassifier(n_neighbors=np.int64(12))In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| n_neighbors | np.int64(12) | |
| weights | 'uniform' | |
| algorithm | 'auto' | |
| leaf_size | 30 | |
| p | 2 | |
| metric | 'minkowski' | |
| metric_params | None | |
| n_jobs | None |
print(neighbors, '\n', train_accuracies, '\n', test_accuracies)
#> [ 1 2 3 4 5 6 7 8 9 10 11 12]
#> {np.int64(1): 1.0, np.int64(2): 0.928082191780822, np.int64(3): 0.9383561643835616, np.int64(4): 0.9075342465753424, np.int64(5): 0.9212328767123288, np.int64(6): 0.9006849315068494, np.int64(7): 0.9006849315068494, np.int64(8): 0.9041095890410958, np.int64(9): 0.9006849315068494, np.int64(10): 0.9006849315068494, np.int64(11): 0.9006849315068494, np.int64(12): 0.8972602739726028}
#> {np.int64(1): 0.8108108108108109, np.int64(2): 0.8378378378378378, np.int64(3): 0.8243243243243243, np.int64(4): 0.8513513513513513, np.int64(5): 0.8513513513513513, np.int64(6): 0.8648648648648649, np.int64(7): 0.8648648648648649, np.int64(8): 0.8648648648648649, np.int64(9): 0.8648648648648649, np.int64(10): 0.8648648648648649, np.int64(11): 0.8648648648648649, np.int64(12): 0.8648648648648649}Add a title “KNN: Varying Number of Neighbors. Plot the .values() method of train_accuracies on the y-axis against neighbors on the x-axis, with a label of”Training Accuracy”. Plot the .values() method of test_accuracies on the y-axis against neighbors on the x-axis, with a label of “Testing Accuracy”. Display the plot.
import matplotlib.pyplot as plt
# Add a title
# Add a title
plt.title("KNN: Varying Number of Neighbors")
# Plot training accuracies
plt.plot( neighbors,train_accuracies.values(), label="Training Accuracy")
# Plot test accuracies
plt.plot( neighbors,test_accuracies.values(), label="Testing Accuracy")
plt.legend()
plt.xlabel("Number of Neighbors")
plt.ylabel("Accuracy")
# Display the plot
plt.show()Logistic Regression
In logistic regression, we model the probability of \(Y\) belonging to a class, rather than the response \(Y\) itself. The probability of default given balance can be written:
\[ \text{Pr}(\text{default = Yes}|\text{balance}) = p(\text{balance}). \]
One might predict a default for an individual with \(p(\text{balance}) > 0.5\). Or they may alter the threshold to be conservative, e.g. \(p(\text{balance}) > 0.1\)
The Logistic Model
As previously discussed, we could model the probability as linear:
\[ p(X) = \beta_0 + \beta_1 X \]
but this could give probabilities outside of the range 0-1. We must instead model \(p(X)\) using a function that gives outputs 0-1. Many functions meet this description, but logistic regression uses the logistic function:
\[ p(X) = \frac{e^{\beta_0 + \beta_1X}}{1 + e^{\beta_0 + \beta_1 X}}. \]
Estimating the Regression Coefficients
We fit logistic regression models with maximum likelihood, which seeks estimates for \(\beta_0\) and \(\beta_1\) such that the predicted probabilities \(\hat{p}(x_i)\) corresponds as closely as possible to the values \(y_i\). This idea is formalized using a likelihood function:
\[ \ell (\beta_0, \beta_1) = \prod_{i: y_i = 1} p(x_i) \prod_{i': y_{i'} = 0} (1 - p(x_{i'})). \]
We find the estimates \(\hat{\beta}_0\) and \(\hat{\beta}_1\) by maximizing this likelihood function. Note that the least squares approach to linear regression is a special case of maximum likelihood.
Multiple Logistic Regression
The extension to multiple predictors \(p\) is straightfoward:
\[ \log \left( \frac{p(X)}{1 - p(X)} \right) = \beta_0 + \beta_1 X_1 + \dots + \beta_p X_p. \]
Multinomial Logistic Regression
For predicting \(K > 2\) classes, we can extend logistic regression in a method called multinomial logistic regression. To do this, we choose a single class \(K\) to serve as the baseline. Then the probability of another class \(k\) is:
\[ \text{Pr}(Y = k|X = x) = \frac{e^{\beta_{k0} + \beta_{k1} x_1 + \beta_{kp} x_p}}{1 + \sum_{l=1}^{K-1} e^{\beta_{l0} + \beta_{l1} x_1 + \beta_{lp} x_p}} \]
for \(k = 1, \dots, K - 1\). Then for the baseline class \(K\):
\[ \text{Pr}(Y = K|X = x) = \frac{1}{1 + \sum_{l=1}^{K-1} e^{\beta_{l0} + \beta_{l1} x_1 + \beta_{lp} x_p}}. \]
The log-odds of a class \(k\) is then linear in the predictors:
\[ \log \left( \frac{\text{Pr} (Y = k| X = x)}{\text{Pr} (Y = K| X = x)}\right) = \beta_{k0} + \beta_{k1} x_1 + \dots + \beta_{kp} x_p. \]
The softmax coding is equivalent to the coding just described in the sense that the fitted values, log odds between any pair of classes, and other key model outputs will remain the same, regardless of coding. But the softmax coding is used extensively in some areas of the machine learning literature (and will appear again in Chapter 10), so it is worth being aware of it. In the softmax coding, rather than selecting a baseline class, we treat all \(K\) classes symmetrically, and assume that for \(k = 1,...,K\),
\[ \text{Pr}(Y = k|X = x) = \frac{e^{\beta_{k0} + \beta_{k1} x_1 + \beta_{kp} x_p}}{ \sum_{l=1}^{K} e^{\beta_{l0} + \beta_{l1} x_1 + \beta_{lp} x_p}}. \]
Rather than estimating coefficients for \(K − 1\) classes, we actually estimate coefficients for all \(K\) classes. The log odds ratio between the \(k\)th and \(k′\)th classes equals
\[ \frac{\log \text{Pr} (Y = k| X = x)}{\log \text{Pr} (Y = k'| X = x)} = (\beta_{k0} - \beta_{k'0}) + (\beta_{k1} - \beta_{k'1}) x_1 + \dots + (\beta_{kp} - \beta_{k'p}) x_p. \]
A simple approach from a statistical point of view
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
# obtain salespeople data
url = "diabetes_data.csv"
diabetes_data = pd.read_csv(url)
# define model
model = smf.glm(formula = "Diabetes~Age+Height+Chol+Stab_Glu+HDL+Ratio+Weight+SBP+DBP+Waist+Hip+Time_PPN",
data = diabetes_data,
family = sm.families.Binomial())
# fit model
diabetes_data_model = model.fit()
# see results summary
print(diabetes_data_model.summary())diabetes_model<-glm(Diabetes~Age+Height+Chol+Stab_Glu+HDL+Ratio+Weight+SBP+DBP+Waist+Hip+Time_PPN,
family = binomial ,
data = df_sub)
summary(diabetes_model)
#>
#> Call:
#> glm(formula = Diabetes ~ Age + Height + Chol + Stab_Glu + HDL +
#> Ratio + Weight + SBP + DBP + Waist + Hip + Time_PPN, family = binomial,
#> data = df_sub)
#>
#> Coefficients:
#> Estimate Std. Error z value Pr(>|z|)
#> (Intercept) -7.9507762 5.8913827 -1.350 0.177
#> Age 0.0264575 0.0169682 1.559 0.119
#> Height -0.0587432 0.0680871 -0.863 0.388
#> Chol 0.0137409 0.0090560 1.517 0.129
#> Stab_Glu 0.0360470 0.0056026 6.434 1.24e-10 ***
#> HDL -0.0302160 0.0322711 -0.936 0.349
#> Ratio -0.0897711 0.3074298 -0.292 0.770
#> Weight -0.0005899 0.0129717 -0.045 0.964
#> SBP 0.0116767 0.0115665 1.010 0.313
#> DBP 0.0048074 0.0202423 0.237 0.812
#> Waist 0.0619241 0.0786466 0.787 0.431
#> Hip -0.0276283 0.0775378 -0.356 0.722
#> Time_PPN 0.0008173 0.0006547 1.248 0.212
#> ---
#> Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#>
#> (Dispersion parameter for binomial family taken to be 1)
#>
#> Null deviance: 329.81 on 365 degrees of freedom
#> Residual deviance: 164.56 on 353 degrees of freedom
#> AIC: 190.56
#>
#> Number of Fisher Scoring iterations: 6Building a logistic regression model
The model will be used to predict the probability of individuals in the test set having a diabetes diagnosis.
Instantiate the model
# Import LogisticRegression
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()Fit the model
logreg.fit(X_trains , y_trains)LogisticRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| penalty | 'l2' | |
| dual | False | |
| tol | 0.0001 | |
| C | 1.0 | |
| fit_intercept | True | |
| intercept_scaling | 1 | |
| class_weight | None | |
| random_state | None | |
| solver | 'lbfgs' | |
| max_iter | 100 | |
| multi_class | 'deprecated' | |
| verbose | 0 | |
| warm_start | False | |
| n_jobs | None | |
| l1_ratio | None |
Predict probabilities
y_pred_probs = logreg.predict_proba(X_tests)[:, 1]
print(y_pred_probs[:10])
#> [0.15181717 0.03146513 0.45635634 0.01503335 0.99757483 0.06744415
#> 0.01029615 0.03532296 0.01997421 0.99442928]Instantiate the model
glm_direction_fit <-
logistic_reg(mode = "classification") |>
set_engine("glm")Fit the model
glm_fit<- glm_direction_fit |>
fit(Diabetes ~., data= train)View coeficients
tidy(glm_fit)| term | estimate | std.error | statistic | p.value |
|---|---|---|---|---|
| (Intercept) | -8.3631887 | 6.3036971 | -1.3267117 | 0.1846041 |
| Age | 0.0366299 | 0.0205306 | 1.7841650 | 0.0743969 |
| Height | -0.0614719 | 0.0730168 | -0.8418864 | 0.3998515 |
| Chol | 0.0222500 | 0.0103530 | 2.1491289 | 0.0316242 |
| Stab_Glu | 0.0328716 | 0.0059407 | 5.5332926 | 0.0000000 |
| HDL | -0.0613408 | 0.0386991 | -1.5850685 | 0.1129508 |
| Ratio | -0.2037039 | 0.3362527 | -0.6058059 | 0.5446437 |
| Weight | -0.0056014 | 0.0148806 | -0.3764250 | 0.7066009 |
| SBP | 0.0207464 | 0.0140806 | 1.4734039 | 0.1406422 |
| DBP | -0.0058297 | 0.0224675 | -0.2594726 | 0.7952706 |
| Waist | 0.0614430 | 0.0936534 | 0.6560688 | 0.5117799 |
| Hip | -0.0024371 | 0.0869086 | -0.0280423 | 0.9776284 |
| Time_PPN | 0.0005883 | 0.0008063 | 0.7296096 | 0.4656289 |
Get results
knn_direction_test_pred <- glm_fit %>%
augment(new_data = test)
knn_direction_test_pred %>%
accuracy(truth = Diabetes, estimate = .pred_class)| .metric | .estimator | .estimate |
|---|---|---|
| accuracy | binary | 0.8783784 |
Now you have built a logistic regression model for predicting diabetes status, you can plot the ROC curve to visualize how the true positive rate and false positive rate vary as the decision threshold changes.
The test labels, y_test, and the predicted probabilities of the test features belonging to the positive class, y_pred_probs, have been preloaded for you, along with matplotlib.pyplot as plt.
You will create a ROC curve and then interpret the results.
import matplotlib.pyplot as plt
plt.close('all')
# Import roc_curve
from sklearn.metrics import roc_curve
# Generate ROC curve values: fpr, tpr, thresholds
fpr, tpr, thresholds = roc_curve(y_tests, y_pred_probs)
plt.plot([0, 1], [0, 1], 'k--')
# Plot tpr against fpr
plt.plot(fpr, tpr)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve for Diabetes Prediction')
plt.show()glm_direction_fit <-
logistic_reg(mode = "classification") |>
set_engine("glm")
glm_fit<- glm_direction_fit |>
fit(Diabetes ~., data= train)
knn_direction_test_pred <- glm_fit %>%
augment(new_data = test)
knn_direction_test_pred %>%
accuracy(truth = Diabetes, estimate = .pred_class)| .metric | .estimator | .estimate |
|---|---|---|
| accuracy | binary | 0.8783784 |
results <-test|>
select(Diabetes)|>
bind_cols(glm_fit|>
predict(new_data = test))|>
bind_cols(glm_fit|>
predict(new_data =test, type = "prob"))results|>
conf_mat(truth = Diabetes, estimate = .pred_class)
#> Truth
#> Prediction 0 1
#> 0 57 5
#> 1 4 8update_geom_defaults(geom = "rect", new = list(fill = "midnightblue", alpha = 0.7))
results|>
conf_mat(truth = Diabetes, estimate = .pred_class)|>
autoplot()Now you will compute the area under the ROC curve, along with the other classification metrics you have used previously.
# Import roc_auc_score
from sklearn.metrics import roc_auc_score
# Calculate roc_auc_score
print(roc_auc_score(y_tests, y_pred_probs))
#> 0.8266129032258065
# Calculate the confusion matrix
print(confusion_matrix(y_tests, y_pred))
#> [[62 0]
#> [10 2]]
# Calculate the classification report
print(classification_report(y_tests, y_pred))
#> precision recall f1-score support
#>
#> 0 0.86 1.00 0.93 62
#> 1 1.00 0.17 0.29 12
#>
#> accuracy 0.86 74
#> macro avg 0.93 0.58 0.61 74
#> weighted avg 0.88 0.86 0.82 74# Evaluate ROC_AUC metrics
results|>
roc_auc(Diabetes, .pred_0)| .metric | .estimator | .estimate |
|---|---|---|
| roc_auc | binary | 0.8713745 |
Model Performance
Multiple Regression
X_df3 = diabetes_df.drop(columns=['ID', 'Diabetes','Residence','Sex','Frame'], axis =1).values
X_df3
#> array([[ 46., 62., 203., ..., 29., 38., 720.],
#> [ 29., 64., 165., ..., 46., 48., 360.],
#> [ 58., 61., 228., ..., 49., 57., 180.],
#> ...,
#> [ 51., 63., 284., ..., 32., 43., 180.],
#> [ 29., 69., 194., ..., 33., 40., 20.],
#> [ 41., 63., 199., ..., 41., 48., 255.]], shape=(366, 12))
y_df3 = diabetes_df['SBP'].values
y_df3
#> array([118, 112, 190, 110, 138, 132, 161, 160, 108, 130, 102, 130, 100,
#> 130, 130, 100, 110, 178, 148, 137, 136, 158, 100, 144, 140, 125,
#> 180, 146, 130, 170, 176, 120, 140, 115, 124, 158, 105, 142, 149,
#> 130, 110, 140, 110, 106, 150, 104, 158, 124, 126, 165, 141, 160,
#> 130, 159, 130, 158, 120, 120, 150, 160, 138, 126, 108, 142, 140,
#> 156, 130, 178, 120, 174, 145, 138, 120, 136, 147, 119, 120, 125,
#> 121, 138, 151, 103, 119, 110, 125, 112, 142, 160, 160, 111, 136,
#> 136, 136, 115, 130, 110, 150, 158, 138, 160, 118, 131, 159, 150,
#> 150, 150, 138, 160, 124, 112, 110, 110, 170, 130, 180, 122, 130,
#> 132, 141, 111, 140, 136, 150, 162, 110, 145, 104, 146, 130, 125,
#> 125, 140, 126, 108, 140, 135, 139, 120, 151, 150, 110, 138, 140,
#> 110, 146, 150, 140, 98, 161, 125, 138, 230, 122, 142, 136, 138,
#> 132, 148, 140, 118, 186, 140, 200, 110, 118, 146, 136, 140, 142,
#> 136, 180, 110, 140, 142, 104, 138, 142, 118, 190, 118, 180, 140,
#> 160, 142, 170, 199, 131, 190, 110, 190, 135, 120, 178, 122, 110,
#> 125, 130, 180, 130, 102, 130, 152, 118, 160, 150, 165, 142, 132,
#> 184, 176, 150, 170, 130, 122, 116, 158, 122, 140, 123, 118, 131,
#> 108, 136, 121, 162, 100, 108, 150, 120, 100, 105, 125, 175, 140,
#> 118, 150, 150, 142, 106, 130, 140, 140, 108, 130, 150, 138, 130,
#> 118, 120, 125, 136, 140, 142, 130, 150, 131, 126, 148, 140, 106,
#> 132, 110, 220, 180, 100, 212, 134, 162, 122, 138, 112, 128, 148,
#> 130, 110, 122, 136, 172, 138, 122, 120, 110, 138, 138, 250, 138,
#> 116, 150, 138, 110, 130, 148, 135, 140, 110, 145, 142, 118, 140,
#> 140, 130, 128, 136, 128, 110, 152, 90, 122, 140, 126, 130, 135,
#> 122, 135, 162, 140, 172, 138, 142, 130, 140, 178, 162, 134, 124,
#> 142, 120, 140, 124, 130, 100, 144, 110, 156, 148, 160, 110, 122,
#> 140, 140, 140, 125, 170, 144, 124, 170, 110, 142, 140, 130, 120,
#> 128, 140, 174, 118, 146, 144, 130, 110, 140, 190, 218, 138, 140,
#> 120, 120])
print(X_df3.shape,y_df3.shape)
#> (366, 12) (366,)
X_df3 = X_df3
print(X_df3.shape,y_df3.shape)
#> (366, 12) (366,)
ols_regLinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
X_train1, X_test1, y_train1, y_test1 = train_test_split(X_df3, y_df3, test_size=0.3, random_state=42)
from sklearn.linear_model import LinearRegression
ols_reg = LinearRegression()
ols_reg.fit(X_train1,y_train1)LinearRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| fit_intercept | True | |
| copy_X | True | |
| tol | 1e-06 | |
| n_jobs | None | |
| positive | False |
y_pred = ols_reg.predict(X_test1)
print("Predictions: {}, Actual Values: {}".format(y_pred[:2], y_test1[:2]))
#> Predictions: [122. 115.], Actual Values: [122 115]Training Performance: In-Sample Error
\[\text{MSE}({\bf \hat{w}})=\frac{1}{n}\sum_{i=1}^n(y_i-\hat{y})^2\]
y_train_pred = ols_reg.predict(X_train1)
y_train_pred
#> array([122., 125., 148., 137., 98., 138., 175., 148., 120., 150., 138.,
#> 141., 120., 105., 138., 140., 134., 130., 142., 140., 142., 160.,
#> 110., 150., 161., 138., 150., 102., 142., 150., 103., 180., 184.,
#> 160., 100., 118., 140., 102., 136., 174., 138., 150., 110., 138.,
#> 158., 140., 120., 144., 142., 146., 150., 178., 110., 150., 148.,
#> 170., 145., 140., 122., 142., 130., 199., 126., 138., 172., 118.,
#> 120., 123., 140., 125., 149., 130., 130., 110., 170., 118., 106.,
#> 150., 132., 122., 140., 162., 144., 118., 118., 136., 136., 180.,
#> 140., 190., 122., 150., 125., 138., 140., 110., 150., 140., 146.,
#> 147., 142., 170., 110., 128., 160., 110., 121., 108., 170., 134.,
#> 150., 110., 156., 148., 112., 131., 145., 118., 100., 158., 130.,
#> 180., 140., 140., 138., 120., 108., 140., 142., 160., 110., 110.,
#> 130., 190., 150., 162., 140., 111., 250., 142., 139., 180., 110.,
#> 138., 130., 110., 138., 126., 140., 118., 108., 170., 122., 110.,
#> 138., 158., 126., 124., 140., 162., 130., 142., 146., 116., 105.,
#> 132., 200., 135., 151., 108., 135., 130., 108., 140., 130., 132.,
#> 110., 160., 118., 122., 122., 172., 150., 132., 130., 145., 156.,
#> 140., 144., 148., 138., 152., 140., 106., 140., 135., 106., 150.,
#> 159., 112., 165., 151., 165., 124., 180., 136., 130., 100., 140.,
#> 130., 140., 160., 130., 136., 140., 140., 90., 128., 130., 130.,
#> 130., 141., 104., 190., 140., 190., 136., 150., 126., 150., 142.,
#> 158., 135., 186., 136., 120., 140., 144., 148., 140., 125., 125.,
#> 230., 160., 160., 100., 116., 136., 120., 136., 110., 138., 138.,
#> 112., 140., 159.])train_errors = y_train_pred - y_train1
train_errors
#> array([ 0.00000000e+00, -7.10542736e-14, 5.68434189e-14, 2.27373675e-13,
#> -1.70530257e-13, -1.98951966e-13, 3.12638804e-13, -1.70530257e-13,
#> -1.70530257e-13, 1.70530257e-13, -2.84217094e-14, 2.55795385e-13,
#> -1.84741111e-13, -2.98427949e-13, 1.13686838e-13, -2.84217094e-14,
#> 1.13686838e-13, 5.68434189e-14, 1.70530257e-13, 0.00000000e+00,
#> 2.84217094e-14, -3.97903932e-13, -1.27897692e-13, 1.13686838e-13,
#> -2.84217094e-14, -8.52651283e-14, 5.68434189e-14, 0.00000000e+00,
#> 2.84217094e-14, 1.13686838e-13, -2.13162821e-13, 1.98951966e-13,
#> 1.98951966e-13, -5.68434189e-14, 5.68434189e-14, -2.55795385e-13,
#> 1.70530257e-13, -2.70006240e-13, -2.84217094e-14, 1.98951966e-13,
#> 2.84217094e-14, 0.00000000e+00, 7.10542736e-14, -3.97903932e-13,
#> 3.97903932e-13, 1.13686838e-13, 1.56319402e-13, -1.70530257e-13,
#> 2.84217094e-14, 1.70530257e-13, -1.13686838e-13, -1.42108547e-13,
#> 1.13686838e-13, 8.52651283e-14, -1.13686838e-13, 5.68434189e-14,
#> -5.68434189e-14, -3.12638804e-13, -2.84217094e-14, 8.52651283e-14,
#> 1.42108547e-13, 1.13686838e-13, 7.10542736e-14, -7.10542736e-13,
#> -2.84217094e-14, -5.68434189e-14, 3.12638804e-13, -7.10542736e-14,
#> 8.52651283e-14, -1.98951966e-13, 1.98951966e-13, 2.84217094e-14,
#> -1.42108547e-13, -5.68434189e-14, 1.13686838e-13, -1.13686838e-13,
#> -1.84741111e-13, 0.00000000e+00, 0.00000000e+00, -5.68434189e-14,
#> 2.84217094e-14, 1.98951966e-13, -2.27373675e-13, -8.52651283e-14,
#> -1.84741111e-13, 1.70530257e-13, 0.00000000e+00, 8.52651283e-14,
#> -8.52651283e-14, 3.12638804e-13, 1.13686838e-13, 1.70530257e-13,
#> -2.70006240e-13, 0.00000000e+00, -1.98951966e-13, 2.41584530e-13,
#> -5.68434189e-14, 5.68434189e-14, 5.68434189e-14, -8.52651283e-14,
#> -2.55795385e-13, -2.27373675e-13, 1.27897692e-13, -2.84217094e-14,
#> 0.00000000e+00, -4.26325641e-14, -2.84217094e-14, -2.84217094e-13,
#> -2.84217094e-14, 1.98951966e-13, 2.84217094e-14, -1.42108547e-14,
#> -2.27373675e-13, -1.70530257e-13, -2.13162821e-13, -5.68434189e-14,
#> 1.70530257e-13, 1.42108547e-14, 0.00000000e+00, -2.84217094e-13,
#> -1.98951966e-13, 2.84217094e-14, 1.42108547e-13, -2.84217094e-14,
#> 0.00000000e+00, 1.42108547e-14, 0.00000000e+00, 2.55795385e-13,
#> 1.13686838e-13, 2.84217094e-14, -2.41584530e-13, 2.98427949e-13,
#> -1.13686838e-13, 1.70530257e-13, 0.00000000e+00, 1.42108547e-13,
#> -3.41060513e-13, -1.13686838e-13, 2.84217094e-13, 2.27373675e-13,
#> -8.52651283e-14, 1.42108547e-13, -5.68434189e-14, -1.42108547e-13,
#> -1.13686838e-13, -9.94759830e-14, 1.42108547e-13, -1.27897692e-13,
#> 8.52651283e-14, -9.94759830e-14, -1.98951966e-13, 2.84217094e-14,
#> -4.26325641e-14, -7.10542736e-14, 0.00000000e+00, 2.84217094e-13,
#> 0.00000000e+00, 8.52651283e-14, -8.52651283e-14, 2.84217094e-13,
#> 2.55795385e-13, -1.98951966e-13, -1.13686838e-13, 1.13686838e-13,
#> -3.12638804e-13, -1.13686838e-13, 2.27373675e-13, 1.13686838e-13,
#> -2.27373675e-13, -5.68434189e-14, -1.13686838e-13, -2.55795385e-13,
#> 2.13162821e-13, 8.52651283e-14, 2.27373675e-13, -1.13686838e-13,
#> 3.12638804e-13, -1.98951966e-13, 8.52651283e-14, 1.42108547e-13,
#> -1.56319402e-13, 1.42108547e-13, -1.13686838e-13, -2.84217094e-14,
#> 0.00000000e+00, 0.00000000e+00, -2.84217094e-14, -2.27373675e-13,
#> -1.42108547e-13, 0.00000000e+00, 5.68434189e-14, 1.70530257e-13,
#> -8.52651283e-14, -1.84741111e-13, 1.98951966e-13, -2.55795385e-13,
#> 1.42108547e-14, -2.84217094e-14, -2.84217094e-14, -7.10542736e-14,
#> 1.98951966e-13, -2.55795385e-13, -2.55795385e-13, -5.68434189e-14,
#> 1.70530257e-13, 2.84217094e-14, -1.13686838e-13, 1.42108547e-14,
#> 1.13686838e-13, 0.00000000e+00, 3.41060513e-13, -3.69482223e-13,
#> 8.52651283e-14, 1.13686838e-13, -8.52651283e-14, -8.52651283e-14,
#> -1.13686838e-13, 3.97903932e-13, 2.55795385e-13, -1.13686838e-13,
#> -1.42108547e-13, -8.52651283e-14, 1.42108547e-14, -1.70530257e-13,
#> 2.27373675e-13, 1.13686838e-13, -2.84217094e-14, -3.12638804e-13,
#> 1.70530257e-13, 1.42108547e-13, 5.68434189e-14, 2.84217094e-13,
#> 1.42108547e-13, 1.13686838e-13, -5.68434189e-14, -5.68434189e-14,
#> 1.98951966e-13, 1.42108547e-13, -8.52651283e-14, 2.84217094e-14,
#> 7.10542736e-14, -5.68434189e-14, 1.98951966e-13, 2.84217094e-13,
#> 0.00000000e+00, -9.94759830e-14, -9.94759830e-14, -2.27373675e-13,
#> 7.10542736e-14, -2.27373675e-13, 5.68434189e-14, 2.84217094e-13,
#> -1.42108547e-13, -1.56319402e-13, 1.13686838e-13, -2.84217094e-14])training_mse = sum(train_errors**2)/ len(train_errors)
training_mse
#> np.float64(2.7994306943578046e-26)from sklearn.metrics import mean_squared_error
train_mse = mean_squared_error(y_train1, y_train_pred)
train_mse
#> 2.7994306943578046e-26The default performance metric in
scikit-learnis \(R^2\) ( normalized version of the MSE).\[R^2=1-\frac{\sum_{i=1}^n(y_i-\hat{y})^2}{\sum_{i=1}^n(y_i-\bar{y})^2}\]
It does not depend on the scale of the data, and it is easily interpretable.
train_r2 = ols_reg.score(X_train1, y_train1)
train_r2
#> 1.0# Import root_mean_squared_error
# Import root_mean_squared_error
from sklearn.metrics import root_mean_squared_error
# Compute R-squared
r_squared = ols_reg.score(X_test1 ,y_test1)
# Compute RMSE
rmse = root_mean_squared_error(y_test1 ,y_pred)
# Print the metrics
print("R^2: {}".format(r_squared))
#> R^2: 1.0
print("RMSE: {}".format(rmse))
#> RMSE: 1.9080781755778386e-13Resampling Techniques
Generally, resampling techniques for estimating model performance operate similarly: a subset of samples are used to fit a model and the remaining samples are used to estimate the efficacy of the model. This process is repeated multiple times and the results are aggregated and summarized. The differences in techniques usually center around the method in which subsamples are chosen.
Model Validation: Cross-Validation
\(k\)-fold cross validation may be indicative of how the model will perform on truly unseen data.
Split the data on, say, \(k=5\) or \(k=10\) different Folds.
Compare the mean performance score with the full training set performance.
If the CV Score < full training set model:
Model fitted on the training set has better performance.
It suggests overfitting.
If CV Score > model fitted on full training set:
The model is underfitting.
It has not captured the underlying patterns in the data.
Thus, it has worse performance on the full training set.
If CV Score \(\approx\) model fitted on full training set:
The model is neither overfitting nor underfitting.
The model generalizes well.
For KNN model
from sklearn.model_selection import cross_val_score ,KFold
kf = KFold(n_splits = 6, shuffle =True , random_state=42)ols_reg = LinearRegression()
cv_results = cross_val_score(ols_reg, X_df, y_df, cv=kf)
cv_results
#> array([0.80408556, 0.63198615, 0.64633168, 0.77853465, 0.76442011,
#> 0.68489916])cv_r2 = np.mean(cv_results)
cv_r2
#> np.float64(0.7183762201152595)# Print the mean
print(np.mean(cv_results))
#> 0.7183762201152595
# Print the standard deviation
print( np.std(cv_results))
#> 0.06690732574802465
# Print the 95% confidence interval
print(np.quantile(cv_results, [0.025, 0.975]))
#> [0.63377934 0.8008917 ]Regularized regression
linear regression is a simple and fundamental approach for supervised learning. Moreover, when the assumption required by OLS are met, the coefficients produced by OLS are unbiased and, of all unbiased linear techniques, have the lowest variance. However, in today’s world, data sets being analyzed typically have a large amount of features. As the number of features grow, our OLS assumptions typically break down and our models often overfit (aka have high variance) to the training sample, causing our out of sample error to increase. Regularization methods provide a means to control our regression coefficients, which can reduce the variance and decrease our out of sample error.
Why regularize
The objective of ordinary least squares regression is to find the plane that minimizes the sum of squared errors (SSE) between the observed and predicted response.More formally, this objective function is written as: \[ minimize [{SSE = \Sigma_{i=1}^n (y_i-\hat{y_i})^2}] \]
The OLS objective function performs quite well when our data align to the key assumptions of OLS regression:
- Linear relationship
- Multivariate normality
- No autocorrelation
- Homoscedastic (constant variance in residuals)
- There are more observations (n) than features
However, for many real-life data sets we have very wide data, meaning we have a large number of features (p) that we believe are informative in predicting some outcome. As p increases, we can quickly violate some of the OLS assumptions and we require alternative approaches to provide predictive analytic solutions. Specifically, as p increases there are three main issues we most commonly run into:
1. Multicollinearty
As p increases we are more likely to capture multiple features that have some multicollinearity. When multicollinearity exists, we often see high variability in our coefficient terms. Coefficients for correlated features become over-inflated and can fluctuate significantly. One consequence of these large fluctuations in the coefficient terms is overfitting, which means we have high variance in the bias-variance tradeoff space. Although an analyst can use tools such as variance inflaction factors (Myers, 1994) to identify and remove those strongly correlated variables, it is not always clear which variable(s) to remove. Nor do we always wish to remove variables as this may be removing signal in our data.
2. Insufficient solution
When the number of features exceed the number of observations (\(p>n\)), the OLS solution matrix is not invertible. This causes significant issues because it means: (1) The least-squares estimates are not unique. In fact, there are an infinite set of solutions available and most of these solutions overfit the data. (2) In many instances the result will be computationally infeasible.
Consequently, to resolve this issue an analyst can remove variables until \(p < n\) and then fit an OLS regression model. Although an analyst can use pre-processing tools to guide this manual approach (Kuhn & Johnson, 2013, pp. 43-47), it can be cumbersome and prone to errors.
3. Interpretability
With a large number of features, we often would like to identify a smaller subset of these features that exhibit the strongest effects. In essence, we sometimes prefer techniques that provide feature selection. One approach to this is called hard threshholding feature selection, which can be performed with linear model selection approaches. However, model selection approaches can be computationally inefficient, do not scale well, and they simply assume a feature as in or out. We may wish to use a soft threshholding approach that slowly pushes a feature’s effect towards zero. As will be demonstrated, this can provide additional understanding regarding predictive signals.
Regulaized regression
When we experience these concerns, one alternative to OLS regression is to use regularized regression (also commonly referred to as penalized models or shrinkage methods) to control the parameter estimates. Regularized regression puts contraints on the magnitude of the coefficients and will progressively shrink them towards zero. This constraint helps to reduce the magnitude and fluctuations of the coefficients and will reduce the variance of our model.
The objective function of regulaized regression model is very similar to OLS regression; however, we add a penalty paramter (P)
\[ minimize(SSE + P) \]
There are two main penalty parameters, which we will see shortly, but they both have a similarr effect. They constrain the size of the coefficients such that the only way the coefficients can increase is if we experience a comparable decrease in the sum of squared errors (SSE). Next, we’ll explore the most common approaches to incorporate regularization.
Shrinkage Methods
A technique that contrains or regularizes or shrinks the coefficient estimates towards zero in a model fit with all \(p\) predictors. It turns out that shrinking the coefficient estimates can significantly reduce the variance.
Recall that the least squares fitting procedure involves estimating \(\beta_0, \beta_1, \dots, \beta_p\) by minimizing the RSS:
\[ \text{RSS} = \sum_{i=1}^n \left(y_i - \hat{y}_i \right)^2 = \sum_{i=1}^n \left(y_i - \beta_0 - \sum_{j=1}^p \beta_j x_{ij} \right)^2. \]
I. Ridge Regression
Ridge regression (Hoerl, 1970) controls the coefficients by adding \(\lambda \Sigma_{j=1}^p \beta_j^2\) to the objective function. This penalty parameter is also referred to as \(L_2\)” as it signifies a second-order penalty being used on the coefficients.
\[minimize (\sum_{i=1}^n \left(y_i - \beta_0 - \sum_{j=1}^p \beta_j x_{ij} \right)^2 + \lambda \sum_{j=1}^p \beta_j^2 = \text{RSS} + \lambda \sum_{j=1}^p \beta_j^2,)\]
where \(\lambda \geq 0\) is a tuning parameter, to be determined separately. The second term above, called a shrinkage penalty is small when the coefficients are close to zero, and so has the effect of shrinking the estimates \(\beta_j\) towards zero. The tuning parameter \(\lambda\) serves to control the relative impact of these two terms on the regression coefficient estimates. When \(\lambda = 0\), the penalty term has no effect, and ridge regression will produce the same least squares estimates. Unlike least squares, which generates only one set of coefficient estimates (the “best fit”), ridge regression will produce a different set of coefficient estimates \(\hat{\beta}_{\lambda}^R\) for each value \(\lambda\). Selecting a good value for \(\lambda\) is critical. Note that the shrinkage penalty is not applied to the intercept \(\beta_0\), which is simply a measure of the mean value of the response when all predictors are zero (\(x_{i1} = x_{i2} = \dots = 0\))
OLS estimated parameters are BLUE (Best Linear Unbiased Estimators).
Best: Minimum Variance
Unbiased: E(Estimates) = Parameters
Possible to produce models with smaller MSEs by allowing the estimates to be biased.
\[MSE(\hat{\bf w})=\underset{\hat{\bf w} - \bar{\hat{\bf w}}}{\underbrace{Var(\hat{\bf w})}}+\underset{\hat{\bf w} - {\bf w}}{\underbrace{Bias(\hat{\bf w})}}\] - Ridge regression is a biased model that adds a penalty (i.e. \(L_2\) norm of \({\bf w}\) - the sum of square values) to the SSE.
\[\min_{{\bf w} \in {\cal R}^{p+1}} [\text{SSE}(\hat{\bf w})+\text{penalty}]=\min_{{\bf w} \in {\cal R}^{p+1}}\left[\sum_{i=1}^n(y_i-\hat{y})^2+\alpha\sum_{j=1}^pw_j^2\right]= \min_{{\bf w} \in {\cal R}^{p+1}} \left[\sum_{i=1}^n \left\|y_i-{\bf w}^T {\bf x}_i \right\|^2 + \alpha \left\| {\bf w} \right\|^2_2\right] \]
The ridge effect \(\alpha\) is a regularization hyper-parameter and its optimal value should be found.
Implication:
The little bias might help generalization (decrease the test error) even though training performance decreases.
Larger values of the parameter estimates are penalized more than smaller values.
Shrinks the estimates towards 0 as the \(\alpha\) penalty becomes large (called shrinkage methods).
Used when there is multicollinearity.
Note: IN ALL OF THE REGULARIZATION METHODS, THE PENALTIES DOES NOT INCLUDE THE BIAS TERM \(w_0\).
This penalty parameter can take on a wide range of values, which is controlled by the tuning parameter \(\lambda\). When \(lambda>0\) there is no effect and our objective function equals the normal PLS regression objective function of simply minimizing SSE.
However, as \(\lambda -> \infty\), the penalty becomes large and forces our coefficients to zero. This is illustrated in Figure 2 where exemplar coefficients have been regularized with $ranging from 0 to over 8,000 (log(8103)=9).
Ridge regression performs regularization by computing the squared values of the model parameters multiplied by alpha and adding them to the loss function.
from sklearn.linear_model import Ridgeridge_reg = Ridge()
ridge_regRidge()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
ridge_reg.fit(X_train, y_train)Ridge()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
ridge_regRidge()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
ridge_reg.intercept_
#> np.float64(30.169391119163546)ridge_reg.coef_
#> array([-9.99837790e-02, 4.59112005e-02, -2.56034422e-02, 2.01346109e+00,
#> -7.67562710e+00, 3.68397500e+00, 1.05152766e-03, -1.31675886e+00,
#> 3.01387090e-01, -1.34012055e-02, -8.66645246e-01, 1.31748345e-02,
#> -5.81098179e-01])ridge_test_r2 = ridge_reg.score(X_test, y_test)
ridge_test_r2
#> 0.652030993062622# Import Ridge
from sklearn.linear_model import Ridge
alphas = [0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0]
ridge_scores = []
for alpha in alphas:
# Create a Ridge regression model
ridge = Ridge(alpha = alpha)
# Fit the data
ridge.fit(X_train , y_train)
# Obtain R-squared
score = ridge.score(X_test, y_test)
ridge_scores.append(score)Ridge(alpha=10000.0)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 10000.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
print(ridge_scores)
#> [0.6596424637058627, 0.652030993062622, 0.637153132923751, 0.6082668485667664, 0.5467449074772439, 0.42961472208669826]Standardization and Normalization
If the covariates are not in a consistent scale, the penality may not be fair.
This is because of the sum of squares of the coefficients.
There is a need to center and scale the predictors.
from sklearn.preprocessing import StandardScaler, MinMaxScalertransformer = MinMaxScaler()
transformerMinMaxScaler()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| feature_range | (0, ...) | |
| copy | True | |
| clip | False |
X_train = transformer.fit_transform(X_train)
X_train
#> array([[8.80410371e-02, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 1.00000000e+00, 3.17052977e-01],
#> [1.36817095e-02, 0.00000000e+00, 6.92423674e-01, ...,
#> 2.23404204e-01, 9.15132609e-01, 7.89183234e-02],
#> [9.70440846e-04, 3.40000000e-01, 1.83942713e-01, ...,
#> 3.72340441e-01, 9.66301515e-01, 1.91501099e-01],
#> ...,
#> [1.06238208e-03, 0.00000000e+00, 3.31699973e-01, ...,
#> 5.53191390e-01, 9.96678337e-01, 2.32615882e-01],
#> [1.82344870e-02, 0.00000000e+00, 7.79494895e-01, ...,
#> 9.14893694e-01, 1.00000000e+00, 9.01765970e-01],
#> [5.13252377e-03, 0.00000000e+00, 1.88088949e-01, ...,
#> 5.10638238e-01, 9.47360465e-01, 9.71302391e-02]], shape=(354, 13))X_test = transformer.transform(X_test)
X_test
#> array([[ 2.00746365e-01, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 9.91987414e-01, 5.53256071e-01],
#> [ 3.22013260e-01, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 5.28551155e-01, 5.06346559e-01],
#> [ 1.53667513e-01, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 1.68441599e-01, 8.91004398e-01],
#> ...,
#> [ 1.59941776e-04, 8.50000000e-01, -1.77157947e-02, ...,
#> 4.99999899e-01, 1.00000000e+00, 1.11479024e-01],
#> [ 1.62211984e-01, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 4.48400029e-01, 4.98068435e-01],
#> [ 6.59293915e-02, 0.00000000e+00, 6.36637788e-01, ...,
#> 8.08510711e-01, 1.00000000e+00, 4.86754973e-01]],
#> shape=(152, 13))ridge_reg_scaled = Ridge()
ridge_reg_scaled.fit(X_train, y_train)Ridge()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
ridge_train_r2 = ridge_reg_scaled.score(X_train, y_train)
ridge_train_r2
#> 0.7554960209707067ridge_test_r2 = ridge_reg_scaled.score(X_test, y_test)
ridge_test_r2
#> 0.6573657484247004ridge_train_r2 - ridge_test_r2
#> 0.09813027254600626import matplotlib.pyplot as pltnp.logspace(-3, 4, 100)
#> array([1.00000000e-03, 1.17681195e-03, 1.38488637e-03, 1.62975083e-03,
#> 1.91791026e-03, 2.25701972e-03, 2.65608778e-03, 3.12571585e-03,
#> 3.67837977e-03, 4.32876128e-03, 5.09413801e-03, 5.99484250e-03,
#> 7.05480231e-03, 8.30217568e-03, 9.77009957e-03, 1.14975700e-02,
#> 1.35304777e-02, 1.59228279e-02, 1.87381742e-02, 2.20513074e-02,
#> 2.59502421e-02, 3.05385551e-02, 3.59381366e-02, 4.22924287e-02,
#> 4.97702356e-02, 5.85702082e-02, 6.89261210e-02, 8.11130831e-02,
#> 9.54548457e-02, 1.12332403e-01, 1.32194115e-01, 1.55567614e-01,
#> 1.83073828e-01, 2.15443469e-01, 2.53536449e-01, 2.98364724e-01,
#> 3.51119173e-01, 4.13201240e-01, 4.86260158e-01, 5.72236766e-01,
#> 6.73415066e-01, 7.92482898e-01, 9.32603347e-01, 1.09749877e+00,
#> 1.29154967e+00, 1.51991108e+00, 1.78864953e+00, 2.10490414e+00,
#> 2.47707636e+00, 2.91505306e+00, 3.43046929e+00, 4.03701726e+00,
#> 4.75081016e+00, 5.59081018e+00, 6.57933225e+00, 7.74263683e+00,
#> 9.11162756e+00, 1.07226722e+01, 1.26185688e+01, 1.48496826e+01,
#> 1.74752840e+01, 2.05651231e+01, 2.42012826e+01, 2.84803587e+01,
#> 3.35160265e+01, 3.94420606e+01, 4.64158883e+01, 5.46227722e+01,
#> 6.42807312e+01, 7.56463328e+01, 8.90215085e+01, 1.04761575e+02,
#> 1.23284674e+02, 1.45082878e+02, 1.70735265e+02, 2.00923300e+02,
#> 2.36448941e+02, 2.78255940e+02, 3.27454916e+02, 3.85352859e+02,
#> 4.53487851e+02, 5.33669923e+02, 6.28029144e+02, 7.39072203e+02,
#> 8.69749003e+02, 1.02353102e+03, 1.20450354e+03, 1.41747416e+03,
#> 1.66810054e+03, 1.96304065e+03, 2.31012970e+03, 2.71858824e+03,
#> 3.19926714e+03, 3.76493581e+03, 4.43062146e+03, 5.21400829e+03,
#> 6.13590727e+03, 7.22080902e+03, 8.49753436e+03, 1.00000000e+04])
alphas = np.logspace(-3, 4, 100)
reg_coef = []
for a in alphas:
ridge_reg = Ridge(alpha=a)
ridge_reg.fit(X_train, y_train)
reg_coef.append(ridge_reg.coef_)Ridge(alpha=np.float64(10000.0))In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | np.float64(10000.0) | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
ax = plt.gca()
ax.plot(alphas, reg_coef)
ax.set_xscale('log')
ax.set_xlim(ax.get_xlim())
#> (np.float64(0.00044668359215096305), np.float64(22387.21138568338))
plt.xlabel('Shrinkage effect ($\\alpha$)')
plt.ylabel('Regression Coefficients')
plt.show()When using the Ridge model with tidymodels, The only two changes are that we set the argument mixture= in the linear_reg() command to mixture=0, indicating that we use a Ridge model and that we arbitrarily set the argument penalty=1000000
\(\lambda=1000000\)
.
ridge_spec<-linear_reg(penalty = 1, mixture = 0) |>
set_engine("glmnet") |>
set_mode("regression")
ridge_spec |> translate()
#> Linear Regression Model Specification (regression)
#>
#> Main Arguments:
#> penalty = 1
#> mixture = 0
#>
#> Computational engine: glmnet
#>
#> Model fit template:
#> glmnet::glmnet(x = missing_arg(), y = missing_arg(), weights = missing_arg(),
#> alpha = 0, family = "gaussian")model_ft<-ridge_spec |>
fit(Price~., data= train_df)tidy(model_ft)| term | estimate | penalty |
|---|---|---|
| (Intercept) | 18.6382130 | 1 |
| CRIM | -0.0139169 | 1 |
| ZN | 0.0196570 | 1 |
| INDUS | -0.0403636 | 1 |
| CHAS | 3.8950449 | 1 |
| NOX | -10.6358990 | 1 |
| RM | 4.9903138 | 1 |
| AGE | -0.0091234 | 1 |
| DIS | -0.9698048 | 1 |
| RAD | 0.1152020 | 1 |
| TAX | -0.0046328 | 1 |
| PT | -0.7810886 | 1 |
| B | 0.0099651 | 1 |
| LSTAT | -0.4365943 | 1 |
Because our ridge_spec had penalty = 0, the coefficients here correspond to no penalty, but the glmnet::glmnet() function fits a range of penalty values all at once, which we can extract with broom::tidy like so:
tidy(model_ft, penalty = 100)| term | estimate | penalty |
|---|---|---|
| (Intercept) | 23.7668129 | 100 |
| CRIM | -0.0336930 | 100 |
| ZN | 0.0074350 | 100 |
| INDUS | -0.0351352 | 100 |
| CHAS | 0.5966899 | 100 |
| NOX | -1.9288152 | 100 |
| RM | 0.7451779 | 100 |
| AGE | -0.0060023 | 100 |
| DIS | 0.0315950 | 100 |
| RAD | -0.0199604 | 100 |
| TAX | -0.0014309 | 100 |
| PT | -0.1643814 | 100 |
| B | 0.0020597 | 100 |
| LSTAT | -0.0681767 | 100 |
Check a range of hyperparameters
I’ll first re-fit the data on standardized data (continuous variables re-scaled to have mean of 0, standard deviation of 1):
Recipe <- recipe(Price~., data= train_df) |>
step_normalize(all_predictors())wf <- workflow() |>
add_model(ridge_spec) |>
add_recipe(Recipe) |>
fit(train_df)tidy(wf)| term | estimate | penalty |
|---|---|---|
| (Intercept) | 22.8166667 | 1 |
| CRIM | -0.0915496 | 1 |
| ZN | 0.4658779 | 1 |
| INDUS | -0.2791774 | 1 |
| CHAS | 1.0175297 | 1 |
| NOX | -1.1515438 | 1 |
| RM | 3.5247816 | 1 |
| AGE | -0.2549532 | 1 |
| DIS | -2.0611996 | 1 |
| RAD | 0.9860166 | 1 |
| TAX | -0.7710985 | 1 |
| PT | -1.6910227 | 1 |
| B | 0.8872415 | 1 |
| LSTAT | -3.0809561 | 1 |
DataTestWithPredRidge <- augment(wf, test_df)
library(yardstick)
DataTestWithPredRidge %>%
metrics(truth = Price, estimate = .pred, options = metric_set(rmse, rsq, mae))| .metric | .estimator | .estimate |
|---|---|---|
| rmse | standard | 5.0783215 |
| rsq | standard | 0.6526819 |
| mae | standard | 3.3400487 |
Then I’ll compile coefficient estimates for a wide range of \(\lambda\) values with purrr::map_dfr():
library(ggsci)
library(dplyr)
library(purrr)
library(ggplot2)
library(broom)
theme_set(theme_bw()) # or theme_minimal(), or theme_tableau()
# 100 values from 10^-3 to 10^4
penalties <- 10^(seq(-3, 4, length.out = 100))
# compute coefficient path
ridge_path <- map_dfr(
penalties,
~ tidy(wf, penalty = .x) %>% mutate(penalty = .x)
)
ridge_path %>%
filter(term != "(Intercept)") %>%
ggplot(aes(x = penalty, y = estimate, group = term, color = term)) +
geom_line(size = 1) +
scale_x_log10(breaks = 10^c(-3, -1, 1, 3, 4)) +
geom_vline(xintercept = 40, lty = 2, size = 1) +
labs(
x = expression(lambda),
y = "Standardized coefficients",
color = NULL
) +
ggthemes::scale_color_pander() + # from ggsci, can replace with scale_color_viridis_d() etc.
theme_minimal()+
theme(legend.position = c(0.8, 0.8))The regularization path can be set manually using the path_values argument (see this article for more details):
coef_path_values <- 10^seq(-2, 5, 0.1)
ridge_spec <- linear_reg(penalty = 0, mixture = 0) %>%
set_engine("glmnet", path_values = coef_path_values)model_ft<-ridge_spec |>
fit(Price~., data= train_df)Recipe <- recipe(Price~., data= train_df) |>
step_normalize(all_predictors())wf <- workflow() |>
add_model(ridge_spec) |>
add_recipe(Recipe) |>
fit(train_df)# Compute the l2 norm for the least squares model
credit_lm_fit <- lm(Price~., data= train_df)
credit_lm_fit_l2_norm <- sum(credit_lm_fit$coefficients[-1]^2)
d <- map_dfr(seq(-2, 5, 0.1),
~ tidy(wf, penalty = 10^.x)) %>%
filter(term != "(Intercept)") %>%
group_by(penalty) %>%
mutate(l2_norm = sum(estimate^2),
l2_norm_ratio = l2_norm / credit_lm_fit_l2_norm) %>%
ungroup()
p1 <- d %>%
ggplot(aes(x = penalty, y = estimate)) +
geom_line(aes(group = term), size = 1) +
scale_x_log10(breaks = 10^c(-2, 0, 2, 4)) +
labs(x = expression(lambda), y = "Standardized coefficients", color = NULL) +
scale_color_manual(values = c(td_colors$pastel6[1:4], "grey80")) +
theme(legend.position = c(0.7, 0.8))
p2 <- d %>%
ggplot(aes(x = l2_norm_ratio, y = estimate)) +
geom_line(aes(group = term), size = 1) +
labs(
x = expression(paste("||", hat(beta[lambda]), "||2 / ||", hat(beta), "||2")),
y = NULL, color = NULL
) +
scale_color_manual(values = c(td_colors$pastel6[1:4], "grey80")) +
theme(legend.position = "none")
p1 | p2Hyperparameter tuning
ridge_reg = Ridge()
ridge_regRidge()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
param_grid = {'alpha': np.logspace(-3, 4, 100)}
param_grid
#> {'alpha': array([1.00000000e-03, 1.17681195e-03, 1.38488637e-03, 1.62975083e-03,
#> 1.91791026e-03, 2.25701972e-03, 2.65608778e-03, 3.12571585e-03,
#> 3.67837977e-03, 4.32876128e-03, 5.09413801e-03, 5.99484250e-03,
#> 7.05480231e-03, 8.30217568e-03, 9.77009957e-03, 1.14975700e-02,
#> 1.35304777e-02, 1.59228279e-02, 1.87381742e-02, 2.20513074e-02,
#> 2.59502421e-02, 3.05385551e-02, 3.59381366e-02, 4.22924287e-02,
#> 4.97702356e-02, 5.85702082e-02, 6.89261210e-02, 8.11130831e-02,
#> 9.54548457e-02, 1.12332403e-01, 1.32194115e-01, 1.55567614e-01,
#> 1.83073828e-01, 2.15443469e-01, 2.53536449e-01, 2.98364724e-01,
#> 3.51119173e-01, 4.13201240e-01, 4.86260158e-01, 5.72236766e-01,
#> 6.73415066e-01, 7.92482898e-01, 9.32603347e-01, 1.09749877e+00,
#> 1.29154967e+00, 1.51991108e+00, 1.78864953e+00, 2.10490414e+00,
#> 2.47707636e+00, 2.91505306e+00, 3.43046929e+00, 4.03701726e+00,
#> 4.75081016e+00, 5.59081018e+00, 6.57933225e+00, 7.74263683e+00,
#> 9.11162756e+00, 1.07226722e+01, 1.26185688e+01, 1.48496826e+01,
#> 1.74752840e+01, 2.05651231e+01, 2.42012826e+01, 2.84803587e+01,
#> 3.35160265e+01, 3.94420606e+01, 4.64158883e+01, 5.46227722e+01,
#> 6.42807312e+01, 7.56463328e+01, 8.90215085e+01, 1.04761575e+02,
#> 1.23284674e+02, 1.45082878e+02, 1.70735265e+02, 2.00923300e+02,
#> 2.36448941e+02, 2.78255940e+02, 3.27454916e+02, 3.85352859e+02,
#> 4.53487851e+02, 5.33669923e+02, 6.28029144e+02, 7.39072203e+02,
#> 8.69749003e+02, 1.02353102e+03, 1.20450354e+03, 1.41747416e+03,
#> 1.66810054e+03, 1.96304065e+03, 2.31012970e+03, 2.71858824e+03,
#> 3.19926714e+03, 3.76493581e+03, 4.43062146e+03, 5.21400829e+03,
#> 6.13590727e+03, 7.22080902e+03, 8.49753436e+03, 1.00000000e+04])}from sklearn.model_selection import GridSearchCVgrid = GridSearchCV(ridge_reg, param_grid, cv=10, return_train_score=True)
gridGridSearchCV(cv=10, estimator=Ridge(),
param_grid={'alpha': array([1.00000000e-03, 1.17681195e-03, 1.38488637e-03, 1.62975083e-03,
1.91791026e-03, 2.25701972e-03, 2.65608778e-03, 3.12571585e-03,
3.67837977e-03, 4.32876128e-03, 5.09413801e-03, 5.99484250e-03,
7.05480231e-03, 8.30217568e-03, 9.77009957e-03, 1.14975700e-02,
1.35304777e-02, 1.59228279e-02, 1.87381742e-02, 2...
2.36448941e+02, 2.78255940e+02, 3.27454916e+02, 3.85352859e+02,
4.53487851e+02, 5.33669923e+02, 6.28029144e+02, 7.39072203e+02,
8.69749003e+02, 1.02353102e+03, 1.20450354e+03, 1.41747416e+03,
1.66810054e+03, 1.96304065e+03, 2.31012970e+03, 2.71858824e+03,
3.19926714e+03, 3.76493581e+03, 4.43062146e+03, 5.21400829e+03,
6.13590727e+03, 7.22080902e+03, 8.49753436e+03, 1.00000000e+04])},
return_train_score=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| estimator | Ridge() | |
| param_grid | {'alpha': array([1.0000...00000000e+04])} | |
| scoring | None | |
| n_jobs | None | |
| refit | True | |
| cv | 10 | |
| verbose | 0 | |
| pre_dispatch | '2*n_jobs' | |
| error_score | nan | |
| return_train_score | True |
Ridge()
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
grid.fit(X_train, y_train)GridSearchCV(cv=10, estimator=Ridge(),
param_grid={'alpha': array([1.00000000e-03, 1.17681195e-03, 1.38488637e-03, 1.62975083e-03,
1.91791026e-03, 2.25701972e-03, 2.65608778e-03, 3.12571585e-03,
3.67837977e-03, 4.32876128e-03, 5.09413801e-03, 5.99484250e-03,
7.05480231e-03, 8.30217568e-03, 9.77009957e-03, 1.14975700e-02,
1.35304777e-02, 1.59228279e-02, 1.87381742e-02, 2...
2.36448941e+02, 2.78255940e+02, 3.27454916e+02, 3.85352859e+02,
4.53487851e+02, 5.33669923e+02, 6.28029144e+02, 7.39072203e+02,
8.69749003e+02, 1.02353102e+03, 1.20450354e+03, 1.41747416e+03,
1.66810054e+03, 1.96304065e+03, 2.31012970e+03, 2.71858824e+03,
3.19926714e+03, 3.76493581e+03, 4.43062146e+03, 5.21400829e+03,
6.13590727e+03, 7.22080902e+03, 8.49753436e+03, 1.00000000e+04])},
return_train_score=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| estimator | Ridge() | |
| param_grid | {'alpha': array([1.0000...00000000e+04])} | |
| scoring | None | |
| n_jobs | None | |
| refit | True | |
| cv | 10 | |
| verbose | 0 | |
| pre_dispatch | '2*n_jobs' | |
| error_score | nan | |
| return_train_score | True |
Ridge(alpha=np.float64(0.9326033468832199))
Parameters
| alpha | np.float64(0.9326033468832199) | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
gridGridSearchCV(cv=10, estimator=Ridge(),
param_grid={'alpha': array([1.00000000e-03, 1.17681195e-03, 1.38488637e-03, 1.62975083e-03,
1.91791026e-03, 2.25701972e-03, 2.65608778e-03, 3.12571585e-03,
3.67837977e-03, 4.32876128e-03, 5.09413801e-03, 5.99484250e-03,
7.05480231e-03, 8.30217568e-03, 9.77009957e-03, 1.14975700e-02,
1.35304777e-02, 1.59228279e-02, 1.87381742e-02, 2...
2.36448941e+02, 2.78255940e+02, 3.27454916e+02, 3.85352859e+02,
4.53487851e+02, 5.33669923e+02, 6.28029144e+02, 7.39072203e+02,
8.69749003e+02, 1.02353102e+03, 1.20450354e+03, 1.41747416e+03,
1.66810054e+03, 1.96304065e+03, 2.31012970e+03, 2.71858824e+03,
3.19926714e+03, 3.76493581e+03, 4.43062146e+03, 5.21400829e+03,
6.13590727e+03, 7.22080902e+03, 8.49753436e+03, 1.00000000e+04])},
return_train_score=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| estimator | Ridge() | |
| param_grid | {'alpha': array([1.0000...00000000e+04])} | |
| scoring | None | |
| n_jobs | None | |
| refit | True | |
| cv | 10 | |
| verbose | 0 | |
| pre_dispatch | '2*n_jobs' | |
| error_score | nan | |
| return_train_score | True |
Ridge(alpha=np.float64(0.9326033468832199))
Parameters
| alpha | np.float64(0.9326033468832199) | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
best_alpha = grid.best_params_["alpha"].item()
best_alpha
#> 0.9326033468832199best_r2 = grid.best_score_
best_r2
#> np.float64(0.7152343447251888)cv_results_df = pd.DataFrame(grid.cv_results_)
cv_results_df
#> mean_fit_time std_fit_time ... mean_train_score std_train_score
#> 0 0.000895 0.000902 ... 0.760816 0.008495
#> 1 0.000573 0.000008 ... 0.760816 0.008495
#> 2 0.000583 0.000014 ... 0.760816 0.008495
#> 3 0.000582 0.000025 ... 0.760816 0.008495
#> 4 0.000601 0.000084 ... 0.760816 0.008494
#> .. ... ... ... ... ...
#> 95 0.000594 0.000046 ... 0.018967 0.000863
#> 96 0.000574 0.000009 ... 0.016203 0.000738
#> 97 0.000582 0.000031 ... 0.013831 0.000631
#> 98 0.000570 0.000007 ... 0.011799 0.000538
#> 99 0.000575 0.000016 ... 0.010059 0.000459
#>
#> [100 rows x 31 columns]cv_results_df[['param_alpha', 'mean_test_score', 'mean_train_score','rank_test_score']][30:50]
#> param_alpha mean_test_score mean_train_score rank_test_score
#> 30 0.132194 0.711010 0.760679 17
#> 31 0.155568 0.711318 0.760629 16
#> 32 0.183074 0.711659 0.760562 15
#> 33 0.215443 0.712033 0.760471 14
#> 34 0.253536 0.712437 0.760349 13
#> 35 0.298365 0.712865 0.760187 11
#> 36 0.351119 0.713310 0.759971 10
#> 37 0.413201 0.713759 0.759686 9
#> 38 0.486260 0.714196 0.759312 7
#> 39 0.572237 0.714596 0.758823 6
#> 40 0.673415 0.714930 0.758188 4
#> 41 0.792483 0.715159 0.757370 2
#> 42 0.932603 0.715234 0.756323 1
#> 43 1.097499 0.715096 0.754991 3
#> 44 1.291550 0.714673 0.753308 5
#> 45 1.519911 0.713879 0.751197 8
#> 46 1.788650 0.712614 0.748568 12
#> 47 2.104904 0.710763 0.745317 18
#> 48 2.477076 0.708195 0.741328 49
#> 49 2.915053 0.704766 0.736472 50train_R2s_mean = cv_results_df["mean_train_score"]
train_R2s_std = cv_results_df["std_train_score"]
train_lower = train_R2s_mean - train_R2s_std
train_upper = train_R2s_mean + train_R2s_std
test_R2s_mean = cv_results_df["mean_test_score"]
test_R2s_std = cv_results_df["std_test_score"]
test_lower = test_R2s_mean - test_R2s_std
test_upper = test_R2s_mean + test_R2s_std
alphas = cv_results_df['params'].apply(lambda x: x['alpha'])
plt.figure()
plt.xlabel('Shrinkage effect ($\\alpha$)')
plt.ylabel(r'$R^2$ Score')
plt.semilogx(alphas, train_R2s_mean, label='Mean Train score', color='navy')
plt.gca().fill_between(alphas, train_lower, train_upper,
alpha=0.3, linestyle="--", color='navy')
plt.semilogx(alphas, test_R2s_mean, label='Mean Test score', color='darkorange')
plt.gca().fill_between(alphas, test_lower, test_upper,
alpha=0.3, linestyle="--", color='darkorange')
plt.legend(loc='best')
plt.show()final_ridge_reg = Ridge(alpha=0.79)
final_ridge_reg.fit(X_train, y_train)Ridge(alpha=0.79)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 0.79 | |
| fit_intercept | True | |
| copy_X | True | |
| max_iter | None | |
| tol | 0.0001 | |
| solver | 'auto' | |
| positive | False | |
| random_state | None |
final_ridge_reg.score(X_train, y_train), final_ridge_reg.score(X_test, y_test)
#> (0.7568371435725293, 0.6584246195908776)2. Lasso Regression
- Lasso (Least Absolute Shrinkage and Selection Operator)
Ridge regression will shrink all coefficients towards zero, but will not set them to exactly zero (unless \(\lambda = \infty\)). This doesn’t affect prediction accuracy, but may cause challenges in model interpretation for large numbers of variables \(p\).
The lasso is a relatively recent alternative to ridge regression with a similar formulation as ridge regression. The coefficients \(\hat{\beta}_{\lambda}^L\) minimize the quantity:
\[ \sum_{i=1}^n \left(y_i - \beta_0 - \sum_{j=1}^p \beta_j x_{ij} \right)^2 + \lambda \sum_{j=1}^p | \beta_j | = \text{RSS} + \lambda \sum_{j=1}^p | \beta_j |. \]
Lasso regression is another biased model that uses an \(L_1\) norm (i.e. the sum of absolute values):
\[\min_{{\bf w} \in {\cal R}^p}\ \{\text{SSE}(\hat{\bf w})+\text{penalty}\}=\min_{{\bf w} \in {\cal R}^p}\left[\sum_{i=1}^n(y_i-\hat{y})^2+\alpha\sum_{j=1}^p|w_j|\right]= \min_{{\bf w} \in {\cal R}^p} \sum_{i=1}^p \left\| {\bf w}^T {\bf x}_i - y_i \right\|^2 + \alpha \left\| {\bf w} \right\|_1 \]
Differently from \(L_2\) norm (i.e., ridge regression), which penalizes very large coefficients more, \(L_1\) penalizes equally.
While ridge regression shrinks the parameter estimates towards 0, lasso sets some of the estimates to zero.
Lasso not only performs regularization to improve the model but it also conducts a sort of feature selection.
from sklearn.linear_model import Lassolasso_reg = Lasso()
lasso_regLasso()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_reg.fit(X_train, y_train)Lasso()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_regLasso()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_reg.intercept_
#> np.float64(26.64087491657085)lasso_reg.coef_
#> array([-0. , 0. , -0. , 0. , -0. ,
#> 0. , -0. , 0. , -0. , -2.02965776,
#> -0. , 0. , -9.38089057])lasso_test_r2 = lasso_reg.score(X_test_df, y_test)
#> NameError: name 'X_test_df' is not defined
lasso_test_r2
#> NameError: name 'lasso_test_r2' is not definedfeature_names = transformer.get_feature_names_out()
lasso_reg = Lasso(alpha=0.1)
lasso_reg.fit(X_train, y_train)Lasso(alpha=0.1)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 0.1 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_coef = lasso_reg.coef_
plt.figure(figsize=(6, 3))
plt.plot(range(len(feature_names)), lasso_coef);
plt.xticks(range(len(feature_names)), feature_names, rotation=60);
plt.ylabel('Coefficients')
plt.grid()
plt.show()- \(\alpha =1\)
lasso_reg = Lasso(alpha=0.1)
lasso_reg.fit(X_train, y_train)Lasso(alpha=0.1)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 0.1 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_reg.score(X_train, y_train), lasso_reg.score(X_test, y_test)
#> (0.7174023465148797, 0.615962237876271)Tuning \(\alpha\) Hyperparameter: GridSearchCV()
Instantiate Grid Models:
GridSearchCV()Methods:
.fit(X,y),.score(X,y)Attributes:
.best_params_,.best_score_
lasso_reg = Lasso()
lasso_regLasso()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
np.linspace(0.1, 2, 10)
#> array([0.1 , 0.31111111, 0.52222222, 0.73333333, 0.94444444,
#> 1.15555556, 1.36666667, 1.57777778, 1.78888889, 2. ])param_values = {
'alpha': np.linspace(0.01, 2, 10)
}
param_values
#> {'alpha': array([0.01 , 0.23111111, 0.45222222, 0.67333333, 0.89444444,
#> 1.11555556, 1.33666667, 1.55777778, 1.77888889, 2. ])}lasso_grid = GridSearchCV(estimator = lasso_reg,
param_grid = param_values,
cv=10,
return_train_score=True
)
lasso_gridGridSearchCV(cv=10, estimator=Lasso(),
param_grid={'alpha': array([0.01 , 0.23111111, 0.45222222, 0.67333333, 0.89444444,
1.11555556, 1.33666667, 1.55777778, 1.77888889, 2. ])},
return_train_score=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| estimator | Lasso() | |
| param_grid | {'alpha': array([0.01 ..., 2. ])} | |
| scoring | None | |
| n_jobs | None | |
| refit | True | |
| cv | 10 | |
| verbose | 0 | |
| pre_dispatch | '2*n_jobs' | |
| error_score | nan | |
| return_train_score | True |
Lasso()
Parameters
| alpha | 1.0 | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
lasso_grid.fit(X_train, y_train)GridSearchCV(cv=10, estimator=Lasso(),
param_grid={'alpha': array([0.01 , 0.23111111, 0.45222222, 0.67333333, 0.89444444,
1.11555556, 1.33666667, 1.55777778, 1.77888889, 2. ])},
return_train_score=True)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| estimator | Lasso() | |
| param_grid | {'alpha': array([0.01 ..., 2. ])} | |
| scoring | None | |
| n_jobs | None | |
| refit | True | |
| cv | 10 | |
| verbose | 0 | |
| pre_dispatch | '2*n_jobs' | |
| error_score | nan | |
| return_train_score | True |
Lasso(alpha=np.float64(0.01))
Parameters
| alpha | np.float64(0.01) | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
best_alpha = lasso_grid.best_params_
best_alpha
#> {'alpha': np.float64(0.01)}best_score = lasso_grid.best_score_
best_score
#> np.float64(0.7086445624905477)lasso_reg = Lasso()
alphas = np.logspace(-3, 1, 50)
coefs = list()
for alpha in alphas:
lasso_reg.set_params(alpha=alpha)
lasso_reg.fit(X_train, y_train)
coefs.append(lasso_reg.coef_)Lasso(alpha=np.float64(10.0))In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| alpha | np.float64(10.0) | |
| fit_intercept | True | |
| precompute | False | |
| copy_X | True | |
| max_iter | 1000 | |
| tol | 0.0001 | |
| warm_start | False | |
| positive | False | |
| random_state | None | |
| selection | 'cyclic' |
ax = plt.gca()
ax.plot(alphas, coefs)
ax.set_xscale('log')
ax.set_xlim(ax.get_xlim())
#> (np.float64(0.000630957344480193), np.float64(15.848931924611133))
plt.xlabel('Shrinkage effect ($\\alpha$)')
plt.ylabel('Regression Coefficients')
plt.show()Note:
When we use
Lassoand setalpha=0, we might expect the model to behave like OLS regression.However,
Lassodoes not automatically switch to a pure OLS regression model.Rather, it results some warning error like
UserWarning: ....“.
When using the Ridge model with tidymodels, The only two changes are that we set the argument mixture= in the linear_reg() command to mixture=0, indicating that we use a Ridge model and that we arbitrarily set the argument penalty=1000000
\(\lambda=1000000\)
.
ridge_spec<-linear_reg(penalty=1000, mixture=0) |>
set_engine("glmnet") |>
set_mode("regression")model_ft<-ridge_spec |>
fit(Price~., data= train_df)
Recipe <- recipe(Price~., data= train_df)wf <- workflow() |>
add_model(ridge_spec) |>
add_recipe(Recipe) |>
fit(train_df)tidy(wf)| term | estimate | penalty |
|---|---|---|
| (Intercept) | 23.0431413 | 1000 |
| CRIM | -0.0052309 | 1000 |
| ZN | 0.0011723 | 1000 |
| INDUS | -0.0054930 | 1000 |
| CHAS | 0.0664680 | 1000 |
| NOX | -0.3165618 | 1000 |
| RM | 0.0913370 | 1000 |
| AGE | -0.0010147 | 1000 |
| DIS | 0.0085506 | 1000 |
| RAD | -0.0034940 | 1000 |
| TAX | -0.0002257 | 1000 |
| PT | -0.0217389 | 1000 |
| B | 0.0002997 | 1000 |
| LSTAT | -0.0089553 | 1000 |
DataTestWithPredRidge <- augment(wf, test_df)
library(yardstick)
DataTestWithPredRidge %>%
metrics(truth = Price, estimate = .pred, options = metric_set(rmse, rsq, mae))| .metric | .estimator | .estimate |
|---|---|---|
| rmse | standard | 8.3716399 |
| rsq | standard | 0.5547312 |
| mae | standard | 6.0943078 |
III. Elastic Net Regression
- Elastic Net combines both \(L_1\) and \(L_2\) penalties together (using the effect of both ridge and lasso regressions):
\[\min_{{\bf w} \in {\cal R}^p}\ \{\text{SSE}(\hat{\bf w})+\text{penalty}\}=\min_{{\bf w} \in {\cal R}^p}\left[\sum_{i=1}^n(y_i-\hat{y})^2+\alpha_1\sum_{j=1}^p|w_j| + \alpha_2\sum_{j=1}^pw_j^2\right]= \min_{{\bf w} \in {\cal R}^p} \sum_{i=1}^p \left\| {\bf w}^T {\bf x}_i - y_i \right\|^2 + \alpha_1 \left\| {\bf w} \right\|_1 + \alpha_2 \left\| {\bf w} \right\|_2^2 \]
In
scikit-learn, it is parametrized differently:\[\min_{{\bf w} \in {\cal R}^p}\ \{\text{SSE}(\hat{\bf w})+\text{penalty}\}= \min_{{\bf w} \in {\cal R}^p} \sum_{i=1}^p \left\| {\bf w}^T {\bf x}_i - y_i \right\|^2 + \alpha\; \ell_1\; \left\| {\bf w} \right\|_1+\alpha \;(1-\ell_1)\; \left\| {\bf w} \right\|_2^2 \]
where \(\ell_1\) captures the relative amount of \(L_1\)-penalty.
\(\ell_1=1 \Rightarrow\) Lasso Regression
\(\ell_1=0 \Rightarrow\) Ridge Regression
\(\alpha=0 \Rightarrow\) OLS Regression
Support Vector Machine (SVM)
Linear regression
Applicable only for continuous (or quantitative in general) response variables.
By default assumes a linear relationship between predictors and the outcome.
If the relationship is non-linear, transformations or manual specification are required.
Logistic regression
Used for modeling categorical outcome variables.
The model is intrinsically a linear function of the predictor variables (via the log-odds).
An SVM
Can handle both regression and classification problems.
For classification: Support Vector Classifier (SVC).
For regression problems: Support Vector Regressor (SVR).
Unlike regression models that are strictly linear unless specified otherwise, SVMs can be:
Linear, when used with a linear kernel.
Non-linear, by using kernels that implicitly map data to higher dimensions.
What is an SVM?
For Classification (SVC):
Finds the best separating hyperplane that maximizes the margin between the different classes.
Support vectors (SVs) define the decision boundary (line/plane) and are the closest points to that boundary.
Intuitively, SVM does not just separate classes — it separates them with the widest possible gap.
For regression (SVR):
- Instead of a strict boundary, it fits a function that keeps most data points within a margin of tolerance (the “tube”).
4.1. Linear SVC
Linear SVC looks for the hyperplane that maximizes the margins for linearly separable data.
The decision boundary for a Linear SVC is similar to that of a logistic regression model:
\[w_0+w_1x_{i1}+w_2x_{i2}+\cdots+w_px_{ip}={\bf w}^T{\bf x}_i=0\]
The SVC aims to choose \(\bf w\) that minimize the Hinge loss instead of the log-loss of logistic regression: \[min_{{\bf w}\in {\cal R}^{p+1}}\sum_{i=1}^n \max(0,1-y_i\;{\bf w}^T{\bf x}_i)\]
Note:
|
|
With an \(L_2\) regularization:
\[min_{{\bf w}\in {\cal R}^{p+1}}\left[C\sum_{i=1}^n \max(0,1-y_i\;{\bf w}^T{\bf x}_i)+\frac{1}{2}||{{\bf w}}||^2\right]\]
- Like a regularized logistic regression, \(𝐶>0\) is a regularization parameter.
What is the difference between Linear SVC and Logistic Regression?
In order to construct a classifier based upon a separating hyperplane, we must have a reasonable way to decide which of the infinite possible separating hyperplanes to use.
A natural choice is the maximal margin hyperplane (also known as the maximal optimal separating hyperplane), which is the separating hyperplane that is farthest from the training observations. That is, we can compute the (perpendicular) distance from each training observation to a given separating hyperplane; the smallest such distance is the minimal distance from the observations to the hyperplane, and is known as the margin.
An SVC aims to find the best separating hyperplane that maximizes the margin between the different classes.
- The margin is defined as the distance from the boundary to the closest points of each class.
The maximal margin hyperplane is the separating hyperplane for which the margin is largest—that is, it is the hyperplane that has the farthest minimum distance to the training observations.
We hope that a classifier that has a large maximal margin on the training data will also have a large margin on the test data, and hence will classify the test observations correctly. Although the maximal margin classifier is often successful, it can also lead to overfiting when p is large.
|
Possible decision boundaries of logistic regression : A, B, C |
A decision boundary for a Linear SVC |
In Logistic and linear regression, all points contribute to \(\bf w\), which is not true for SVMs.
Only the SVs (i.e., incorrectly classified examples or close to the boundary) determine \(\bf w\).
If an example is not a SV, removing it has no effect on the model.
How close the SVs are to the boundary plane is controlled by regularization strength (\(C\)).
\(𝐶>0\) balances the trade-off between the margin and classification error.
Using a linear hyperplane to separate these two classes is not feasible.
However, projecting the data into a higher dimension makes a linear separator sufficient. How?
By simply adding a new set of nonlinear features, obtained from the original ones.
Representing each data point from a 2D point, \((x_1, x_2)\), to a 3D point, \((x_1, x_2, x_2^2)\).
Often we do not know which features to add.
Adding many features (like all possible interactions) might be computationally expensive.
Fortunately, there is a kernel trick in an SVM that allows to learn a without actually computing the new representation.
There are two ways commonly used with SVM:
Polynomial kernel: computes all possible polynomials up to a certain degree of the original features, such as \((x_1^2\cdot x_2^5)\).
Radial basis function (RBF) kernel (gaussian kernel):
It considers all possible polynomials of all degress.
But the importance of the features decreases for higher degrees.
\[f({\bf x}_i)=\sum_{h\in \text{SV}}\alpha_hy_h\;K({\bf x}_h,{\bf x}_i)+w_0 \;\;\;\;\; \text{ where }\;\; K({\bf x}_h,{\bf x}_i)=e^{-\gamma||{\bf x}_h-{\bf x}_i||^2}\]
\(\gamma\) represents kernel width (how far the influence of a point reaches) that affects the decision boundary.
The kernel equlivalent for a linear SVC is: \[f({\bf x}_i)={\bf w}^T{\bf x}_i+w_0=\sum_{h\in \text{SV}}\alpha_hy_h{\bf x}_h^T{\bf x}_i+w_0\;\;\;\;\; \text{ where }\;\; K({\bf x}_h,{\bf x}_i)={\bf x}_h^T{\bf x}_i\]
Logistic Regression vs support vector Machine
## import datasets
import sklearn.datasets
wine = sklearn.datasets.load_wine()
## Import model
from sklearn.linear_model import LogisticRegression
## instantiate model
lr = LogisticRegression()
lr.fit(wine.data , wine.target)LogisticRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| penalty | 'l2' | |
| dual | False | |
| tol | 0.0001 | |
| C | 1.0 | |
| fit_intercept | True | |
| intercept_scaling | 1 | |
| class_weight | None | |
| random_state | None | |
| solver | 'lbfgs' | |
| max_iter | 100 | |
| multi_class | 'deprecated' | |
| verbose | 0 | |
| warm_start | False | |
| n_jobs | None | |
| l1_ratio | None |
lr.score(wine.data , wine.target)
#> 0.9662921348314607
lr.predict_proba(wine.data[:1])
#> array([[9.96579143e-01, 2.74166519e-03, 6.79192169e-04]])## import datasets
import sklearn.datasets
wine = sklearn.datasets.load_wine()
## Import model
from sklearn.svm import LinearSVC
## instantiate model
svm = LinearSVC()
svm.fit(wine.data , wine.target)LinearSVC()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| penalty | 'l2' | |
| loss | 'squared_hinge' | |
| dual | 'auto' | |
| tol | 0.0001 | |
| C | 1.0 | |
| multi_class | 'ovr' | |
| fit_intercept | True | |
| intercept_scaling | 1 | |
| class_weight | None | |
| verbose | 0 | |
| random_state | None | |
| max_iter | 1000 |
svm.score(wine.data , wine.target)
#> 0.9887640449438202## import datasets
import sklearn.datasets
wine = sklearn.datasets.load_wine()
## Import model
from sklearn.svm import SVC
## instantiate model
svm = SVC()
svm.fit(wine.data , wine.target)SVC()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| C | 1.0 | |
| kernel | 'rbf' | |
| degree | 3 | |
| gamma | 'scale' | |
| coef0 | 0.0 | |
| shrinking | True | |
| probability | False | |
| tol | 0.001 | |
| cache_size | 200 | |
| class_weight | None | |
| verbose | False | |
| max_iter | -1 | |
| decision_function_shape | 'ovr' | |
| break_ties | False | |
| random_state | None |
svm.score(wine.data , wine.target)
#> 0.7078651685393258from sklearn import datasets
digits = datasets.load_digits()
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target)
# Apply logistic regression and print scores
lr = LogisticRegression()
lr.fit(X_train, y_train)LogisticRegression()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| penalty | 'l2' | |
| dual | False | |
| tol | 0.0001 | |
| C | 1.0 | |
| fit_intercept | True | |
| intercept_scaling | 1 | |
| class_weight | None | |
| random_state | None | |
| solver | 'lbfgs' | |
| max_iter | 100 | |
| multi_class | 'deprecated' | |
| verbose | 0 | |
| warm_start | False | |
| n_jobs | None | |
| l1_ratio | None |
print(lr.score(X_train , y_train))
#> 1.0
print(lr.score(X_test, y_test))
#> 0.9777777777777777
# Apply SVM and print scores
svm = SVC()
svm.fit(X_train, y_train)SVC()In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
| C | 1.0 | |
| kernel | 'rbf' | |
| degree | 3 | |
| gamma | 'scale' | |
| coef0 | 0.0 | |
| shrinking | True | |
| probability | False | |
| tol | 0.001 | |
| cache_size | 200 | |
| class_weight | None | |
| verbose | False | |
| max_iter | -1 | |
| decision_function_shape | 'ovr' | |
| break_ties | False | |
| random_state | None |
print(svm.score(X_train , y_train))
#> 0.9955456570155902
print(svm.score(X_test, y_test))
#> 0.9844444444444445# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.inspection import DecisionBoundaryDisplay
# import some data to play with
iris = datasets.load_iris()
# Take the first two features. We could avoid this by using a two-dim dataset
X = iris.data[:, :2]
y = iris.target
# we create an instance of SVM and fit out data. We do not scale our
# data since we want to plot the support vectors
C = 1.0 # SVM regularization parameter
models = (
svm.SVC(kernel="linear", C=C),
svm.LinearSVC(C=C, max_iter=10000),
svm.SVC(kernel="rbf", gamma=0.7, C=C),
svm.SVC(kernel="poly", degree=3, gamma="auto", C=C),
)
models = (clf.fit(X, y) for clf in models)
# title for the plots
titles = (
"SVC with linear kernel",
"LinearSVC (linear kernel)",
"SVC with RBF kernel",
"SVC with polynomial (degree 3) kernel",
)
# Set-up 2x2 grid for plotting.
fig, sub = plt.subplots(2, 2)
plt.subplots_adjust(wspace=0.4, hspace=0.4)
X0, X1 = X[:, 0], X[:, 1]
for clf, title, ax in zip(models, titles, sub.flatten()):
disp = DecisionBoundaryDisplay.from_estimator(
clf,
X,
response_method="predict",
cmap=plt.cm.coolwarm,
alpha=0.8,
ax=ax,
xlabel=iris.feature_names[0],
ylabel=iris.feature_names[1],
)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors="k")
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)
plt.show()












