
앙상블(Ensemble)
Ensemble Learning
여러개의 머신러닝 모델을 이용해 최적의 답을 찾아내는 기법을 사용하는 모델
test 데이터에 대해 다양한 의견(예측값)을 수렴하기 위해 overfitting(과적합)이 잘 되는 모델을 기본적으로 사용하며, Tree기반 모델(Boosting, RandomForest)을 자주 사용한다.
앙상블은 overfitting(과적합) 감소 효과가 있으며, 개별 모델 성능이 잘 나오지 않을 때 앙상블 학습을 이용하면 성능이 향상될 수 있다.
앙상블 학습의 유형은 보팅(Voting), 배깅(Bagging), 부스팅(Boosting), 스태킹(Stacking)이 있다.
1. 보팅(Voting)
- 서로 다른 알고리즘 model을 조합해서 사용한다.
- 모델에 대해 투표로 결과를 도출한다.
🖥️ 보팅의 유형
- 하드 보팅: 다수결 원칙으로, 예측한 결괏값들 중 다수의 분류기가 결정한 예측값을 최종보팅 결과값으로 선정하는 것.
- 소프트 보팅: 분류기들의 레이블 값 결정 확률을 모두 더하고 이를 평균해서 이들 중 확률이 가장 높은 레이블 값을 최종 보팅 결과값으로 선정한다.
일반적으로 소프트 보팅을 사용
🖥️ 예제
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 개별 모델 생성
logreg_model = LogisticRegression(random_state=42)
svm_model = SVC(probability=True, random_state=42)
# 소프트 보팅 모델 생성
voting_model = VotingClassifier(estimators=[('logreg', logreg_model), ('svm', svm_model)], voting='soft')
# 보팅 모델 학습
voting_model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측
y_pred = voting_model.predict(X_test)
# 정확도 출력
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
2. 배깅(Bagging)
모델을 다양하게 만들기 위해 데이터를 재구성
샘플을 여러번 뽑아(Bootstrap) 각 모델을 학습시켜 결과물 집계 (Aggregration)에 따라서, 학습 데이터가 충분하지 않더라도 충분한 학습효과를 주어 overfitting(과적합)문제를 해결하는데 도움을 준다.
- 같은 알고리즘 내에서 다른 sample조합을 사용.
- 샘플 중복 생성을 통해 결과를 도
🖥️ 예제
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 데이터 불러오기 또는 생성
# X, y = load_data()
# 데이터 분할
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Random Forest 모델 생성
# n_estimators: 생성할 트리의 개수
# max_depth: 각 트리의 최대 깊이
# random_state: 랜덤 시드 값
rf_model = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)
# 모델 학습
rf_model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측
y_pred = rf_model.predict(X_test)
# 정확도 출력
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
3. 스태킹 (Stacking)
스태킹(Stacking)은 여러 다른 기계 학습 모델들의 예측을 결합하여 더 강력하고 안정적인 모델을 만드는 앙상블 기술이다. 스태킹은 다음과 같은 단계로 이루어진다.
- 기본 모델 학습: 여러 다른 기본 모델(첫 번째 수준 모델)을 훈련 데이터로 학습한다.
- 기본 모델 예측: 테스트 데이터에 대한 각 기본 모델의 예측을 생성한다.
- 메타 모델 학습: 기본 모델들의 예측을 입력으로 받아 훈련 데이터에 대한 실제 레이블과 함께 메타 모델(두 번째 수준 모델)을 학습한다.
- 앙상블 예측: 최종 예측은 기본 모델들의 예측을 메타 모델에 입력으로 주어 예측값을 생성한다.
스태킹의 핵심은 다양한 모델들의 예측을 활용하여 보다 강력한 일반화 성능을 얻는 것이다. 기본 모델은 서로 다른 특성을 강조하거나 다른 측면에서 데이터를 이해하기 때문에, 이러한 다양성은 스태킹에서 효과적으로 결합될 수 있습니다.
로지스틱 회귀와 결정 트리 예제
🖥️ 예제
from sklearn.model_selection import train_test_split
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score
# 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 개별 모델 생성
logreg_model = LogisticRegression(random_state=42)
tree_model = DecisionTreeClassifier(random_state=42)
# 스태킹 모델 생성
stacking_model = StackingClassifier(estimators=[('logreg', logreg_model), ('tree', tree_model)], final_estimator=LogisticRegression())
# 스태킹 모델 학습
stacking_model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측
y_pred = stacking_model.predict(X_test)
# 정확도 출력
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
4. 부스팅(Boosting)
부스팅(Boosting)은 여러 약한 학습기(weak learner)를 결합하여 강력한 학습기(strong learner)를 만드는 앙상블 학습 방법입니다. 부스팅은 약한 학습기가 잘못 분류한 샘플에 높은 가중치를 부여하면서 학습을 진행하여, 잘못 분류된 샘플에 집중하여 학습하게 된다.
- AdaBoost (Adaptive Boosting): 이전 모델이 잘못 분류한 샘플에 가중치를 부여하면서 순차적으로 학습한다.
- Gradient Boosting: 이전 모델의 잔여 오차(residual error)에 새로운 모델을 학습시키는 방식으로 동작합니다. 예를 들어, 회귀 문제에서는 이전 예측과 실제 값의 차이를 예측하는 모델을 학습하고, 분류 문제에서는 이전 모델이 분류한 결과와 실제 레이블의 차이를 예측하는 모델을 학습한다.
- XGBoost (eXtreme Gradient Boosting): Gradient Boosting을 기반으로 한 강력한 부스팅 알고리즘으로, 효율적인 구현과 다양한 튜닝 옵션을 제공한다.
- LightGBM: Microsoft에서 개발한 부스팅 알고리즘으로, 대용량 데이터셋과 고차원 데이터에서 효율적으로 동작하도록 설계되었습니다.
부스팅은 일반적으로 과적합에 강하고, 높은 정확도를 달성할 수 있다. 그러나 훈련 시간이 길 수 있고, 모델의 복잡성을 증가시킬 수 있기 때문에 데이터 크기와 복잡성에 따라 적절한 모델을 선택하는 것이 중요합니다.
AdaBoost
🖥️ 예제
from sklearn.ensemble import AdaBoostClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# AdaBoost 모델 생성
adaboost_model = AdaBoostClassifier(n_estimators=50, random_state=42)
# 모델 학습
adaboost_model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측
y_pred = adaboost_model.predict(X_test)
# 정확도 출력
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
LightGBM
import lightgbm as lgb
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# LightGBM 모델 생성 및 학습
lgb_model = lgb.LGBMClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
lgb_model.fit(X_train, y_train)
# 테스트 데이터에 대한 예측
y_pred = lgb_model.predict(X_test)
# 정확도 출력
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)'머신러닝&딥러닝 > 이론' 카테고리의 다른 글
| [머신러닝&딥러닝] 논리회귀(Logistic Regression) (0) | 2024.01.12 |
|---|---|
| [머신러닝&딥러닝] 파이토치 선형회귀-다중 선형 회귀 (0) | 2024.01.11 |
| [머신러닝&딥러닝] 파이토치 선형회귀-단항 선형 회귀 (0) | 2024.01.10 |
| [머신러닝&딥러닝] 파이토치(PyTorch) 주요 함수 (6) | 2024.01.09 |
| [머신러닝&딥러닝] 파이토치(PyTorch) 기초 요소 (0) | 2024.01.08 |