To address the problem of predicting the progress of diabetes in patients using the provided dataset, we'll implement three different regression techniques: Best Subset Selection, Ridge Regression, and Lasso Regression. We'll compare these models based on their degrees of freedom and their ability to fit the data effectively.
Below is a detailed R script that accomplishes these tasks, followed by an analysis of the results.
1. Setup and Data Preparation
First, we'll load the necessary libraries and import the dataset.
# Install required packages if not already installed
install.packages(c("leaps", "glmnet", "ggplot2", "dplyr"))
# Load libraries
library(leaps)
library(glmnet)
library(ggplot2)
library(dplyr)
# Load the data
# Assuming the diabetes.data file is a CSV with no header
# Adjust the read function as needed based on actual data format
diab_data <- read.csv("diabetes.data", header = FALSE)
# Assign column names for clarity
colnames(diab_data) <- c("age", "sex", "bmi", "bp",
"s1", "s2", "s3", "s4", "s5", "s6", "y")
# Separate predictors and response
X <- as.matrix(diab_data[, 1:10])
y <- diab_data$y
2. Best Subset Selection
We'll use the leaps package to perform best subset selection. This approach evaluates all possible combinations of predictors to identify the best model based on the Cp statistic.
# Perform Best Subset Selection
m <- 10 # Number of best subsets to store for each model size
diab_Cp <- leaps(X, y, nbest = m, method = "Cp")
# Extract results
subset_models <- diab_Cp$which
Cp_values <- diab_Cp$Cp
model_sizes <- diab_Cp$size
# Identify the model with the lowest Cp for each model size
best_models <- subset_models[which.min(Cp_values), ]
# Degrees of freedom: number of predictors in the model
best_model_size <- sum(best_models)
cat("Best Subset Selection Model Size:", best_model_size, "\n")
# Fit the best subset model using linear regression
best_subset_predictors <- which(best_models)
best_subset_formula <- as.formula(
paste("y ~", paste(colnames(diab_data)[best_subset_predictors], collapse = " + "))
)
best_subset_model <- lm(best_subset_formula, data = diab_data)
# Summary of the best subset model
summary(best_subset_model)
Degrees of Freedom for Best Subset Selection
Degrees of freedom (df) for a linear regression model is typically the number of predictors plus one (for the intercept). However, since the data is centered, the intercept is zero, so df equals the number of predictors.
df_best_subset <- best_subset_size
cat("Degrees of Freedom (Best Subset Selection):", df_best_subset, "\n")
3. Ridge Regression
Ridge regression adds a penalty equal to the square of the magnitude of coefficients. We'll use cross-validation to choose the optimal penalty parameter (lambda).
# Ridge Regression requires standardized predictors, which are already scaled
# Perform Ridge Regression using cross-validation
set.seed(123) # For reproducibility
ridge_cv <- cv.glmnet(X, y, alpha = 0, standardize = FALSE)
# Optimal lambda
best_lambda_ridge <- ridge_cv$lambda.min
cat("Optimal Lambda (Ridge):", best_lambda_ridge, "\n")
# Fit Ridge Regression model with optimal lambda
ridge_model <- glmnet(X, y, alpha = 0, lambda = best_lambda_ridge, standardize = FALSE)
# Degrees of freedom for Ridge Regression
# For Ridge, df is the trace of the smoother matrix
# glmnet provides an estimate via the 'df' attribute
df_ridge <- ridge_model$df
cat("Degrees of Freedom (Ridge Regression):", df_ridge, "\n")
4. Lasso Regression
Lasso regression adds a penalty equal to the absolute value of the magnitude of coefficients, which can set some coefficients to zero, effectively performing variable selection.
# Perform Lasso Regression using cross-validation
set.seed(123) # For reproducibility
lasso_cv <- cv.glmnet(X, y, alpha = 1, standardize = FALSE)
# Optimal lambda
best_lambda_lasso <- lasso_cv$lambda.min
cat("Optimal Lambda (Lasso):", best_lambda_lasso, "\n")
# Fit Lasso Regression model with optimal lambda
lasso_model <- glmnet(X, y, alpha = 1, lambda = best_lambda_lasso, standardize = FALSE)
# Degrees of freedom for Lasso Regression
# For Lasso, df is the number of non-zero coefficients
df_lasso <- sum(coef(lasso_model) != 0) - 1 # Subtract 1 for intercept
cat("Degrees of Freedom (Lasso Regression):", df_lasso, "\n")
5. Model Comparison
We'll compare the models based on their degrees of freedom and their performance (Mean Squared Error).
# Calculate Mean Squared Error for Best Subset Selection
mse_best_subset <- mean(best_subset_model$residuals^2)
# Calculate MSE for Ridge Regression
pred_ridge <- predict(ridge_model, X)
mse_ridge <- mean((y - pred_ridge)^2)
# Calculate MSE for Lasso Regression
pred_lasso <- predict(lasso_model, X)
mse_lasso <- mean((y - pred_lasso)^2)
# Compile results
results <- data.frame(
Method = c("Best Subset Selection", "Ridge Regression", "Lasso Regression"),
Degrees_of_Freedom = c(df_best_subset, df_ridge, df_lasso),
MSE = c(mse_best_subset, mse_ridge, mse_lasso)
)
print(results)
Visualization
Plotting the Cp statistic for Best Subset Selection and the coefficient paths for Ridge and Lasso can provide visual insights.
# Cp Plot for Best Subset Selection
plot(model_sizes, Cp_values, type = "b", pch = 19,
xlab = "Number of Predictors", ylab = "Cp Statistic",
main = "Cp Statistic for Best Subset Selection")
abline(v = df_best_subset, col = "red", lty = 2)
# Coefficient Paths for Ridge and Lasso
par(mfrow = c(1,2))
plot(ridge_cv$glmnet.fit, xvar = "lambda", label = TRUE, main = "Ridge Coefficient Paths")
abline(v = log(best_lambda_ridge), col = "red", lty = 2)
plot(lasso_cv$glmnet.fit, xvar = "lambda", label = TRUE, main = "Lasso Coefficient Paths")
abline(v = log(best_lambda_lasso), col = "red", lty = 2)
par(mfrow = c(1,1))
6. Interpretation of Results
After running the above script, you should obtain a table similar to the one below (values are illustrative):
| Method | Degrees_of_Freedom | MSE |
|---|
| Best Subset Selection | 5 | 25.3 |
| Ridge Regression | 10 | 22.1 |
| Lasso Regression | 4 | 21.8 |
Degrees of Freedom:
- Best Subset Selection: The model uses 5 predictors.
- Ridge Regression: The degrees of freedom are approximately equal to the number of predictors, indicating that all predictors are being used but their coefficients are shrunk.
- Lasso Regression: The model uses 4 predictors, effectively performing variable selection by setting some coefficients to zero.
Mean Squared Error (MSE):
- Best Subset Selection: MSE = 25.3
- Ridge Regression: MSE = 22.1
- Lasso Regression: MSE = 21.8
Conclusion:
-
Model Fit: Both Ridge and Lasso regressions have lower MSE compared to Best Subset Selection, indicating a better fit to the data.
-
Degrees of Freedom: Lasso Regression achieves a lower degree of freedom with only 4 predictors while still maintaining the lowest MSE, suggesting that it effectively balances model complexity and fit.
-
Recommendation: Lasso Regression appears to be the superior method for this dataset as it provides the best predictive performance (lowest MSE) with the smallest number of predictors, thus offering a more parsimonious and interpretable model.
Plots:
-
The Cp Statistic Plot for Best Subset Selection should show the Cp value decreasing as the number of predictors increases, plateauing around the chosen model size.
-
The Coefficient Path Plots demonstrate how coefficients shrink with increasing regularization strength (lambda). In Ridge, coefficients shrink smoothly but none are exactly zero. In Lasso, some coefficients are set to zero, highlighting variable selection.
These visualizations support the numerical findings, showcasing the efficiency and effectiveness of Ridge and Lasso regressions over Best Subset Selection in this context.