2025. 12. 15. 20:50ㆍTIL
1. XGBoost와 LightGBM

XGBoost (Extreme Gradient Boosting) : 여러 개의 약한 결정 트리를 순차적으로 학습시키되, 앞 트리의 오류를 다음 트리가 보완하도록 만드는 분류 머신러닝 모델. 이전 Tree에서의 test 데이터와 predicted 데이터의 오차를 다음 Tree의 훈련 데이터에 투입하고, 경사 하강법(gradient descent)을 이용해 오류를 보완한다. 이러한 과정을 반복해 데이터를 분류할 수 있는 최적의 모델을 찾는다. XGBoost는 안정적이고 좋은 성능을 보이지만, 데이터의 양이 많을 경우 속도가 느려진다는 단점이 있다.

LightGBM (Light Gradient Boosting Machine) : 속도, 메모리 효율, 대용량 데이터 처리에 최적화된 분류 머신러닝 모델. 가장 손실 감소량이 큰 leaf node만 선택해서 확장한다. XGBoost처럼 Tree를 계속 전체적으로 확장하는 것은 아니기 때문에 속도는 빠르지만, Tree의 node가 무한정으로 확장될 수 있기 때문에 과적합의 위험이 있다. (따라서 max_depth나 num_leaves parameter들을 이용해 Tree의 깊이를 적절히 제한하는 것이 필요하다.)
실무에서는 XGBoost를 LightGBM보다 많이 쓴다고 한다. (성능 문제가 큰 듯)
2. 라이브러리 불러오기
LabelEncoder : 범주형 변수를 숫자로 바꾸기 위한 encoding
XGBClassifier : XGBoost 모델 불러오기
LGBMClassifier : LightGBM 모델 불러오기
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
3. 데이터 불러오기, Label Encoding하기
Mapping : 분류 대상(종속변수)인 Subscription Status를 0(No), 1(Yes)로 설정
고유값 제거 : Customer ID는 각 행마다 다른 값을 가지는 고유값이기 때문에, 해당 데이터가 모델에 학습되면 잘못된 결과가 일어날 가능성이 높다. 따라서 Customer ID, Name 등과 같은 고유값들은 제거해야 한다.
Label encoding : 범주형 변수를 가진 컬럼들의 데이터를 label encoding
df = pd.read_csv("customer_details.csv")
df["Subscription Status"] = df["Subscription Status"].map({'Yes':1, 'No':0})
df = df.drop(columns=["Customer ID"])
# 범주형 변수를 가진 컬럼들 label encoding
# Label encoding의 특성 상 숫자 순서대로 encoding하기 때문에,
# 머신러닝이 이를 크기로 잘못 인식하여 잘못된 결과를 만들 수 있음.
cat_cols = df.select_dtypes(include="object").columns
le_dict = {}
for col in cat_cols:
le = LabelEncoder()
df[col] = le.fit_transform(df[col])
le_dict[col] = le
4. 독립변수(X), 종속변수(y) 설정 / 데이터셋 분리
X = df.drop(columns=["Subscription Status"])
y = df["Subscription Status"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
5. XGBoost, LightGBM 모델에 적용하기
# XGBoost 모델 적용
# XGBoost 모델 정의
xgb_clf = XGBClassifier(n_estimators=200, learning_rate=0.1, max_depth=3, random_state=42)
# n_estimators : 트리 수
# learning_rate : 한 번에 얼마나 보정할 지
# max_depth : 트리 깊이(복잡도)
xgb_clf.fit(X_train, y_train)
y_pred_xgb = xgb_clf.predict(X_test)
accuracy_score(y_test, y_pred_xgb)
print(classification_report(y_test, y_pred_xgb))

# LightGBM 모델 적용
# LightGBM 모델 정의
lgbm_clf = LGBMClassifier(n_estimators=200, learning_rate=0.1, max_depth=-1, num_leaves=30, random_state=42)
# n_estimators : 트리 수
# learning_rate : 한 번에 얼마나 보정할 지
# max_depth : 트리 깊이(복잡도), -1이면 깊이 제한 없음. 과적합이 발생할 경우, max_depth를 줄여야 한다.
# num_leaves : 리프(leaf) 개수 (복잡도)
lgbm_clf.fit(X_train, y_train)
y_pred_lgbm = lgbm_clf.predict(X_test)
accuracy_score(y_test, y_pred_lgbm)
print(classification_report(y_test, y_pred_lgbm))

'TIL' 카테고리의 다른 글
| 251217_BootCamp Day 43_앞으로의 방향성 (1) | 2025.12.17 |
|---|---|
| 251216_BootCamp Day 42_클러스터링(Clustering) (3) | 2025.12.16 |
| 251212_BootCamp Day 40_분류분석 (0) | 2025.12.12 |
| 251211_BootCamp Day 39_선형회귀 (0) | 2025.12.11 |
| 251210_BootCamp Day 38_기초 통계학 (2) (1) | 2025.12.10 |