본문 바로가기
개발/Python

AdaBoost Hyper Parameters and Attributes

by 피로물든딸기 2025. 11. 22.
반응형

전체 링크

AdaBoost

- 샘플의 가중치를 수정 → 문제를 많이 틀린 학생에게 더 집중해서 가르치기

- 다음 라운드의 모델을 학습할 때 오차가 큰 데이터 포인트의 비중을 높이고, 손실을 최소화하는 모델의 가중치를 구함

- 이전 학습기가 잘못 분류한 샘플에 가중치를 부여, 잔차를 직접 학습하지는 않음.
- weak learner는 랜덤 분류기보다 약간 더 성능이 좋아야 한다.

- 결정 stump(깊이 1의 결정 트리) 를 기본 모델로 사용
- 분류 모델들의 confidence level에 따라 가중합하여 최종 결정을 내린다. (신뢰도에 따라 가중치를 줘서 최종 예측)
- SVM을 내부 모델로 사용할 수 있다. (일반적으로는 Decision Stump = 깊이 1짜리 트리를 사용)

 

장점

- 단일 모델보다 높은 정확도

- 과적합 ↓ : 각 약한 학습기가 단순하여 일반화 성능이 좋음

- Base Estimator을 변경 가능 (SVM, Tree, Linear Model)

 

단점 

- 노이즈에 민감 : 잘못된 라벨을 반복해서 강조하게 되면 성능 저하

- 순차 학습 → 병렬 처리 어려움 → 큰 데이터에서는 학습 속도 느림.

- 결정 stump 같은 단순 모델만 사용할 경우 복잡한 패턴 학습이 어려움 → Gradient, XGB, LightGBM의 등장


하이퍼 파라미터

from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor

AdaBoostClassifier(
    base_estimator=None,
    n_estimators=50,
    learning_rate=1.0,
    algorithm='SAMME.R',
    random_state=None,
)

AdaBoostRegressor(
    base_estimator=None,
    n_estimators=50,
    learning_rate=1.0,
    loss='linear',
    random_state=None,
)

base_estimator

- 부스팅 앙상블을 구성하는 기본 학습기

- 샘플 가중치(sample weighting) 지원이 필요

- None일 경우 DecisionTreeClassifier(max_depth=1)이 기본 모델로 사용

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression

# 1. 데이터 로드
data = load_iris()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 2. 비교할 base_estimator 정의
models = {
    "Decision Tree(depth=1)": DecisionTreeClassifier(max_depth=1),
    "Decision Tree(depth=3)": DecisionTreeClassifier(max_depth=3),
    "SVC": SVC(probability=True, gamma=1.0),
    "Logistic Regression": LogisticRegression(max_iter=200, solver='lbfgs', multi_class='ovr'),    
}

results = {}

# 3. 각 모델을 AdaBoost로 감싸고 학습
for name, base in models.items():
    ada = AdaBoostClassifier(
        base_estimator=base,
        n_estimators=50,
        learning_rate=0.5,        
    )
    ada.fit(X_train, y_train)
    y_pred = ada.predict(X_test)
    results[name] = accuracy_score(y_test, y_pred)

# 4. 결과 출력
for model_name, acc in results.items():
    print(f"{model_name} → Accuracy: {acc:.4f}")

 

n_estimators

- 부스팅 단계 수(트리 개수)

- 만약 완벽하게 학습하는 경우, 학습 과정은 조기에 중단

 

learning_rate

- 각 분류기의 기여도에 곱해지는 학습률

- learning_rate와 n_estimators은 trade-off 존재

 

algorithm

- 'SAMME.R' : 실수(real) Boosting 알고리즘을 사용 (base_estimator가 클래스 확률 계산을 지원)

- 'SAMME' : 이산(discrete) Boosting 알고리즘을 사용

- 일반적으로 SAMME.R이 SAMME보다 더 빠르게 수렴, 더 낮은 테스트 오류를 달성


Attributes

    estimators_ : list of classifiers
        The collection of fitted sub-estimators.

    classes_ : array of shape = [n_classes]
        The classes labels.

    n_classes_ : int
        The number of classes.

    estimator_weights_ : array of floats
        Weights for each estimator in the boosted ensemble.

    estimator_errors_ : array of floats
        Classification error for each estimator in the boosted
        ensemble.

    feature_importances_ : array of shape = [n_features]
        The feature importances if supported by the ``base_estimator``.

 

estimators_

- 학습된 서브(estimator) 모델들의 목록

 

estimator_weights_

- 앙상블 내 각 추정기에 부여된 가중치

 

estimator_errors_

- 앙상블 내 각 추정기의 분류 오류율

 

feature_importances_

- 각 피처의 중요도(importance)

- 값이 클수록 해당 피처가 모델 결정에 중요함

반응형

댓글