SUPERVISED LEARNING WITH SCIKIT-LEARN AND TIDYMODELS

AI and Machine Learning for Public Health Practioners

Bongani Ncube

2026-01-02

reticulate package logo

reticulate package logo

Library Setup

Data Preparation

Data dimension

Check Missing data

Sum of missing data in each column

Data description

Correlations matrix

Introduction 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

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:

  1. Sampling variability in the estimated coefficients (\(\hat{\beta}\)).
  2. Model bias if the assumed linearity does not hold.
  3. Irreducible error \(\epsilon\).

Prediction intervals are always wider than confidence intervals since they incorporate both reducible and irreducible error.

NoteSummary model evaluation

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!

TipMachine learning

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.1711712

A simple Model Training workflow

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

  1. 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?

  2. 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.

  3. 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

NoteClassification Metrics
  • 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

NoteIdeally

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.

we will drop categorical columns for now , to use as illustration in feature engineering

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_split returns four arrays: the training data, the test data, the training labels, and the test labels

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.

Overfitting 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.
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}
Note

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

Building a logistic regression model

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_reg
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.
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.

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-26
  • The default performance metric in scikit-learn is \(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-13

Resampling 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

NoteRegularized 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).

Hyperparameter tuning

ridge_reg = Ridge()
ridge_reg
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.
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 GridSearchCV
grid = GridSearchCV(ridge_reg, param_grid, cv=10, return_train_score=True)
grid
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.
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.
grid
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.
best_alpha = grid.best_params_["alpha"].item()
best_alpha
#> 0.9326033468832199
best_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               50
train_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.
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.

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:

  • \(y_i=1\) and \({\bf w}^T{\bf x}_i>1\): hinge loss = 0

  • \(y_i=1\) and (\({\bf w}^T{\bf x}_i>0\) and \({\bf w}^T{\bf x}_i<1\)): 0 < hinge loss < 1

  • \(y_i=1\) and \({\bf w}^T{\bf x}_i<0\): hinge loss > 1

  • \(y_i=0\) and \({\bf w}^T{\bf x}_i<0\): hinge loss = 1

  • \(y_i=0\) and \({\bf w}^T{\bf x}_i>0\): hinge loss = 1

  • 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

    Back to top