파이썬/머신러닝

[분류모델] SVM: Support Vector Machine 개념

토마토농장농장 2022. 6. 6. 11:02

빨간 점 데이터와 초록 점 데이터를 분류하는 초평면을 f(x) 평면이라고 하자. 

이 초평면은 decision boundary라고도 한다.

초평면과의 가장 가까운 포인트, 즉 최단거리가 되는 지점을 support vector라고 하며, 

평면과 각 점 데이터 사이의 거리를 M (margin)이라고 한다. 

분류 알고리즘에 대한 기본 아이디어는 Margin을 적절하게 설정하여 경계선을 찾는 것이 목적이다. 

Margin이 최대가 될 때의 decision boundary가 가장 적절한 구분선이 된다. 

우선 데이터를 정확히 분류하는 범위를 먼저 찾고, 그 범위 안에서 Margin을 최대화하는 구분선을 택한다.

 

* Support Vector :

 

 

 

* SVMβ와 β0를 찾는 과정. 

 

 

*Robustness : 사전적 의미 ; 견고성, 강건성.    로버스트하다; 아웃라이어의 영향을 덜 받는다. 

 

 

* Kernel Trick : 저차원 공간을 고차원 공간으로 매핑해주는 작업.  기존의 저차원에서는 Linear로 구분선을 그릴 수 없을 때, 

고차원으로 변경함으로써 Linear 혹은 구분선을 더 쉽게 그릴 수 있게 해주는 방법. 

 

linear, polynomial, sigmoid, rbf 등의 kernel 기법을 선택할 수 있다.  (default : rbf)

 

 

 

* C : (cost function의 C 값 ) : 에러의 허용범위를 설정.  C가 크면 decision boundary는 더 굴곡지고, C가 작으면 decision boundary는 직선에 가깝다.  분류할 때 얼마나 더 정교하게 구분선을 만들것인가. 

C가 클수록 error를 적게 허용하나 계산시간이 오래 걸린다. C가 너무 작으면 과소적합, C가 너무 크면 과대적합이 될 수 있다

 

* gamma : 곡률. 

 

 

SVM은 노이즈가 많은 데이터셋에서는 오버피팅이 될 수 있다. 노이즈가 많을 경우에는 나이브 베이즈를 사용하는게 오히려 낫다.

 

 

 

[SVM kernel 방식 별 예시]

 

*linearSVC : 하이퍼 파라미터로 cost값 설정. 

model_1 = svm.SVC(kernel='linear', C=1).fit(X, y)
y_pred_1 = model_1.predict(X)

print(model_1.score(X, y))
confusion_matrix(y, y_pred_1)

 

* rbf kernel : radial basis function.  grid search를 이용해서 최적의 cost, gamma를 찾는다. 

 

model_2 = svm.SVC(kernel='rbf', gamma=0.7, C=1).fit(X, y)
y_pred_2 = model_2.predict(X)

print(model_2.score(X, y))
confusion_matrix(y, y_pred_2)

 

*polynomial kernel : 다항 커널. 

model_3 = svm.SVC(kernel='poly', degree=2, gamma="auto", C=1).fit(X,y)
y_pred_3 = model_3.predict(X)

print(model_3.score(X, y))
confusion_matrix(y, y_pred_3)

 

 

 

 

* 시각화 :

def make_meshgrid(x, y, h=.02):
    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    return xx, yy


def plot_contours(ax, clf, xx, yy, **params):
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    out = ax.contourf(xx, yy, Z, **params)
    return out
    
titles = ('1. SVC with linear kernel',
          '2. SVC with RBF(gamma:10, C:1) kernel',
          '3. SVC with RBF(gamma:0.5, C:1) kernel',
          '4. SVC with RBF(gamma:0.5, C:100) kernel',
          '5. SVC with RBF(gamma:0.5, C:100000) kernel',
          '6. SVC with polynomial (degree 3) kernel')
          
          
models = (svm.SVC(kernel='linear', C=1),
          svm.SVC(kernel='rbf', gamma=10, C=1),
          svm.SVC(kernel='rbf', gamma=0.5, C=1),
          svm.SVC(kernel='rbf', gamma=0.5, C=100),
          svm.SVC(kernel='rbf', gamma=0.5, C=100000),
          svm.SVC(kernel='poly', degree=3, gamma='auto', C=1))

models = (model.fit(X, y) for model in models)

fig, sub = plt.subplots(2, 3, figsize=(20, 10))
xx, yy = make_meshgrid(X[:, 0], X[:, 1])

for model, title, ax in zip(models, titles, sub.flatten()):
    plot_contours(ax, model, xx, yy, cmap="rainbow", alpha=0.5)
    ax.scatter(X[:, 0], X[:, 1], c=y, cmap="rainbow", s=20, edgecolors='k')
    ax.set_xlabel('Sepal length')
    ax.set_ylabel('Sepal width')
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title("{}:{}".format(title, np.round(model.score(X, y), 3)))

plt.show()