Lasso 迴歸

R 的降維

Matt Pickard

Owner, Pickard Predictives, LLC

Lasso 迴歸概觀

  • 監督式特徵選擇
  • L1 正規化
  • 懲罰迴歸係數
  • 係數收縮
  • 次要係數收縮為 0
  • 自然進行特徵選擇
linear_reg(engine = "glmnet", penalty = 0.001 , mixture = 1)
R 的降維

標準化資料

  • 先標準化資料,讓懲罰在各特徵上同等適用
  • 對目標變數用 scale()
    • 回傳矩陣,用 as.vector() 轉為向量
  • 對解釋變數用 step_normalize()

範例

# 對目標變數做標準化
df <- df %>% mutate(target = as.vector(scale(target))) 
... 
# 對解釋變數做標準化
recipe() %>% step_normalize(all_numeric_predictors()) 
R 的降維

選擇懲罰值

  • 懲罰是要最佳化的超參數
  • 搜尋最佳懲罰值
  • tidymodels 中使用 tune()
linear_reg(engine = "glmnet", penalty = tune() , mixture = 1)
R 的降維

準備資料

對目標變數做標準化
house_sales_subset_df <- house_sales_subset_df %>% 
  mutate(price = as.vector(scale(price)))
建立訓練集與測試集
split <- initial_split(house_sales_subset_df, prop = 0.8)
train <- split %>% training()
test <-  split %>% testing()
R 的降維

建立 recipe

建立 recipe
lasso_recipe <- 
  recipe(price ~ ., data = train) %>% 
  step_normalize(all_numeric_predictors()) 
R 的降維

建立工作流程

建立模型規格
lasso_model <- linear_reg(penalty = 0.01, mixture = 1, engine = "glmnet")
建立工作流程
lasso_workflow <- workflow(preprocessor = lasso_recipe, spec =  lasso_model)
R 的降維

擬合工作流程

tidy(lasso_workflow %>% fit(train)) %>% filter(estimate > 0)
# A tibble: 9 × 3
  term          estimate penalty
  <chr>            <dbl>   <dbl>
1 bathrooms      0.0477     0.01
2 sqft_living    0.434      0.01
3 floors         0.0262     0.01
4 waterfront     0.133      0.01
5 view           0.0510     0.01
6 condition      0.0319     0.01
...              ...        ...
R 的降維

建立可調參的模型工作流程

建立可調參的模型規格
lasso_model <- linear_reg(penalty = tune(), mixture = 1, engine = "glmnet")
lasso_workflow <- workflow(preprocessor = lasso_recipe, spec =  lasso_model)
建立交叉驗證訓練樣本
train_cv <- vfold_cv(train, v = 5)
建立懲罰值網格
penalty_grid <- grid_regular(penalty(range = c(-3, -1)), levels = 20)
  • 懲罰範圍 0.001 到 0.1 以 range = c(-3, -1) 指定
R 的降維

擬合一組模型網格

建立已擬合模型的網格
lasso_grid <- tune_grid(
  lasso_workflow,
  resamples = train_cv,
  grid = penalty_grid)
繪製模型效能
autoplot(lasso_grid, metric = "rmse")
R 的降維

懲罰效能圖

懲罰效能圖

R 的降維

完成模型

取回最佳模型的懲罰值
best_rmse <- lasso_grid %>% select_best("rmse")
重新擬合最佳模型
final_lasso <- 
  finalize_workflow(lasso_workflow, best_rmse) %>% 
  fit(train)
顯示最佳模型的係數
tidy(final_lasso) %>% filter(estimate > 0)
R 的降維

一起來練習吧!

R 的降維

Preparing Video For Download...