LightGBM R 패키지 실전 활용: 고성능 예측 모델 구축 가이드

LightGBM 환경 구성 및 설치

CRAN에서 안정적인 버전 설치:

install.packages("lightgbm")

개발 버전 설치 방법:

devtools::install_git("https://github.com/microsoft/LightGBM", subdir = "R-package")

은행 고객 예금 가입 예측 사례

내장 데이터셋을 활용한 이진 분류 실습:

# 데이터 준비
library(lightgbm)
data(bank_data, package = "lightgbm")
target_var <- ifelse(bank_data$subscription == "yes", 1, 0)
features <- data.matrix(bank_data[, c("age", "balance", "duration")])

기본 모델 구축

basic_model <- lightgbm(
  data = features,
  label = target_var,
  params = list(
    objective = "binary",
    num_leaves = 31,
    learning_rate = 0.1,
    metric = "binary_logloss"
  ),
  nrounds = 50
)

고급 모델 튜닝 기법

# 데이터 분할
train_set <- lgb.Dataset(features[1:4000, ], label = target_var[1:4000])
valid_set <- lgb.Dataset(features[4001:nrow(features), ], 
                         label = target_var[4001:length(target_var)])

# 매개변수 설정
model_params <- list(
  objective = "binary",
  num_leaves = 127,
  max_depth = 8,
  learning_rate = 0.05,
  min_data_in_leaf = 50,
  feature_fraction = 0.7
)

# 조기 종료 적용 학습
tuned_model <- lgb.train(
  params = model_params,
  data = train_set,
  valids = list(validation = valid_set),
  nrounds = 500,
  early_stopping_rounds = 30
)

모델 평가 및 해석

# 검증 성능 확인
predictions <- predict(tuned_model, features[4001:nrow(features), ])
auc_score <- pROC::auc(target_var[4001:length(target_var)], predictions)

# 특징 중요도 분석
feature_importance <- lgb.importance(tuned_model, percentage = TRUE)
lgb.plot.importance(feature_importance, top_n = 15)

하이퍼파라미터 최적화

# 그리드 서치 설정
param_grid <- expand.grid(
  num_leaves = c(63, 127, 255),
  learning_rate = c(0.01, 0.05),
  min_data_in_leaf = c(30, 50)
)

# 교차 검증 수행
best_score <- -Inf
optimal_params <- list()

for(i in 1:nrow(param_grid)) {
  cv_result <- lgb.cv(
    params = as.list(param_grid[i, ]),
    data = train_set,
    nrounds = 300,
    nfold = 4,
    early_stopping_rounds = 20
  )
  if(cv_result$best_score > best_score) {
    best_score <- cv_result$best_score
    optimal_params <- as.list(param_grid[i, ])
  }
}

모델 배포

# 모델 저장 및 로드
lgb.save(tuned_model, "lightgbm_model.rds")
deployed_model <- lgb.load("lightgbm_model.rds")

문제 해결 가이드

  • 메모리 부족: max_bin 매개변수 값 축소
  • 과적합: min_data_in_leaf 증가 또는 num_leaves 감소
  • 범주형 특징: lgb.Dataset.set.categorical() 함수 적용
  • 다중 클래스 분류: objective = "multiclass" 및 num_class 설정

태그: LightGBM R 기울기부스팅 머신러닝 이진분류

6월 8일 19:27에 게시됨