일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- fastapi를 사용한 파이썬 웹 개발
- 백준
- ARM
- MDP
- Stream
- rao
- BFS
- Widget
- BAEKJOON
- Got
- pytorch
- 영상처리
- Kaggle
- Dreamhack
- study book
- BOF
- Flutter
- bloc
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- DART
- Image Processing
- llm을 활용 단어장 앱 개발일지
- ML
- Computer Architecture
- MATLAB
- Algorithm
- C++
- system hacking
- PCA
- FastAPI
- Today
- Total
Bull
[ML] Ensemble (앙상블) 본문
개념
앙상블 기법은 여러 개의 학습 알고리즘을 조합하여 더 좋은 예측 성능을 얻기 위한 방법이다.
단일 모델만 사용할 때보다 더 안정적이고, 높은 성능을 달성할 수 있다.
즉, 한 명의 전문가 보다 일반인 여러명에서 더 좋은 결과를 낼 수 있다.
주요 Ensemble 알고리즘 종류
1. Bagging (Bootstrap Aggregating)
배깅(Bagging, Bootstrap Aggregating의 약자)은 복원 추출(즉, 한 번 선택된 샘플을 다시 선택할 수 있음)을 통해 여러 개의 데이터셋을 생성하고,
각각의 데이터셋에 대해 독립적으로 모델을 학습시킨 후,
그 결과를 통합하여 최종 결정을 내리는 방법이다.
배깅은 특히 결정 트리(Decision Tree)와 같이 높은 분산을 가지는 알고리즘의 과적합을 줄이는 데 유용하다.
쉽게 설명하자면 같은 데이터들에 대해 조금씩 랜덤하게 복제한 후 여러 그룹으로 모델화하여 각각의 학습 알고리즘으로 분류하여 결합하는 방식이다.
Code
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 가상 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# 배깅 분류기 생성 및 학습
bagging_model = BaggingClassifier(
DecisionTreeClassifier(),
n_estimators=100,
random_state=42
)
bagging_model.fit(X_train, y_train)
# 성능 평가
print(f"Test Accuracy: {bagging_model.score(X_test, y_test):.4f}")
- 20개의 features를 가지고 2개의 클래스로 이루어진 가상의 데이터셋.
- train과 text을 25% 비율.
- 100개의 결정 트리 분류기.
* 여기서 random_state는 시드난수라고 생각하면 된다.
* random forest방식(decision trees)을 배깅에 적용함.
>>> Test Accuracy: 0.8760
2. Voting
Voting은여러 다른 모델의 예측을 결합하는 방법 중 하나로, 각 모델의 예측 결과에 기반해 최종 예측을 결정한다.
Voting 방식은 크게 두 가지로 나뉜다.
Hard Voting: 가장 많은 투표를 받은 클래스를 최종 예측 결과로 선택한다.
즉, 각 모델의 예측 결과 중 다수결로 결정된 클래스를 최종 결과로 한다.
Soft Voting: 각 클래스별로 예측된 확률을 평균내어, 가장 높은 확률을 가진 클래스를 최종 예측 결과로 선택한다.
이 방식은 모델이 예측 확률을 제공할 수 있을 때 사용할 수 있다.
Code(Soft Voting)
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
# 가상 데이터셋 생성
X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 개별 모델 인스턴스 생성
log_clf = LogisticRegression(random_state=42)
rf_clf = RandomForestClassifier(n_estimators=100, random_state=42)
svc_clf = SVC(probability=True, random_state=42)
# VotingClassifier 생성 (soft voting)
voting_clf = VotingClassifier(
estimators=[('lr', log_clf), ('rf', rf_clf), ('svc', svc_clf)],
voting='soft'
)
# Voting Classifier 학습 및 평가
voting_clf.fit(X_train, y_train)
print(f"Test Accuracy: {voting_clf.score(X_test, y_test):.4f}")
*로지스틱 회귀(Logistic Regression), 랜덤 포레스트(Random Forest), 서포트 벡터 머신(Support Vector Machine)을 결합.
- 쉽게 생각하면 LR, RF, SVC가 투표자 인거고 soft voting을 했다고 보면된다.
>>> Test Accuracy: 0.8950
3. Boosting
부스팅은 약한 학습기 여러 개를 순차적으로 학습시키면서,
잘못 예측된 데이터에 대한 가중치를 조절해 가며 모델의 성능을 향상시키는 방법이다.
부스팅은 배깅과 달리 여러 학습기가 순차적으로 오류를 보정해 나가므로 병렬 처리가 어렵지만, 성능이 뛰어나다.
- AdaBoost
에이다부스팅(Adaptive Boosting)은 부스팅의 한 종류로,
이전 학습기가 잘못 분류한 샘플에 더 높은 가중치를 부여하면서 학습기를 순차적으로 학습시키는 방법이다.
각 학습기의 예측 성능에 따라 가중치가 부여되며, 이를 통해 최종적인 모델을 생성한다.
Code(Boosting - AdaBoost)
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 가상 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# AdaBoost 분류기 생성 및 학습
adaboost_model = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1),
n_estimators=100,
random_state=42
)
adaboost_model.fit(X_train, y_train)
# 성능 평가
print(f"Test Accuracy: {adaboost_model.score(X_test, y_test):.4f}")
>>> Test Accuracy: 0.8640
4. Stacking
스태킹은 여러 가지 다른 모델들을 조합하여 새로운 모델을 만드는 방법이다.
기본 모델들의 예측값을 입력으로 하여, 최종 모델(메타 모델)이 최종 예측을 수행한다.
Code
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
# 가상 데이터 생성
X, y = make_classification(n_samples=1000, n_features=20, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# 스태킹 분류기 생성 및 학습
stacking_model = StackingClassifier(
estimators=[
('lr', LogisticRegression()),
('svc', SVC(probability=True)),
('dt', DecisionTreeClassifier())
],
final_estimator=LogisticRegression()
)
stacking_model.fit(X_train, y_train)
# 성능 평가
print(f"Test Accuracy: {stacking_model.score(X_test, y_test):.4f}")
>>> Test Accuracy: 0.8760
'Artificial Intelligence > Machine Learning' 카테고리의 다른 글
[ML] 손실 함수 | study book (0) | 2024.08.10 |
---|---|
[ML] PCA (Principal Component Analysis) 원리 (0) | 2024.07.29 |
[ML] Support Vector Machine(SVM) (7) | 2024.07.22 |
[ML] Hyper Parameters (하이퍼 파라미터) (0) | 2024.03.14 |
[ML] Confusion Matrix (혼동 행렬) (1) | 2024.03.13 |