캐글 회귀 앙상블 Ridge XGBoost 코드 예제
| topics | 100-데이터분석 & AI 101 머신러닝 |
| types | 실습 레퍼런스 |
| contexts | 프로젝트 |
| tags |
캐글 회귀 앙상블 Ridge + XGBoost 코드 예제 및 성능 평가
아래 코드는 주어진 X, Y 데이터(넘파이 배열 혹은 판다스 데이터프레임을 가정)에 대해 릿지(Ridge) 회귀와 **XGBoost 회귀(XGBRegressor)**를 각각 학습시키고, 두 모델의 예측값 평균을 앙상블하여 R2, RMSE, 피어슨 상관계수를 출력하는 가장 기본적인 예제다.
1. 앙상블 코드 예제 (Python)
import numpy as np
from sklearn.linear_model import Ridge
from xgboost import XGBRegressor
from sklearn.metrics import r2_score, mean_squared_error
from scipy.stats import pearsonr
# <span id="x-y-데이터-준비-여기에-실제-데이터-입력"></span>X, Y 데이터 준비 (여기에 실제 데이터 입력)
np.random.seed(42)
X = np.random.rand(100, 5)
Y = np.random.rand(100)
# <span id="모델-정의-및-학습"></span>모델 정의 및 학습
ridge = Ridge()
xgb = XGBRegressor(objective='reg:squarederror', random_state=42)
ridge.fit(X, Y)
xgb.fit(X, Y)
# <span id="예측"></span>예측
ridge_pred = ridge.predict(X)
xgb_pred = xgb.predict(X)
# <span id="앙상블평균"></span>앙상블(평균)
ensemble_pred = (ridge_pred + xgb_pred) / 2
# <span id="성능-평가"></span>성능 평가
r2 = r2_score(Y, ensemble_pred)
rmse = mean_squared_error(Y, ensemble_pred) ** 0.5
pearson_corr, _ = pearsonr(Y, ensemble_pred)
print(f'R2: {r2:.4f}')
print(f'RMSE: {rmse:.4f}')
print(f'피어슨 상관계수: {pearson_corr:.4f}')
주의: 실제 캐글 대회에서는 train/test 분할, 교차검증 등도 반드시 진행한다.
설치: XGBoost 설치가 필요하다: pip install xgboost
2. 주요 지표 설명
| 지표명 | 설명 | 계산 방법 |
|---|---|---|
| R2 | 결정계수, 1에 가까울수록 좋음 | sklearn.metrics.r2_score |
| RMSE | 평균제곱근오차, 낮을수록 좋음 | sklearn.metrics.mean_squared_error 후 sqrt |
| 피어슨 | 예측-정답 상관계수, 1/–1에 가까울수록 강한 상관 | scipy.stats.pearsonr |
3. 참고 자료 및 실전 팁
Ridge, XGBoost에 대한 앙상블과 대표적 평가지표 활용법은 여러 캐글 및 블로그, 공식 문서에서 확인할 수 있다.
성능 개선을 원한다면 그리드 서치, 스태킹 등 다양한 앙상블 기법도 활용한다.
핵심: 이 코드는 앙상블과 성능 평가의 가장 기본적인 골격을 보여준다. 데이터셋 특성에 따라 하이퍼파라미터 튜닝, 교차검증, 예측값 후처리 등을 추가해 실전에 맞게 최적화한다.
- https://www.kaggle.com/code/bashkeel/eda-to-ensemble-model-lasso-ridge-xgboost
- https://velog.io/@kupulau/Regression-model-%EC%BD%94%EB%93%9C
- https://www.kaggle.com/code/abhishek1aa/stacking-ensemble-roberta-xgboost-ridge
- https://riverzayden.tistory.com/17
- https://scikit-learn.org/stable/modules/ensemble.html
- https://www.kaggle.com/code/theintegratedguy/ensemble-regression
- https://blog.csdn.net/weixin_39889597/article/details/110776483
- https://xgboosting.com/xgboost-stable-predictions-via-ensemble-of-final-models/
- https://www.machinelearningmastery.com/xgboost-for-regression/
- https://stackoverflow.com/questions/20115272/calculate-coefficient-of-determination-r2-and-root-mean-square-error-rmse-fo/20115859
- https://jaylala.tistory.com/entry/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D-with-Python-%EC%95%99%EC%83%81%EB%B8%94Ensemble-%ED%95%99%EC%8A%B5-4-XGBoost
- https://www.geeksforgeeks.org/machine-learning/ensemble-methods-in-python/
- https://www.datatechnotes.com/2019/10/accuracy-check-in-python-mae-mse-rmse-r.html
- https://www.youtube.com/watch?v=ujKt3JdI2B8
- https://www.datacamp.com/tutorial/rmse
- https://www.mdpi.com/2079-8954/12/7/254
- https://tyami.github.io/machine%20learning/ensemble-6-boosting-XGBoost-regression/
- https://stackoverflow.com/questions/893657/how-do-i-calculate-r-squared-using-python-and-numpy
- https://www.sciencedirect.com/science/article/abs/pii/S0306261922003555
- https://cloud.google.com/python/docs/reference/bigframes/latest/bigframes.ml.ensemble.XGBRegressor