미식가의 개발 일기

[머신러닝] 동일 모델을 반복 학습하는 앙상블(부스팅, 시드 앙상블, KFold 앙상블) 본문

ML, DL

[머신러닝] 동일 모델을 반복 학습하는 앙상블(부스팅, 시드 앙상블, KFold 앙상블)

대체불가 핫걸 2024. 7. 31. 12:43
앙상블이란?
"여러 학습 알고리즘을 결합하여 더 나은 성능을 얻는 머신러닝 기법"

이 중에서도 이 포스팅에서는 동일 모델을 반복 학습하는 형태를 살펴볼 것이다. 

 

 

※ 앙상블 전체 개념에 대해 학습하고 싶다면 아래 포스팅을 먼저 읽고 오는 것을 추천한다.

 

[머신러닝] 앙상블

앙상블이란?"여러 모델의 예측 결과들을 종합해 정확도를 높이는 기법이다"(단 각 모델 간의 상호 연관성이 낮아야 정확도가 높아진다.) 보팅(Voting)동일한 데이터셋에 서로 다른 종류의 모델의

irreplaceablehotgirl.tistory.com

 

부스팅(Boosting)

여러 약한 학습기를 결합하여 강력한 학습기를 만드는 기법

 

 

[머신러닝] LightGBM과 Gradient Boosting(광고 클릭 예측하기 with 캐글)

캐글 -> DataSets -> Click Through Rate csv 파일 다운로드 후 실습 진행Gradient Boosting이란?앙상블 학습(여러 개의 모델을 결합해 더 나은 성능을 얻는 기법) 방법의 하나로 예측 정확도를 높이기 위해 여러

irreplaceablehotgirl.tistory.com

 

 

 

시드 앙상블(Seed Ensemble)

동일한 모델을 각각 다른 무작위 시드 값을 사용하여 학습한 후 예측 값을 평균내어 최종 예측 값을 얻는 기법  
  • 데이터 로드 후 전처리와 학습, 검증 데이터는 모두 분리 되었다고 가정 
import numpy as np
from sklearn.ensemble import RandomForestRegressor

predictions = []
seeds = [10, 20, 30, 42, 50]

# 시드 앙상블 사용
for seed in seeds:
    seed_model = RandomForestRegressor(n_estimators = 20, random_state = seed)
    seed_model.fit(X_train, y_train)
    seed_predict = seed_model.predict(X_valid)
    predictions.append(seed_predict)
    
seed_predict = np.mean(predictions, axis = 0)

 

 

 

KFold 앙상블(KFold Ensemble)

교차 검증을 통해 여러 모델을 훈련시키고 예측을 결합하는 기법
import numpy as np
from sklearn.model_selection import KFold
from sklearn.ensemble import GradientBoostingRegressor

kf = KFold(n_splits=5, shuffle=True, random_state=42)

models = []

# KFold를 사용한 앙상블 
drop_train = train.drop([...학습에 사용하지 않을 컬럼들...], axis = 1)

for train_idx, valid_idx in kf.split(drop_train):
    X_train, X_valid = drop_train.iloc[train_idx], drop_train.iloc[valid_idx]
    y_train, y_valid = target.iloc[train_idx], target.iloc[valid_idx]

    # 모델 초기화 및 학습
    model = GradientBoostingRegressor(n_estimators=10, random_state=42)
    model.fit(X_train, y_train)

    y_pred = model.predict(X_valid)

    models.append(model)

 

→ models에 담긴 model값들을 평균내거나 가중치를 부여하여 다양한 예측값을 얻을 수 있고, 성능을 비교하여 최적의 모델을 찾을수도 있다.

반응형