lasso回归R语言代码
时间: 2023-09-20 15:04:27 浏览: 92
Sure! Here's an example of Lasso regression code in R:
```R
# Load the glmnet package
library(glmnet)
# Generate some sample data
set.seed(123)
x <- matrix(rnorm(1000), ncol = 10)
y <- rnorm(100)
# Split the data into training and testing sets
train_idx <- sample(1:100, 70)
x_train <- x[train_idx, ]
y_train <- y[train_idx]
x_test <- x[-train_idx, ]
y_test <- y[-train_idx]
# Fit the Lasso regression model using cross-validation
fit <- cv.glmnet(x_train, y_train, alpha = 1)
# Determine the optimal lambda value
best_lambda <- fit$lambda.min
# Print the optimal lambda value
print(best_lambda)
# Fit the Lasso regression model with the optimal lambda value
lasso_model <- glmnet(x_train, y_train, alpha = 1, lambda = best_lambda)
# Predict on the test set
predictions <- predict(lasso_model, newx = x_test)
# Calculate the root mean squared error (RMSE)
rmse <- sqrt(mean((predictions - y_test)^2))
# Print the RMSE
print(rmse)
```
This code uses the `glmnet` package to perform Lasso regression. It starts by generating some sample data, splitting it into training and testing sets. Then, it fits the Lasso regression model using cross-validation and selects the optimal lambda value. Finally, it fits the Lasso model with the optimal lambda value, predicts on the test set, and calculates the root mean squared error (RMSE).
阅读全文