import pandas as pd
data = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/data/ad_click.csv')
data.head()
타겟 변수, 특성 분리 후 데이터 타입 확인
# 타겟 변수와 특성 분리
X = data.drop('Clicked on Ad', axis=1)
y = data['Clicked on Ad']
# 데이터 타입 확인
X.info()
object가 5개 존재
데이터 타입이 object인 컬럼 category로 변경하기
object_cols = [col for col in X.columns if X[col].dtype == 'object']
X[object_cols] = X[object_cols].astype('category')
X.info()
학습 데이터, 검증 데이터 분할
from sklearn.model_selection import train_test_split
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
LGBM 회귀 모델 생성 후 학습
모델 초기화
n_estimators: 모델이 훈련할 트리 수
learning_rate: 예측을 얼마나 수행할지 결정, 높을수록 적은 수의 트리로 학습이 빠르게 이루어질 수 있지만 과적합이 발생할 수 있다.
max_depth: 결정 트리의 최대 깊이
조기 종료 → early_stopping: 주어진 라운드 동안 성능 개선이 없으면 학습 중단
로그 출력 콜백 -> log_evaluation: 지정된 주기마다 평가지표 출력
모델 학습
eval_set: 모델 학습 중 성능 평가를 위한 검증 데이터셋 설정
eval_metrics: 평가 지표 지정
callbacks: 학습 중 특정 작업으로 자동으로 수행할 함수들의 리스트
from lightgbm import LGBMRegressor
from lightgbm.callback import early_stopping, log_evaluation
# 모델 초기화
lgbm = LGBMRegressor(
n_estimators=1000,
learning_rate=0.01,
max_depth=8,
random_state=42
)
# 조기 종료 및 학습 로그 출력 콜백 정의
early_stop = early_stopping(stopping_rounds=15)
log_eval = log_evaluation(period=30)
# 모델 학습
lgbm.fit(
X_train, y_train,
eval_set=[(X_val, y_val)],
eval_metric='rmse',
callbacks=[early_stop, log_eval]
)
# 정확도 출력
print(lgbm.score(X_val, y_val))
평가지표 변화 확인
import lightgbm as lgb
import matplotlib.pyplot as plt
loss_plot = lgb.plot_metric(lgbm.evals_result_, metric='rmse')
plt.show()
피처 중요도 확인
# 최대 피처 수 -> 5개
importance_plot = lgb.plot_importance(lgbm.booster_, max_num_features=5)
plt.show()