본문 바로가기

AI

1208 - 서포트백터머신

728x90

딥러닝 기초 - Support Vector Machine 


SVM

from sklearn.svm import SVC
svm = SVC(kernel = 'linear', C = 1.0, random_state=1)
svm.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std,
                      y_combined,
                      classifier = svm,
                      test_idx = range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc = 'upper left')
plt.tight_layout()
plt.show()

SVC 모델, 커널은 선형, 규제 C는 1로 낮게 줬을 때

 

SVM-SGD

from sklearn.linear_model import SGDClassifier

ppn = SGDClassifier(loss='perceptron') # 퍼셉트론
lr = SGDClassifier(loss='log') # 로지스틱회귀
svm = SGDClassifier(loss='hinge') # 소프트백터머신

 

 

소프트백터머신으로 비선형 문제를 해결하기 위해 커널을 사용.

 

RBF커널 SVM으로 XOR 문제 해결하기

# XOR 형태의 데이터셋 생성
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)
X_xor = np.random.randn(200, 2)
y_xor = np.logical_xor(X_xor[:, 0] > 0,
                       X_xor[:, 1] > 0)
y_xor = np.where(y_xor, 1, -1)

plt.scatter(X_xor[y_xor == 1, 0],
            X_xor[y_xor == 1, 1],
            c = 'b',
            marker = 'x',
            label = '1')
plt.scatter(X_xor[y_xor == -1, 0],
            X_xor[y_xor == -1, 1],
            c = 'r',
            marker = 's',
            label = '-1')
plt.xlim([-3, 3])
plt.ylim([-3, 3])
plt.legend(loc = 'best')
plt.tight_layout()
plt.show()

선형으로는 구분할 수 없도록 섞여있음.

 

커널 SVM으로 XOR 데이터셋 학습

svm = SVC(kernel = 'rbf', random_state = 1, gamma = 0.10, C = 10.0)
svm.fit(X_xor, y_xor)
plot_decision_regions(X_xor, y_xor, classifier = svm)
plt.legend(loc = 'upper left')
plt.tight_layout()
plt.show()

커널 SVM 모델이 학습한 XOR 데이터셋의 결정 경계

 

 

감마(𝛾γ)값에 따른 결정 경계 비교

붓꽃 데이터셋에서 RBF 커널 적용

# 감마값을 낮게
svm = SVC(kernel = 'rbf', random_state = 1, gamma = 0.2, C = 1.0)
svm.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std,
                      y_combined,
                      classifier = svm,
                      test_idx = range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc = 'upper left')
plt.tight_layout()
plt.show()

감마값 0.2로 낮게, 러프한 곡선

 

# 감마값을 높게
svm = SVC(kernel = 'rbf', random_state = 1, gamma = 100.0, C = 1.0)
svm.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std,
                      y_combined,
                      classifier = svm,
                      test_idx = range(105, 150))
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.legend(loc = 'upper left')
plt.tight_layout()
plt.show()

감마값을 100으로 높게, 클래스값들 주위로 결정 경계가 매우 가까이

 

알고리즘이 훈련 데이터셋 변화에 너무 민감할때 감마 매개변수가 과대적합 또는 분산을 조절하는데 중요한 역할을 함.

 

 

 

 

GitHub - HonorJay/diary

Contribute to HonorJay/diary development by creating an account on GitHub.

github.com

 

'AI' 카테고리의 다른 글

머신러닝 기초 - 읽어보기  (0) 2021.12.09
1209 - 의사결정나무  (0) 2021.12.09
1207 - 로지스틱회귀  (0) 2021.12.07
1207 - 아달린 SGD  (0) 2021.12.07
1202 - 아달린  (0) 2021.12.02