• 매개 변수를 튜닝하여 일반화 성능을 개선하고자 함
  • 관심 있는 매개변수들을 대상으로 가능한 조합을 시도하여 최적의 값을 찾음
  • SVM에 적용하여 gamma, C의 조합을 찾아보자

 

커널 기법

 

  • 비선형 특성을 추가하여 선형 모델을 사용할 경우, 특성이 많을 때 연산비용이 증가할 뿐 아니라 데이터가 부정확해질 위험이 있다.
  • 수학적 기법을 이용하여 새로운 특성을 임의로 만들지 않고 고차원에서 학습할 수 있다 --> 커널 기법

 

 

 

 

from sklearn.svm import SVC
from sklearn import datasets
from sklearn.model_selection import train_test_split

# 1. load data and split
iris = datasets.load_iris()

X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3, random_state=0)


# 2. Grid Search

best_score = 0

# 임의의 gamma와 C를 지정해 반복문으로 돌려봄
for gamma in [0.001,0.01,0.1,1,10,100]:
    for C in [0.001,0.01,0.1,1,10,100]:
        # train SVC using combination of gamma and C
        svm = SVC(gamma = gamma, C = C)
        svm.fit(X_train, y_train)
        
        # evaluate model
        test_score = svm.score(X_test, y_test)
        
        # restore the highest score with its parameter
        if test_score > best_score:
            best_score = test_score
            best_parameter = {'gamma':gamma, 'C':C}
            train_score = svm.score(X_train, y_train)

print("Best score : {}".format(np.round(best_score,3)))
print("Train score : {}".format(train_score))
print("parameters :{}".format(best_parameter))

- gamma와 C를 임의로 주어 반복문 돌린 결과로  모델의 정확도가 97% 라고 결론 짓는 것은 위험

- 매개변수를 조정하기 위해 테스트 세트를 이미 사용했기 때문에 최종 모델의 정확성은 새로운 데이터가 생성될 때까지 알 수 없다

- 즉, 최종 평가를 위해서는 모델을 만들고 튜닝할 때 사용하지 않은 독립된 데이터 셋이 필요

- 애당초 데이터셋을 3개(train, validation, test) 로 나누어 이 문제 해결 가능 -> 하지만 데이터의 수가 적을 경우 부정확할 수 있음

 

 

- 검증 데이터 분류 후 확인

# 1. 데이터 분할 step1 -> train+validation/test

iris = datasets.load_iris()

X = iris.data
y = iris.target
X_trainval, X_test, y_trainval, y_test = train_test_split(X,y,test_size=0.25, random_state=0)


# 1. 데이터 분할 step2 -> train, validation

X_train, X_valid, y_train, y_valid = train_test_split(X_trainval,y_trainval,test_size=0.25,random_state=1)
print("train set size : {} , validation set size : {} , test set size: {}".format(X_train.shape[0],X_valid.shape[0],X_test.shape[0]))

# output : train set size : 84 , validation set size : 28 , test set size: 38



# 2. Grid Search
best_score = 0

for gamma in [0.001,0.01,0.1,1,10,100]:
    for C in [0.001,0.01,0.1,1,10,100]:
        # train SVC using combination of gamma and C
        svm = SVC(gamma = gamma, C = C)
        svm.fit(X_train, y_train)
        
        # evaluate model
        test_score = svm.score(X_valid, y_valid)  # train 데이터 학습한 것에서 검증 데이터 가지고 점수
        
        # restore the highest score with its parameter
        if test_score > best_score:
            best_score = test_score
            best_parameter = {'gamma':gamma, 'C':C}

            
# train / validation set을 합쳐 최적 모델 적합도
# test set 사용해 평가

svm = SVC(**best_parameter)
svm.fit(X_trainval,y_trainval)  # trainval : train + validation 모두 합한 데이터
test_score = svm.score(X_test, y_test)  # 테스트에 대한 점수 

print("Best score : {}".format(np.round(best_score,3)))
print("test score : {}".format(test_score))
print("parameters :{}".format(best_parameter))

- 결과 : Best score : 0.964 test score : 0.9210526315789473 parameters :{'gamma': 0.001, 'C': 10}

+ Recent posts