[데이터처리및분석] SVM 정리 및 실습¶
- SVM(Support Vector Machine)은 지도 학습(Supervised Learning) 알고리즘 중 하나로, 분류(Classification)와 회귀(Regression) 분석에 모두 사용됩니다. 특히, SVM은 이진 분류 문제에서 뛰어난 성능을 발휘하며, 고차원 데이터에서도 효과적으로 작동합니다.
====
SVM의 주요 개념¶
1. 초평면(Hyperplane):¶
- SVM은 데이터를 구분하는 초평면을 찾습니다. 이 초평면은 고차원 공간에서 데이터 포인트를 두 개의 클래스(또는 다수의 클래스)로 나누는 경계선 역할을 합니다.
- 이 초평면은 w⋅x+b=0의 형태를 가지며, 여기서 w는 가중치 벡터, x는 데이터 포인트, b는 절편입니다.
2. 서포트 벡터(Support Vectors):¶
- 서포트 벡터는 초평면에 가장 가까이 위치한 데이터 포인트들로, 이 포인트들은 초평면을 결정하는 데 중요한 역할을 합니다.
- 서포트 벡터와 초평면 사이의 거리를 최대화하는 것이 SVM의 목표입니다.
3. 마진(Margin):¶
- 마진은 두 클래스 간의 간격을 의미합니다. SVM은 마진을 최대화하는 초평면을 찾습니다. 이를 최대 마진 분류(Maximum Margin Classifier)라고 합니다.
- 마진은 서포트 벡터와 초평면 사이의 거리로 정의됩니다.
SVM의 수학적 모델¶
- SVM의 목적은 다음과 같은 제약 조건을 만족하면서 마진을 최대화하는 것입니다:
커널 트릭(Kernel Trick)¶
- SVM은 선형적으로 구분할 수 없는 데이터를 다루기 위해 커널 트릭을 사용합니다. 커널 함수는 저차원 입력 공간을 고차원 특성 공간으로 매핑하여 선형적으로 구분 가능한 형태로 변환합니다. 일반적으로 사용되는 커널 함수는 다음과 같습니다:
- 선형 커널(Linear Kernel)
- 다항 커널(Polynomial Kernel)
- RBF 커널(Radial Basis Function Kernel, 가우시안 커널)
SVM의 장점과 단점¶
장점:¶
- 고차원 데이터에서도 효과적으로 작동합니다.
- 서포트 벡터에 의존하기 때문에 비교적 메모리 효율적입니다.
- 다양한 커널 함수를 통해 비선형 분류 문제도 해결할 수 있습니다.
단점:¶
- 큰 데이터셋에서의 학습 시간이 길어질 수 있습니다.
- 선택한 커널과 매개변수에 따라 성능이 크게 달라질 수 있습니다.
결과 해석이 직관적이지 않을 수 있습니다.
- SVM은 강력한 분류 알고리즘으로, 특히 고차원 데이터와 복잡한 경계를 가진 데이터에서 뛰어난 성능을 발휘합니다. 커널 트릭을 통해 비선형 문제를 해결할 수 있으며, 다양한 응용 분야에서 널리 사용되고 있습니다.
============
1. 데이터 예시 만들기¶
1-1. sklearn의 make_blob 만들기¶
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn');
1-2. 비선형 데이터 로드¶
- make_circles를 이용
from sklearn.datasets import make_circles
X, y = make_circles(100, factor=.1, noise=.1, random_state=0)
2. SVM 학습¶
2-1. SVM 선언 및 fit¶
from sklearn.svm import SVC # "Support vector classifier"
model = SVC(kernel='linear', C=1E10)
model.fit(X, y)
2-2. 비선형적 데이터¶
clf = SVC(kernel='rbf', C=1E6)
clf.fit(X, y)
3. 튜닝¶
3-1. C을 얼마나 줄 것인가.¶
- C를 크게 주면 엄격하게 Decision boundary를 잡고, 작게 잡으면 오류가 많이 생겨도 봐주는 형태로 된다.
============
추가적으로 알아두면 좋을 점¶
- 커널 트릭
Support Vector Machines¶
Appeared in 1990s (originally in 60s), and is still being used in every field of ML. (In early years, performed better than NN) Let's look at high-level.
supervised learning의 세가지
- GMM
- SVM
- PCA
여기서는 SVM을 할 것이고 rbf, polynomial등이 있다.
감마를 크게하면 곡률은 좋아지는데 -> 오버피팅 문제가 있을 수 있다.
SVM에서 C-> '하이퍼 파라미터' : 노이즈를 얼만큼 무시하는지 설정할 수 있다.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
# use seaborn plotting defaults
import seaborn as sns; sns.set()
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=50, centers=2,
random_state=0, cluster_std=0.60)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn');
There's several ways of drawing decision boundary....
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
#plt.plot([0.6], [2.1], 'x', color='red', markeredgewidth=2, markersize=10)
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m * xfit + b, '-k')
plt.xlim(-1, 3.5);
Out of three plot, which is the best one?
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plt.plot([0.6], [2.1], 'x', color='red', markeredgewidth=2, markersize=10)
for m, b in [(1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
plt.plot(xfit, m * xfit + b, '-k')
plt.xlim(-1, 3.5);
새로운 점 x(빨간색) 이 등장한다고 가정할 때, 각기 다른 결과를 보일 것이다. 그렇다면, 어떤 선이 좋일지 고민해볼 필요가 있다. It depends on a new datapoint in red x.... We might have different results. Let's try to find out the best one.
Focus on the Margin!¶
Intuitively, decision boundary should separate two cluster as much as possible. Let's define the margin.
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
yfit = m * xfit + b
plt.plot(xfit, yfit, '-k')
plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='none',
color='#AAAAAA', alpha=0.4)
plt.xlim(-1, 3.5);
Scikit-learn 을 이용한 SVM¶
from sklearn.svm import SVC # "Support vector classifier"
model = SVC(kernel='linear', C=1E10)
model.fit(X, y)
SVC(C=10000000000.0, kernel='linear')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SVC(C=10000000000.0, kernel='linear')
Let''s draw deciision bouundary using SVM in Scikit-learn
def plot_svc_decision_function(model, ax=None, plot_support=True):
"""Plot the decision function for a 2D SVC"""
if ax is None:
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# create grid to evaluate model
x = np.linspace(xlim[0], xlim[1], 30)
y = np.linspace(ylim[0], ylim[1], 30)
Y, X = np.meshgrid(y, x)
xy = np.vstack([X.ravel(), Y.ravel()]).T
P = model.decision_function(xy).reshape(X.shape)
# plot decision boundary and margins
ax.contour(X, Y, P, colors='k',
levels=[-1, 0, 1], alpha=0.5,
linestyles=['--', '-', '--'])
# plot support vectors
if plot_support:
ax.scatter(model.support_vectors_[:, 0],
model.support_vectors_[:, 1],
s=300, linewidth=1, facecolors='none');
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(model,plot_support=False);
def plot_svm(N=10, ax=None):
X, y = make_blobs(n_samples=200, centers=2,
random_state=0, cluster_std=0.60)
X = X[:N]
y = y[:N]
model = SVC(kernel='linear', C=1E10)
model.fit(X, y)
ax = ax or plt.gca()
ax.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
ax.set_xlim(-1, 4)
ax.set_ylim(-1, 6)
plot_svc_decision_function(model, ax)
fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
for axi, N in zip(ax, [60, 120]):
plot_svm(N, axi)
axi.set_title('N = {0}'.format(N))
Non-linear 한 decision boundary¶
Why SVM is powerful?
Another strength of SVM is the kernal function. (we can have non linearlity)
from sklearn.datasets import make_circles
X, y = make_circles(100, factor=.1, noise=.1, random_state=0)
clf = SVC(kernel='linear').fit(X, y)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(clf, plot_support=False);
linear 한 decision boundary는 두 점들을 잘 구분하지 못한다.
Let's use RBF kernel을 and repeat !
clf = SVC(kernel='rbf', C=1E6)
clf.fit(X, y)
SVC(C=1000000.0)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
SVC(C=1000000.0)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(clf)
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
s=300, lw=1, facecolors='none');
What about this case?¶
X, y = make_blobs(n_samples=100, centers=2,
random_state=0, cluster_std=1.2)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn');
X, y = make_blobs(n_samples=100, centers=2,
random_state=0, cluster_std=0.8)
fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
for axi, C in zip(ax, [10.0, 0.1]):
model = SVC(kernel='linear', C=C).fit(X, y)
axi.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(model, axi)
axi.scatter(model.support_vectors_[:, 0],
model.support_vectors_[:, 1],
s=300, lw=1, facecolors='none');
axi.set_title('C = {0:.1f}'.format(C), size=14)
'Learn' 카테고리의 다른 글
[논문리뷰] 이해가 안되는 논문 해결 법 : 묻고 더블로 가 (0) | 2024.06.26 |
---|---|
[데이터처리와분석] GMM EM Algorithm (1) | 2024.06.13 |
[컴퓨터비전] Fast-RCNN (1) | 2024.06.13 |
[데이터처리와 분석] K-Mean 실습 및 확인 (0) | 2024.06.13 |
[컴퓨터비전] R-CNN (0) | 2024.06.13 |