Post

Lasso & Ridge 회귀 분석, 로지스틱 회귀 & 랜덤포레스트를 활용한 변수 선택 및 분석

Lasso & Ridge 회귀 분석, 로지스틱 회귀 & 랜덤포레스트를 활용한 변수 선택 및 분석

✅ Lasso & Ridge 회귀 분석 개요

Lasso와 Ridge 회귀는 선형 회귀에서 다중공선성을 해결하고 변수 선택(Feature Selection)을 할 때 유용한 정규화 기법입니다.

🔹 Lasso 회귀 (L1 정규화)

특징

  • 불필요한 변수를 자동으로 0으로 만들어 제거하는 기능이 있음 (변수 선택 기능).
  • 즉, 중요한 변수만 남김 → 해석력이 높아짐.
  • 희소성(Sparsity)을 가지므로, 차원이 높은 데이터에 적합.

목적 함수 (Loss Function)

[ \text{Minimize} \quad \sum_{i=1}^{n} (y_i - \hat{y_i})^2 + \lambda \sum_{j=1}^{p} |\beta_j| ]

  • λ(람다): 정규화 강도 (클수록 더 많은 변수를 0으로 만듦)

🔹 Ridge 회귀 (L2 정규화)

특징

  • 모든 변수를 유지하지만, 회귀 계수를 작게 조정하여 다중공선성 해결.
  • 변수를 완전히 제거하지 않음 → 모든 변수가 예측에 기여.
  • 과적합(Overfitting)을 방지할 때 유용함.

목적 함수 (Loss Function)

[ \text{Minimize} \quad \sum_{i=1}^{n} (y_i - \hat{y_i})^2 + \lambda \sum_{j=1}^{p} \beta_j^2 ]

  • λ(람다): 정규화 강도 (클수록 가중치를 더 작게 만듦)

✅ Lasso & Ridge 적용 설명

  1. One-Hot Encoding을 통해 범주형 변수를 숫자로 변환 → 다중공선성 문제 가능성 있음.
  2. cv.glmnet()을 이용해 Cross Validation을 수행하여 최적의 λ를 찾음.
  3. 최적의 λ를 사용해 Lasso & Ridge 모델을 학습.
  4. 변수 중요도 확인 후, 변수를 줄여서 다시 모델 학습.

변수 중요도를 반영한 모델 개선

🔹 주요 변수만 선택하여 모델 학습 Lasso를 이용해 중요도가 높은 변수만 유지하고 나머지는 제거합니다.

🔹 코드 수정 방향

  1. Lasso를 이용해 변수 중요도가 높은 변수만 선택.
  2. 선택된 변수를 사용하여 로지스틱 회귀 & 랜덤 포레스트 모델 학습.

로지스틱 회귀 & 랜덤포레스트를 활용한 변수 선택 및 분석

본 글에서는 로지스틱 회귀(Logistic Regression)와 랜덤포레스트(Random Forest) 를 활용하여 중요 변수를 추출하고 모델의 성능을 개선하는 방법을 다룹니다.

1. 데이터 준비 및 전처리

우리는 아래 데이터셋을 사용하여 분석을 진행합니다. 각 Characteristic(특성)은 범주형 변수이며, Complication(합병증 발생 여부)을 종속변수로 설정합니다.

1.1 데이터 로딩 및 변환

# 📌 필요한 라이브러리 로드 library(tidyverse) library(caret) library(randomForest) library(smotefamily) library(fastDummies) library(pROC) library(glmnet) set.seed(300) # 📌 데이터 로딩 data <- read.csv("your_data.csv") # 📌 데이터 전처리 (One-hot Encoding) data_encoded <- dummy_cols(data, select_columns = "Category", remove_first_dummy = TRUE, remove_selected_columns = TRUE) # 📌 Train/Test 데이터 분할 (70:30) set.seed(300) train_index <- createDataPartition(data_encoded$Complication, p = 0.7, list = FALSE) train_data <- data_encoded[train_index, ] test_data <- data_encoded[-train_index, ] # 📌 데이터 정규화 preProcess_model <- preProcess(train_data, method = c("center", "scale")) train_scaled <- predict(preProcess_model, train_data) test_scaled <- predict(preProcess_model, test_data) # 📌 데이터 불균형 해결 (SMOTE 적용) smote_train <- SMOTE(train_scaled[,-1], train_scaled$Complication) train_balanced <- smote_train$data %>% rename(Complication = class) %>% mutate(Complication = as.factor(Complication))

2. 로지스틱 회귀 분석 (Logistic Regression)

먼저 로지스틱 회귀 모델을 사용하여 변수별 유의성(p-value)을 분석합니다. p-value가 0.05 미만인 변수만 선택하여 모델을 개선합니다.

# 📌 로지스틱 회귀 모델 학습 logit_model <- glm(Complication ~ ., family = binomial, data = train_balanced) logit_summary <- summary(logit_model) # 📌 중요 변수 선택 (p-value < 0.05) p_values <- logit_summary$coefficients[, 4] significant_vars <- names(which(p_values < 0.05)) # 📌 Intercept(절편) 제거 significant_vars <- significant_vars[!significant_vars %in% "(Intercept)"] # 📌 선택된 변수 출력 print("로지스틱 회귀에서 선택된 변수:") print(significant_vars)

3. 랜덤포레스트(Random Forest) 변수 중요도 분석

랜덤포레스트 모델을 사용하여 변수 중요도(Feature Importance) 를 평가합니다. Gini 계수 기준으로 상위 10개 변수만 선택합니다.

# 📌 랜덤포레스트 모델 학습 rf_model <- randomForest(Complication ~ ., data = train_balanced, ntree = 500, importance = TRUE) # 📌 변수 중요도 추출 rf_importance <- importance(rf_model) %>% as.data.frame() %>% rownames_to_column("Feature") %>% arrange(desc(MeanDecreaseGini)) # 📌 상위 10개 변수 선택 top_rf_vars <- head(rf_importance$Feature, 10) # 📌 선택된 변수 출력 print("랜덤포레스트에서 선택된 변수:") print(top_rf_vars)

4. 공통 변수 추출 및 모델 개선

로지스틱 회귀와 랜덤포레스트에서 공통적으로 중요하다고 선택된 변수만 남겨서 모델을 다시 학습합니다.

# 📌 공통 변수 선택 selected_vars <- intersect(significant_vars, top_rf_vars) print("최종 선택된 변수 목록:") print(selected_vars) # 📌 선택된 변수만 포함한 데이터셋 생성 train_selected <- train_balanced %>% select(all_of(c("Complication", selected_vars))) test_selected <- test_scaled %>% select(all_of(c("Complication", selected_vars))) # 📌 로지스틱 회귀 모델 재학습 logit_model_selected <- glm(Complication ~ ., family = binomial, data = train_selected) summary(logit_model_selected) # 📌 랜덤포레스트 모델 재학습 rf_model_selected <- randomForest(Complication ~ ., data = train_selected, ntree = 500, importance = TRUE)

5. 모델 성능 평가 (Confusion Matrix & ROC Curve)

최종 선택된 변수를 기반으로 한 모델의 성능을 평가합니다.

# 📌 평가 함수 정의 evaluate_model <- function(model, test_data) { if ("glm" %in% class(model)) { pred_prob <- predict(model, newdata = test_data, type = "response") pred_class <- ifelse(pred_prob > 0.5, 1, 0) } else if ("randomForest" %in% class(model)) { pred_class <- predict(model, newdata = test_data, type = "class") } pred_class <- as.factor(pred_class) actual_class <- as.factor(test_data$Complication) cm <- confusionMatrix(pred_class, actual_class) print(cm) } # 📌 모델 평가 실행 evaluate_model(logit_model_selected, test_selected) evaluate_model(rf_model_selected, test_selected)

6. ROC Curve 및 AUC 확인

AUC 값이 높을수록 모델 성능이 좋음을 의미합니다.

# 📌 로지스틱 회귀 ROC Curve pred_prob_selected <- predict(logit_model_selected, newdata = test_selected, type = "response") roc_curve_selected <- roc(test_selected$Complication, pred_prob_selected) plot(roc_curve_selected, col = "blue", main = "ROC Curve (Selected Features - Logistic Regression)") print(auc(roc_curve_selected)) # 📌 랜덤포레스트 ROC Curve rf_pred_prob_selected <- predict(rf_model_selected, newdata = test_selected, type = "prob")[,2] rf_roc_curve_selected <- roc(test_selected$Complication, rf_pred_prob_selected) plot(rf_roc_curve_selected, col = "red", main = "ROC Curve (Selected Features - Random Forest)") print(auc(rf_roc_curve_selected))

결론 및 개선 방향

💡 변수 선택을 통해 모델의 복잡도를 낮추고, 성능을 개선할 수 있었습니다. 💡 AUC 값이 여전히 낮다면, 새로운 변수 추가 또는 비선형 모델(XGBoost 등) 활용을 고려할 수 있습니다. 💡 SMOTE 비율 조정, 이상치 제거 등의 추가적인 전처리를 적용하면 성능을 더 개선할 수도 있습니다.

🔎 추후 개선 방향:

다른 변수 선택 기법(LASSO, PCA 등) 적용 Decision Tree, XGBoost, ANN 등 다양한 모델 테스트 Feature Engineering을 통한 변수 생성

This post is licensed under CC BY 4.0 by the author.