소개
이 실습에서는 아이리스 데이터셋과 의사결정 트리를 사용하여 아이리스 꽃의 종류를 분류합니다. 먼저 아이리스 데이터셋의 특징 쌍에 대해 학습된 의사결정 트리의 결정 경계를 시각화합니다. 다음으로 아이리스 데이터셋의 모든 특징으로 학습된 단일 의사결정 트리의 구조를 표시합니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.
때때로 Jupyter Notebook 이 완전히 로드되기까지 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.
학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.
아이리스 데이터셋 로드
첫 번째 단계는 scikit-learn 을 사용하여 아이리스 데이터셋을 로드하는 것입니다.
from sklearn.datasets import load_iris
iris = load_iris()
결정 경계 시각화
이제 아이리스 데이터셋의 특징 쌍에 대해 학습된 의사결정 트리의 결정 경계를 시각화합니다.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.inspection import DecisionBoundaryDisplay
## 매개변수
n_classes = 3
plot_colors = "ryb"
plot_step = 0.02
for pairidx, pair in enumerate([[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]):
## 두 개의 대응되는 특징만 사용
X = iris.data[:, pair]
y = iris.target
## 학습
clf = DecisionTreeClassifier().fit(X, y)
## 결정 경계 플롯
ax = plt.subplot(2, 3, pairidx + 1)
plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5)
DecisionBoundaryDisplay.from_estimator(
clf,
X,
cmap=plt.cm.RdYlBu,
response_method="predict",
ax=ax,
xlabel=iris.feature_names[pair[0]],
ylabel=iris.feature_names[pair[1]],
)
## 학습 데이터 포인트 플롯
for i, color in zip(range(n_classes), plot_colors):
idx = np.where(y == i)
plt.scatter(
X[idx, 0],
X[idx, 1],
c=color,
label=iris.target_names[i],
cmap=plt.cm.RdYlBu,
edgecolor="black",
s=15,
)
plt.suptitle("특징 쌍에 대해 학습된 의사결정 트리의 결정 표면")
plt.legend(loc="lower right", borderpad=0, handletextpad=0)
_ = plt.axis("tight")
의사결정 트리 구조 표시
다음으로, 아이리스 데이터셋의 모든 특징으로 학습된 단일 의사결정 트리의 구조를 표시합니다.
from sklearn.tree import plot_tree
plt.figure()
clf = DecisionTreeClassifier().fit(iris.data, iris.target)
plot_tree(clf, filled=True)
plt.title("모든 아이리스 특징으로 학습된 의사결정 트리")
plt.show()
요약
이 실습에서는 의사결정 트리를 사용하여 아이리스 꽃의 종류를 분류했습니다. 먼저 아이리스 데이터셋의 특징 쌍으로 학습된 의사결정 트리의 결정 경계를 시각화했습니다. 다음으로, 아이리스 데이터셋의 모든 특징으로 학습된 단일 의사결정 트리의 구조를 표시했습니다.