트리 앙상블을 이용한 특징 변환

Beginner

This tutorial is from open-source community. Access the source code

소개

이 실습에서는 트리 앙상블을 사용하여 특징을 고차원의 희소 공간으로 변환하는 방법을 배우게 됩니다. 그런 다음 이러한 특징에 선형 모델을 학습시킵니다. 랜덤 포레스트와 그래디언트 부스팅을 포함한 다양한 앙상블 방법을 사용하고 성능을 비교할 것입니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.

때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

데이터 준비

먼저 80,000 개의 샘플로 구성된 대규모 데이터셋을 만들고 세 개의 집합으로 분할합니다.

  • 나중에 특징 공학 변환기로 사용되는 앙상블 방법을 학습시키기 위한 집합
  • 선형 모델을 학습시키기 위한 집합
  • 선형 모델을 테스트하기 위한 집합
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=80_000, random_state=10)

X_full_train, X_test, y_full_train, y_test = train_test_split(
    X, y, test_size=0.5, random_state=10
)

X_train_ensemble, X_train_linear, y_train_ensemble, y_train_linear = train_test_split(
    X_full_train, y_full_train, test_size=0.5, random_state=10
)

앙상블 방법 학습

각 앙상블 방법에 대해 10 개의 추정자와 최대 깊이 3 단계를 사용합니다.

from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier

n_estimators = 10
max_depth = 3

random_forest = RandomForestClassifier(
    n_estimators=n_estimators, max_depth=max_depth, random_state=10
)
random_forest.fit(X_train_ensemble, y_train_ensemble)

gradient_boosting = GradientBoostingClassifier(
    n_estimators=n_estimators, max_depth=max_depth, random_state=10
)
_ = gradient_boosting.fit(X_train_ensemble, y_train_ensemble)

임베딩 변환기 학습

RandomTreesEmbedding은 비지도 학습 방법으로 별도로 학습할 필요가 없습니다.

from sklearn.ensemble import RandomTreesEmbedding

random_tree_embedding = RandomTreesEmbedding(
    n_estimators=n_estimators, max_depth=max_depth, random_state=0
)

rt_model = make_pipeline(random_tree_embedding, LogisticRegression(max_iter=1000))
rt_model.fit(X_train_linear, y_train_linear)

랜덤 포레스트와 그래디언트 부스팅을 이용한 특징 변환

이제 위의 임베딩을 전처리 단계로 사용하는 두 개의 파이프라인을 생성합니다. 특징 변환은 apply 메서드를 호출하여 수행됩니다. 그런 다음 랜덤 포레스트 또는 그래디언트 부스팅을 로지스틱 회귀와 파이프라인으로 연결합니다. 하지만 scikit-learn 의 파이프라인은 transform 호출을 기대하므로 apply 호출을 FunctionTransformer로 감쌌습니다.

from sklearn.preprocessing import FunctionTransformer
from sklearn.preprocessing import OneHotEncoder

def rf_apply(X, model):
    return model.apply(X)

rf_leaves_yielder = FunctionTransformer(rf_apply, kw_args={"model": random_forest})

rf_model = make_pipeline(
    rf_leaves_yielder,
    OneHotEncoder(handle_unknown="ignore"),
    LogisticRegression(max_iter=1000),
)
rf_model.fit(X_train_linear, y_train_linear)

def gbdt_apply(X, model):
    return model.apply(X)[:, :, 0]

gbdt_leaves_yielder = FunctionTransformer(
    gbdt_apply, kw_args={"model": gradient_boosting}
)

gbdt_model = make_pipeline(
    gbdt_leaves_yielder,
    OneHotEncoder(handle_unknown="ignore"),
    LogisticRegression(max_iter=1000),
)
gbdt_model.fit(X_train_linear, y_train_linear)

모델 평가

이제 모든 모델의 ROC 곡선을 보여줄 수 있습니다.

import matplotlib.pyplot as plt
from sklearn.metrics import RocCurveDisplay

fig, ax = plt.subplots()

models = [
    ("RT embedding -> LR", rt_model),
    ("RF", random_forest),
    ("RF embedding -> LR", rf_model),
    ("GBDT", gradient_boosting),
    ("GBDT embedding -> LR", gbdt_model),
]

model_displays = {}
for name, pipeline in models:
    model_displays[name] = RocCurveDisplay.from_estimator(
        pipeline, X_test, y_test, ax=ax, name=name
    )
_ = ax.set_title("ROC curve")

요약

이 실험에서 우리는 트리 앙상블을 사용하여 특징을 고차원의 희소 공간으로 변환하는 방법을 배웠습니다. 랜덤 포레스트와 그래디언트 부스팅과 같은 다양한 앙상블 방법을 사용하고 성능을 비교했습니다. RandomTreesEmbedding은 비지도 학습 방법으로 별도로 학습할 필요가 없습니다. 또한 FunctionTransformer를 사용하여 랜덤 포레스트 또는 그래디언트 부스팅을 로지스틱 회귀와 파이프라인으로 연결하는 방법을 배웠습니다. 마지막으로 ROC 곡선을 사용하여 모든 모델의 성능을 평가했습니다.