본문 바로가기

Study/class note

머신러닝 / 파이썬으로 서포트 벡터 머신 모델 만들기

72 파이썬으로 서포트 벡터 머신 모델 만들기

- iris 데이터로 품종 분류하는 모델 생성하기

#1. 데이터 로드

#2. 결측치 확인

#3. 정규화 진행

#4. 훈련 데이터와 테스트 데이터 분리

#5. 모델 생성

#6. 모델 훈련

#7. 모델 예측

#8. 모델 평가

#9. 모델 개선

#1. 데이터 로드
import pandas as pd

iris = pd.read_csv("c:\\data\\iris2.csv")
iris.head()  #label컬럼 4번째(마지막컬럼)
iris.shape  #(150, 5)

#2. 결측치 확인
iris.isnull().sum()

#3. 정규화 진행
x = iris.iloc[:,:-1]
y = iris.iloc[:,-1]

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
x_scaled = scaler.fit_transform(x)

#4. 훈련 데이터와 테스트 데이터 분리
from sklearn.model_selection import train_test_split

x_train, x_test, y_train,y_test = train_test_split(x_scaled, y, test_size = 0.1, random_state = 1)

print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)  #(135, 4) (15, 4) (135,) (15,)

#5. 모델 생성
from sklearn import svm

svm_model = svm.SVC(kernel = 'rbf')  #커널 옵션: rbf, poly, sigmoid, linear

#6. 모델 훈련
svm_model.fit(x_train, y_train)

#7. 모델 예측
result = svm_model.predict(x_test)

#8. 모델 평가
sum(result == y_test) / len(y_test)  #1.0

 

svm.SVC(kernel = 'rbf') 일반적인 관행 중 하나는 가우시안 rbf 커널로 시작하는 것

커널 옵션: rbf, poly, sigmoid, linear

#9. 모델 개선

from sklearn import svm
from sklearn.model_selection import GridSearchCV

param_grid = {'C' : [0.1, 1, 10, 100, 1000],
              'gamma' : [1, 0.1, 0.01, 0.001, 0.00001],
              'kernel' : ['rbf', 'poly','sigmoid','linear']}

grid = GridSearchCV(svm.SVC(), param_grid, refit = True, n_jobs = -1, verbose = 2)
grid.fit(x_train, y_train)
print(grid.best_params_)  #{'C': 10, 'gamma': 1, 'kernel': 'rbf'}

refit = True 는 최적의 파라미터를 찾은 뒤 찾아낸 최적의 하이퍼 파라미터로 재학습 시키는 것(default=True)

result2 = grid.predict(x_test)
sum(result2 == y_test) / len(y_test)  #1.0

 

 

- 유방암 데이터의 양성과 악성 종양을 분류하는 서포트 벡터 머신 모델을 파이썬으로 만들기

#1. 데이터 로드
wisc = pd.read_csv("c:\\data\\wisc_bc_data.csv")
wisc.head()  #label 1번째 컬럼 / id컬럼(0) 제외시켜야함
wisc.shape  #(569, 32)

#2. 결측치 확인
wisc.isnull().sum()

#3. 정규화
x = wisc.iloc[:,2:]
y = wisc.iloc[:,1]

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
x_scaled = scaler.fit_transform(x)

#4. 훈련데이터, 테스트 데이터 분리
from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x_scaled, y, test_size = 0.1, random_state = 1)

print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)  #(512, 30) (57, 30) (512,) (57,)

#5. 모델생성
from sklearn import svm

wisc_model = svm.SVC(kernel = 'rbf')

#6. 모델훈련
wisc_model.fit(x_train, y_train)

#7. 모델예측
wisc_result = wisc_model.predict(x_test)

#8. 모델평가
sum(wisc_result == y_test) / len(y_test)  #0.9824561403508771

# 이원교차표
pd.crosstab(y_test,wisc_result)  #FN값 1

정확도도 높이고 FN값을 줄이기 위해 모델을 개선해보겠음.

#9. 모델 개선

from sklearn import svm
from sklearn.model_selection import GridSearchCV

param_grid = {'C' : [0.1, 1, 10, 100, 1000],
              'gamma' : [1, 0.1, 0.01, 0.001, 0.00001],
              'kernel' : ['rbf', 'poly','sigmoid','linear']}

grid2 = GridSearchCV(svm.SVC(), param_grid, refit = True, n_jobs = -1, verbose = 2)
grid2.fit(x_train, y_train)
print(grid2.best_params_)   #{'C': 100, 'gamma': 1, 'kernel': 'rbf'}
print(grid2.best_score_)

wisc_result2 = grid2.predict(x_test)
sum(wisc_result2 == y_test) / len(y_test)  #0.9473684210526315
pd.crosstab(y_test,wisc_result2)  #FN값 1

gridsearch를 썼더니 오히려 성능이 떨어짐. 제공하는 하이퍼 파라미터의 설정값을 적절하게 줘야함.

gridsearch에 cv를 설정하면 성능이 올라가긴 함. 자세한 내용은 11장에서 배울예정

> 모델 개선을 해도 FN값이 떨어지지 않는데 뒤에서 앙상블을 이용해 없애볼 예정

 

 

신경망과 서포트 벡터 머신은 아주 강력한 머신러닝 모델이지만 의사결정트리와 회귀분석처럼 설명하기 어려운 단점이 있음(블랙박스로 진행되기 때문). 그렇지만 지도학습에 있어 아주 강력한 머신러닝 모델이므로 뒤에서 앙상블을 배울 때 이 모델들을 다 섞어서 더 좋은 모델을 만들어보겠음.

 

반응형