소개
이 실습에서는 Scikit-Learn 의 SGDClassifier 를 사용하여 유명한 iris 데이터셋에 대한 다중 클래스 분류 모델을 구현합니다. 모델의 결정 경계면을 데이터셋에 플롯하고, 세 개의 일대일 (OVA) 분류기에 해당하는 초평면을 시각화합니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습을 위한 Jupyter Notebook에 접근합니다.
때때로 Jupyter Notebook 이 로드되는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.
학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.
데이터 로드 및 준비
필요한 라이브러리를 가져오고 iris 데이터셋을 로드하여 시작합니다. 그런 다음 데이터를 섞고 표준화하여 학습에 사용할 준비를 합니다.
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import SGDClassifier
## iris 데이터셋 로드
iris = datasets.load_iris()
## 처음 두 개의 특징 가져오기
X = iris.data[:, :2]
y = iris.target
colors = "bry"
## 데이터 섞기
idx = np.arange(X.shape[0])
np.random.seed(13)
np.random.shuffle(idx)
X = X[idx]
y = y[idx]
## 데이터 표준화
mean = X.mean(axis=0)
std = X.std(axis=0)
X = (X - mean) / std
모델 학습
이제 fit() 메서드를 사용하여 iris 데이터셋에 대한 SGDClassifier 모델을 학습합니다. 이 메서드는 입력 데이터와 대상 값을 입력으로 받아 주어진 데이터로 모델을 학습시킵니다.
clf = SGDClassifier(alpha=0.001, max_iter=100).fit(X, y)
결정 경계 시각화
이제 학습된 모델의 결정 경계를 iris 데이터셋에서 시각화합니다. DecisionBoundaryDisplay 클래스를 사용하여 모델의 결정 경계를 시각화합니다.
from sklearn.inspection import DecisionBoundaryDisplay
ax = plt.gca()
DecisionBoundaryDisplay.from_estimator(
clf,
X,
cmap=plt.cm.Paired,
ax=ax,
response_method="predict",
xlabel=iris.feature_names[0],
ylabel=iris.feature_names[1],
)
plt.axis("tight")
학습 데이터 포인트 플롯
이제 결정 경계 위에 학습 데이터 포인트를 플롯합니다. 서로 다른 대상 값에 대해 서로 다른 색상으로 학습 데이터 포인트를 플롯하기 위해 scatter() 메서드를 사용합니다.
for i, color in zip(clf.classes_, colors):
idx = np.where(y == i)
plt.scatter(
X[idx, 0],
X[idx, 1],
c=color,
label=iris.target_names[i],
cmap=plt.cm.Paired,
edgecolor="black",
s=20,
)
plt.title("다중 클래스 SGD 의 결정 경계")
plt.axis("tight")
일대일 분류기 플롯
이제 결정 경계 위에 세 개의 일대일 (OVA) 분류기를 플롯합니다. 훈련된 모델의 coef* 및 intercept* 속성을 사용하여 OVA 분류기에 해당하는 초평면을 플롯합니다.
xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
coef = clf.coef_
intercept = clf.intercept_
def plot_hyperplane(c, color):
def line(x0):
return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]
plt.plot([xmin, xmax], [line(xmin), line(xmax)], ls="--", color=color)
for i, color in zip(clf.classes_, colors):
plot_hyperplane(i, color)
plt.legend()
plt.show()
요약
이 실습에서는 Scikit-Learn 의 SGDClassifier 를 사용하여 아이리스 데이터셋에 대한 다중 클래스 분류 모델을 구현하는 방법을 배웠습니다. 훈련된 모델의 결정 경계를 데이터셋에 시각화하고, 세 개의 일대일 (OVA) 분류기에 해당하는 초평면을 플롯했습니다.