선형 서포트 벡터 머신(Support Vector Machine : SVM)

선형 분류 알고리즘에서는 다음의 두 모델이 가장 널리 알려져 있다. (둘다 분류 알고리즘이기에 LinearRegression과 같은 회귀 알고리즘과 혼동하지 말자)

로지스틱 회귀(Logistic Regression)

선형 서포트 벡터 머신(Support Vector Machine : SVM)

  1. 클래스들이 선형 경계에 의해 분리될 수 있는 데이터만을 요구하기 때문에 대부분의 데이터에 적용될 수 없다.

  2. 결정 영역의 초평면을 둘러싸고 있는 margin을 최대화 시킨다.

1
2
from IPython.display import Image  # 주피터 노트북에 이미지 삽입
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211127_035302_1.png")

output_2_0

  • 참고사이트 : https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=sanghan1990&logNo=221136368529
1
2
from IPython.display import Image  # 주피터 노트북에 이미지 삽입
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211127_040933_1.png")

output_4_0

  • 참고사이트 :https://jeongmin-lee.tistory.com/87

SVM은 최대 마진(이동 폭)을 갖는 경계를 찾는 것이 SVM알고리즘의 기본 아이디어이다.

최대 마진으로 경계를 생성하면 과적합의 문제가 적고 일반화의 특성이 좋아진다.

SVM은 기본적으로 이진 분류(Binary classification)를 수행하지만, 다중분류(multi-class classification)도 가능하다.

다중분류를 수행할 경우 class 한 개와 나머지로 이진 분류하고, 나머지 class에 또 이진 분류를 적용하는 방식을 사용한다.

SVM은 선형과 비선형으로 나뉘게 된다.

1
2
from IPython.display import Image  # 주피터 노트북에 이미지 삽입
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211129_184747_1.png")

output_7_0

SVM을 이용하여 iris데이터 학습 (Linear SVM & multi-class classification)

1
!pip install mglearn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Collecting mglearn

WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -onlpy (c:\users\mycom\appdata\roaming\python\python38\site-packages)
WARNING: Ignoring invalid distribution -pype1 (c:\users\mycom\anaconda3\lib\site-packages)
WARNING: Ignoring invalid distribution -ensorflow-gpu (c:\users\mycom\anaconda3\lib\site-packages)



  Downloading mglearn-0.1.9.tar.gz (540 kB)
Requirement already satisfied: numpy in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (1.19.5+vanilla)
Requirement already satisfied: matplotlib in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (3.4.2)
Requirement already satisfied: scikit-learn in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (0.24.1)
Requirement already satisfied: pandas in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (1.3.1)
Requirement already satisfied: pillow in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (8.3.1)
Requirement already satisfied: cycler in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (0.10.0)
Requirement already satisfied: imageio in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (2.9.0)
Requirement already satisfied: joblib in c:\users\mycom\anaconda3\lib\site-packages (from mglearn) (1.0.1)
Requirement already satisfied: six in c:\users\mycom\anaconda3\lib\site-packages (from cycler->mglearn) (1.15.0)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\mycom\anaconda3\lib\site-packages (from matplotlib->mglearn) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\mycom\anaconda3\lib\site-packages (from matplotlib->mglearn) (1.3.1)
Requirement already satisfied: pyparsing>=2.2.1 in c:\users\mycom\anaconda3\lib\site-packages (from matplotlib->mglearn) (2.4.7)
Requirement already satisfied: pytz>=2017.3 in c:\users\mycom\anaconda3\lib\site-packages (from pandas->mglearn) (2021.1)
Requirement already satisfied: threadpoolctl>=2.0.0 in c:\users\mycom\anaconda3\lib\site-packages (from scikit-learn->mglearn) (2.2.0)
Requirement already satisfied: scipy>=0.19.1 in c:\users\mycom\anaconda3\lib\site-packages (from scikit-learn->mglearn) (1.6.2)
Building wheels for collected packages: mglearn
  Building wheel for mglearn (setup.py): started
  Building wheel for mglearn (setup.py): finished with status 'done'
  Created wheel for mglearn: filename=mglearn-0.1.9-py2.py3-none-any.whl size=582638 sha256=335ff9e067fd4eaed0b63263e1124b31abf0637a20bf52ac735209ea6bb14656
  Stored in directory: c:\users\mycom\appdata\local\pip\cache\wheels\87\75\37\404e66d0c4bad150f101c9a0914b11a8eccc2681559936e7f7
Successfully built mglearn
Installing collected packages: mglearn
Successfully installed mglearn-0.1.9
1
2
3
4
5
6
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
import mglearn
%matplotlib inline
1
2
3
iris = load_iris()


1
2
3
# 시각화를 위해서 sepal length와 width만 사용한다.
x = iris['data'][:, [0,1]] # column 0과 1만 사용
y = iris['target']
1
2
3
4
# train 데이터 세트와 test 데이터 세트를 구성한다.
trainX, testX, trainY, testY = \
    train_test_split(x, y, test_size=0.2)

1
2
3
# SVM으로 Train 데이터 세트를 학습한다.
svm = SVC(kernel='linear')
svm.fit(trainX, trainY)
1
SVC(kernel='linear')
1
2
3
# 정확도를 계산한다.
print('학습용 데이터로 측정한 정확도 = %.2f' % svm.score(trainX, trainY))
print('시험용 데이터로 측정한 정확도 = %.2f' % svm.score(testX, testY))
1
2
학습용 데이터로 측정한 정확도 = 0.82
시험용 데이터로 측정한 정확도 = 0.83
1
2
3
4
5
6
7
8
# 시각화
plt.figure(figsize=(8, 5))
mglearn.plots.plot_2d_classification(svm, trainX, alpha=0.1)
mglearn.discrete_scatter(trainX[:,0], trainX[:,1], trainY)
plt.legend()
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.show()

output_16_0

SVM을 이용하여 iris데이터 학습 (Non-linear SVM & multi-class classification)

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
import mglearn
import numpy as np
from tqdm import tqdm_notebook
1
2
3
4
iris = load_iris()

x = iris.data
y = iris.target
1
2
3
4
# train 데이터 세트와 test 데이터 세트를 구성한다.
trainX, testX, trainY, testY = \
    train_test_split(x, y, test_size=0.2)

  • RBF 커널은 가장 일반적인 형태의 커널 화이며 가우스 분포와 유사하기 때문에 가장 널리 사용되는 커널 중 하나입니다. 두 점 X₁ 및 X₂에 대한 RBF 커널 함수는 유사성 또는 서로 얼마나 가까운지를 계산합니다. 이 커널은 다음과 같이 수학적으로 나타낼 수 있습니다.

  • 참고사이트 : https://ichi.pro/ko/bangsahyeong-gijeo-hamsu-rbf-keoneol-idong-keoneol-190150318258570

1
2
from IPython.display import Image  # 주피터 노트북에 이미지 삽입
Image("C://Users/MyCom/jupyter-tutorial/수업자료/data/20211129_194434_1.png")

output_22_0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# gamma와 C의 조합을 바꿔가면서 학습 데이터의 정확도가 최대인 조합을 찾는다.
optAcc = -999
optG = 0
optX =0
for gamma in tqdm_notebook(np.arange(0.1, 5.0, 0.1)):
    for c in np.arange(0.1, 5.0, 0.1):
        model = SVC(kernel='rbf', gamma=gamma, C=c)
        model.fit(trainX, trainY)
        acc = model.score(testX, testY)

        if acc > optAcc:
            optG = gamma
            optC = c
            optAcc = acc

print('optG = %.2f' % optG)
print('optC = %.2f' % optC)
print('optAcc = %.2f' % optAcc)
1
2
3
4
5
6
7
8
9
10
11
12
<ipython-input-18-719b936d0102>:5: TqdmDeprecationWarning: This function will be removed in tqdm==5.0.0
Please use `tqdm.notebook.tqdm` instead of `tqdm.tqdm_notebook`
  for gamma in tqdm_notebook(np.arange(0.1, 5.0, 0.1)):



  0%|          | 0/49 [00:00<?, ?it/s]


optG = 0.10
optC = 0.30
optAcc = 1.00
1
2
3
4
5
6
7
# 최적의 조건으로 학습한 결과를 확인한다.
model = SVC(kernel='rbf', gamma=optG, C=optC)
model.fit(testX, testY)

print()
print('학습용 데이터로 측정한 정확도 = %.2f ' % model.score(trainX, trainY))
print('시험용 데이터로 측정한 정확도 = %.2f ' % model.score(testX, testY))
1
2
학습용 데이터로 측정한 정확도 = 0.88
시험용 데이터로 측정한 정확도 = 0.90

Meta Info

Categories: ,

Published At:

Modified At:

Leave a comment