앙상블: 일련의 예측기(한 개 아님!)
앙상블 학습: 일련의 예측기로부터 예측을 수집하여 더 나은 예측을 하는 것
앙상블 메소드: 앙상블 학습 알고리즘
hard voting(직접 투표): 여러 분류기의 예측을 집계하여, 가장 많이 나온 예측을 최종 예측으로 함(다수결 표)
voting_clf = VotingClassifier(
estimators=[
('lr', LogisticRegression(random_state=42)),
('rf', RandomForestClassifier(random_state=42)),
('svc', SVC(random_state=42))
]
)
voting_clf.fit(X_train, y_train)
VotingClassifier는 모든 추정기를 복제하여 복제된 추정기를 훈련함estimators 속성: 원본 추정기가 저장되는 곳estimators_: 훈련된 복제본named_estimators나 named_estimators: 리스트 대신 딕셔너리를 전달하는 경우predict로 예측하고 score를 통해 성능(점수)을 확인할 수 있음soft voting(간접 투표): predict_proba() 메소드와 같이 분류기의 확률을 예측할 수 있다면, 개별 분류기의 예측을 평균 내어 확률이 가장 높은 클래스를 예측하는 방법
voting 매개변수를 soft로 바꾸면 됨voting_clf.voting = "soft"
# SVC는 클래스 확률을 기본적으로 제공하지 않으므로 따로 지정해줘야 함
voting_clf.named_estimators["svc"].probability = True
앞에서 서로 다른 알고리즘을 사용한 앙상블을 만드는 것이 서로 다른 오차를 내기 때문에 더 나은 성능을 보일 수 있다고 했음. 이번에는 같은 알고리즘을 사용하는 대신 훈련 세트의 subset을 랜덤으로 구성하여 분류기를 서로 다르게 학습시키는 방법을 사용한다고 함. (완전히 동일한 데이터가 아니라 훈련 세트에서 subset을 나눠서 훈련하는 거라 괜찮은 건가?)
bagging: bootstrap aggregating의 줄임말. 훈련 세트에서 중복을 허용하여 샘플링하는 방식
pasting: 중복을 허용하지 않고 샘플링하는 방식
BaggingClassifier, 회귀는 BaggingRegressor로!bootstrap=False로 지정해야 함n_jobs: CPU 코어 수 지정, -1은 모든 코어를 사용한다는 것bag_clf = BaggingClassifier(DecisionTreeClassifier(), n_estimators=500, max_samples=100, n_jobs=-1, random_state=42)
bag_clf.fit(X_train, y_train)
oob_score=True로 지정하기bag_clf = BaggingClassifier(DecisionTreeClassifier(), n_estimators=500, oob_score=True, n_jobs=-1, random_state=42)
# 점수 확인
bag_clf.oob_score_
# 기반 예측기가 predict_proba()를 가지는 경우. 아래와 같이 클래스 별 확률 확인 가능
bag_clf.oob_decision_function[:3]
BaggingClassifier는 앞에서 샘플을 조정하는 max_samples, bootstrap 말고도 특성을 샘플링하는 max_features, bootstrap_features가 있음! 특성 샘플링은 더 다양한 예측기를 만들며 편향을 늘리는 대신 분산을 줄임
Random patches method: 훈련 특성과 샘플을 모두 샘플링
Random subspaces method: 훈련 샘플은 모두 사용(bootstrap=False, max_samples=1.0), 특성만 샘플링bootstrap_features=True, max_features은 1.0보다 작게)
max_sample를 훈련 세트의 크기로 지정rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
rnd_clf.fit(X_train, y_train)
y_pred_rf = rnd_clf.predict(X_test)
ExtraTreesClassifier를 사용약한 학습기를 여러 개 연결하여 강한 학습기를 만드는 것. 앞의 모델을 보완하며 순차적으로 예측기를 학습시키는 것
수식 메모
각 샘플의 가중치 =
으로 초기화
j번째 예측기 학습 후 가중치가 적용된 오차율 =
-> : i번째 샘플에 대한 예측()과 실제값()이 다른 경우
-> 이 경우 가중치의 합을 전체 가중치의 합으로 나누므로 오차율이라고 함!
예측기의 가중치 =
-> : 학습률, 기본값=1
-> 예측이 정확하면 는 증가하며 양수임. 랜덤 예측인 경우 는 0에 가까움. 예측이 이보다 더 나쁘면 는 음수
가중치 업데이트 규칙
-> 예측기 학습 및 업데이트 과정은 전체 예측기 수 또는 지정된 예측기의 수만큼 반복 후 종료됨
Adaboost의 최종 예측
-> : 클래스
-> 모든 예측기()의 예측을 계산하고, 예측기 가중치 를 더하여 최종 예측 결과인 를 만듦. arg max k로 나와 있으므로 가중치 합이 가장 큰 클래스의 인자(argument)가 이 되는 것을 알 수 있음!
ada_clf = AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1), n_estimators=30, learning_rate=0.5, random_state=42)
ada_clf.fit(X_train, y_train)
As shown above, Tree1 is trained using the feature matrix X and the labels y. The predictions labeled y1(hat) are used to determine the training set residual errors r1. Tree2 is then trained using the feature matrix X and the residual errors r1 of Tree1 as labels. The predicted results r1(hat) are then used to determine the residual r2. The process is repeated until all the M trees forming the ensemble are trained.
There is an important parameter used in this technique known as Shrinkage. Shrinkage refers to the fact that the prediction of each tree in the ensemble is shrunk after it is multiplied by the learning rate(eta) which ranges between 0 to 1.
There is a trade-off between eta and the number of estimators, decreasing learning rate needs to be compensated with increasing estimators in order to reach certain model performance.
After all trees being trained, predictions can be made. Each tree predicts a label and the final prediction is given by the formula:
y(pred) = y1 + (eta * r1) + (eta * r2) + ....... + (eta * rN)
출처: https://www.geeksforgeeks.org/ml-gradient-boosting/
gbrt_best = GradientBoostingRegressor(
max_depth=2, learning_rate=0.05, n_estimators=500, n_iter_no_change=10, random_state=42)
n_iters_no_change=10: 마지막 10개의 트리가 도움이 되지 않는 경우 훈련을 자동으로 중지subsample=0.25: 각 트리는 랜덤으로 선택된 25%의 훈련 샘플로 학습 -> stochastic GD(Histogram-based gradient boosting 내용 생략)
The idea is that you can attack a learning problem with different types of models which are capable to learn some part of the problem, but not the whole space of the problem.
So, you can build multiple different learners and you use them to build an intermediate prediction, one prediction for each learned model. Then you add a new model which learns from the intermediate predictions the same target.
How stacking works?
출처: https://www.geeksforgeeks.org/stacking-in-machine-learning/
stacking_clf = StackingClassifier(
estimators=[
('lr': LogisisticRegression(random_state=42)),
('rf': RandomForestClassifier(random_state=42)),
('svc': SVC(probability=True, (random_state=42))
],
final_estimator=RandomForestClassifier(random_state=42), cv=5 # 교차 검증 폴드 수
)