가중치가 적용된 서포트 벡터 머신

Beginner

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

소개

이 실습에서는 SVM 에서 가중치가 부여된 데이터셋의 결정 함수를 시각화하는 방법을 배웁니다. 샘플 가중치를 고려하는 모델과 고려하지 않는 모델을 각각 생성하고, 두 모델의 결정 함수를 비교하여 시각화합니다.

VM 팁

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

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

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

라이브러리 가져오기

필요한 라이브러리를 가져오는 것으로 시작합니다.

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

데이터 생성

20 개의 데이터 포인트로 구성된 데이터셋을 생성합니다. 처음 10 개의 포인트는 클래스 1 에 속하고, 마지막 10 개의 포인트는 클래스 -1 에 속합니다.

np.random.seed(0)
X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)]
y = [1] * 10 + [-1] * 10

샘플 가중치 생성

두 가지 샘플 가중치 집합을 생성합니다. 첫 번째 집합은 모든 포인트에 대해 일정하고, 두 번째 집합은 일부 이상치에 대해 더 큰 가중치를 갖습니다.

sample_weight_last_ten = abs(np.random.randn(len(X)))
sample_weight_constant = np.ones(len(X))
sample_weight_last_ten[15:] *= 5
sample_weight_last_ten[9] *= 15

모델 학습

두 개의 SVM 모델을 생성합니다. 첫 번째 모델은 샘플 가중치를 고려하지 않고, 두 번째 모델은 방금 생성한 샘플 가중치를 고려합니다.

clf_no_weights = svm.SVC(gamma=1)
clf_no_weights.fit(X, y)

clf_weights = svm.SVC(gamma=1)
clf_weights.fit(X, y, sample_weight=sample_weight_last_ten)

결정 함수 시각화

방금 생성한 두 모델의 결정 함수를 시각화합니다. 왼쪽에는 첫 번째 모델의 결정 함수를, 오른쪽에는 두 번째 모델의 결정 함수를 표시합니다. 점의 크기는 해당 점의 가중치에 비례합니다.

fig, axes = plt.subplots(1, 2, figsize=(14, 6))

xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500))
Z = clf_no_weights.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

axes[0].contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone)
axes[0].scatter(X[:, 0], X[:, 1], c=y, s=100 * sample_weight_constant, alpha=0.9, cmap=plt.cm.bone, edgecolors="black")
axes[0].axis("off")
axes[0].set_title("일정 가중치")

Z = clf_weights.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

axes[1].contourf(xx, yy, Z, alpha=0.75, cmap=plt.cm.bone)
axes[1].scatter(X[:, 0], X[:, 1], c=y, s=100 * sample_weight_last_ten, alpha=0.9, cmap=plt.cm.bone, edgecolors="black")
axes[1].axis("off")
axes[1].set_title("수정된 가중치")

plt.show()

요약

이 실험에서 SVM 에서 가중치가 부여된 데이터셋의 결정 함수를 시각화하는 방법을 배웠습니다. 샘플 가중치를 고려하는 모델과 고려하지 않는 모델 두 가지를 생성하고, 각 모델의 결정 함수를 시각화하여 비교했습니다.