의사 결정 트리 후 가지치기

Beginner

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

소개

머신 러닝에서 의사 결정 트리는 일반적으로 사용되는 모델입니다. 그러나 의사 결정 트리는 학습 데이터에 과적합되는 경향이 있어 테스트 데이터에 대한 성능이 저하될 수 있습니다. 과적합을 방지하는 한 가지 방법은 의사 결정 트리를 가지치기하는 것입니다. 비용 복잡도 가지치기는 의사 결정 트리를 가지치기하는 인기 있는 방법입니다. 이 실습에서는 scikit-learn 을 사용하여 의사 결정 트리에 대한 비용 복잡도 가지치기를 보여줍니다.

VM 팁

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

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

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

데이터 로드

scikit-learn 의 유방암 데이터셋을 사용할 것입니다. 이 데이터셋은 30 개의 특징과 환자가 악성 또는 양성 암을 가지고 있는지 여부를 나타내는 이진 목표 변수를 포함합니다.

from sklearn.datasets import load_breast_cancer

X, y = load_breast_cancer(return_X_y=True)

데이터 분할

데이터를 학습 데이터셋과 테스트 데이터셋으로 분할합니다.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

적절한 Alpha 값 결정

의사 결정 트리 가지치기에 사용할 적절한 alpha 값을 결정하고자 합니다. 이는 가지치기된 트리의 효과적인 alpha 값 대비 잎 노드의 총 불순도를 플롯하여 수행할 수 있습니다.

from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt

clf = DecisionTreeClassifier(random_state=0)
path = clf.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas, impurities = path.ccp_alphas, path.impurities

fig, ax = plt.subplots()
ax.plot(ccp_alphas[:-1], impurities[:-1], marker="o", drawstyle="steps-post")
ax.set_xlabel("효과적인 alpha")
ax.set_ylabel("잎 노드의 총 불순도")
ax.set_title("학습 데이터셋의 총 불순도 대 효과적인 alpha")

의사 결정 트리 학습

다음으로, 각 효과적인 alpha 값을 사용하여 의사 결정 트리를 학습합니다. ccp_alphas의 마지막 값은 전체 트리를 가지치기하여 트리가 단 하나의 노드만 남기는 alpha 값입니다.

clfs = []
for ccp_alpha in ccp_alphas:
    clf = DecisionTreeClassifier(random_state=0, ccp_alpha=ccp_alpha)
    clf.fit(X_train, y_train)
    clfs.append(clf)
print(
    "마지막 트리의 노드 수는: {}이며 ccp_alpha 는 {}입니다.".format(
        clfs[-1].tree_.node_count, ccp_alphas[-1]
    )
)

불필요한 트리 제거

의사 결정 트리 목록에서 단 하나의 노드만 있는 불필요한 트리를 제거합니다.

clfs = clfs[:-1]
ccp_alphas = ccp_alphas[:-1]

트리의 노드 수와 깊이 시각화

alpha 값이 증가함에 따라 트리의 노드 수와 깊이를 시각화합니다.

node_counts = [clf.tree_.node_count for clf in clfs]
depth = [clf.tree_.max_depth for clf in clfs]
fig, ax = plt.subplots(2, 1)
ax[0].plot(ccp_alphas, node_counts, marker="o", drawstyle="steps-post")
ax[0].set_xlabel("alpha")
ax[0].set_ylabel("노드 수")
ax[0].set_title("alpha 에 따른 노드 수")
ax[1].plot(ccp_alphas, depth, marker="o", drawstyle="steps-post")
ax[1].set_xlabel("alpha")
ax[1].set_ylabel("트리 깊이")
ax[1].set_title("alpha 에 따른 트리 깊이")
fig.tight_layout()

최적의 Alpha 값 결정

의사 결정 트리 가지치기에 사용할 최적의 alpha 값을 결정합니다. 이를 위해 학습 및 테스트 데이터셋에 대한 정확도와 alpha 값의 관계를 그래프로 나타낼 수 있습니다.

train_scores = [clf.score(X_train, y_train) for clf in clfs]
test_scores = [clf.score(X_test, y_test) for clf in clfs]

fig, ax = plt.subplots()
ax.set_xlabel("alpha")
ax.set_ylabel("정확도")
ax.set_title("학습 및 테스트 데이터셋의 alpha 에 따른 정확도")
ax.plot(ccp_alphas, train_scores, marker="o", label="학습", drawstyle="steps-post")
ax.plot(ccp_alphas, test_scores, marker="o", label="테스트", drawstyle="steps-post")
ax.legend()
plt.show()

요약

이 실습에서는 scikit-learn 을 사용하여 의사 결정 트리에 대한 비용 복잡도 가지치기를 수행하는 방법을 보여주었습니다. 데이터를 학습 및 테스트 데이터셋으로 분할하고, 가지치기에 적절한 alpha 값을 결정했습니다. 효과적인 alpha 값을 사용하여 의사 결정 트리를 학습하고, 트리의 노드 수와 깊이를 시각화했습니다. 또한, 학습 및 테스트 데이터셋의 정확도를 기반으로 가지치기에 사용할 최적의 alpha 값을 결정했습니다.