KNN을 통한 Parameter Tuning

Assignment 1

KNN으로 HyperParameter 이해하기

우수과제 선정이유

EDA를 통해 IRIS 데이터에 대한 분석과 기본 데이터와 스케일링한 데이터를 비교하며 하이퍼파리머터 튜닝까지 깔끔하게 해 우수과제로 선정되었습니다.

Load Dataset

Import packages

# data
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore") 

# visualization
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from pandas.plotting import parallel_coordinates

# preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler

# model
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split

# grid search
from sklearn.model_selection import GridSearchCV

# evaluation
from sklearn.model_selection import cross_val_score
from sklearn.metrics import *

Load iris data

  • feature에는 sepal length, sepal width, petal length, petal width가 있다.

  • target은 3개의 class가 있으며 각각 Iris-Setosa, Iris-Versicolour, Iris-Virginica, 즉, 붖꽃의 종류이다.

  • Setosa, Versicolour, Virginica가 각각 0, 1, 2로 분류 되어있다.

  • 총 150개의 instance가 존재한다.

Make DataFrame

sepal length (cm)

sepal width (cm)

petal length (cm)

petal width (cm)

species

0

5.1

3.5

1.4

0.2

setosa

1

4.9

3.0

1.4

0.2

setosa

2

4.7

3.2

1.3

0.2

setosa

3

4.6

3.1

1.5

0.2

setosa

4

5.0

3.6

1.4

0.2

setosa

EDA

sepal length (cm)

sepal width (cm)

petal length (cm)

petal width (cm)

count

150.000000

150.000000

150.000000

150.000000

mean

5.843333

3.054000

3.758667

1.198667

std

0.828066

0.433594

1.764420

0.763161

min

4.300000

2.000000

1.000000

0.100000

25%

5.100000

2.800000

1.600000

0.300000

50%

5.800000

3.000000

4.350000

1.300000

75%

6.400000

3.300000

5.100000

1.800000

max

7.900000

4.400000

6.900000

2.500000

  • 각 Class 별로 data가 50개씩 존재한다.

Pairplot

  • petal length 만으로 0과 1종을 완전히 구분할 수 있다

  • petal length와 petal width 두가지로 나누면 1과 2종도 구분해 낼 수 있을 것으로 보인다

Distplot

  • 위의 분포를 보면 petal length 하나의 변수만으로 setosa와 다른 종들을 쉽게 분류해낼 수 있을 것으로 보인다.

  • 반면 virginica와 versicolor는 petal length 만으로는 완전히 분류해내기 어려워보인다.

Parallel coordinates plot

  • 각 feature들로 얼마나 붓꽃 종류를 구분할 수 있는지 한눈에 알 수 있다.

  • 앞에서 언급했듯이 petal length와 petal width로 0과 1를 구분해낼 수 있다

Boxplot¶

  • 각 데이터의 분포를 살펴보았다.

  • sepal_width 데이터에서 outlier가 있는 것을 알 수 있었다.

Preprocessing

  • KNN을 사용하기에 앞서 거리를 구하는 것이 분류의 핵심이므로 Scaling을 해주기로 하였다.

  • 그 전에 train data와 test data를 나누어 주기로 하였다.

Split data

Scaling

sepal length (cm)

sepal width (cm)

petal length (cm)

petal width (cm)

0

0.701282

-0.850872

0.852239

0.902670

1

0.444603

-2.033225

0.390008

0.369166

2

0.701282

-0.614401

1.025575

1.169422

3

-0.068753

-0.850872

0.043334

-0.030962

4

-1.608823

1.277364

-1.632254

-1.364723

sepal length (cm)

sepal width (cm)

petal length (cm)

petal width (cm)

0

0.583333

0.318182

0.754386

0.750000

1

0.527778

0.090909

0.614035

0.583333

2

0.583333

0.363636

0.807018

0.833333

3

0.416667

0.318182

0.508772

0.458333

4

0.083333

0.727273

0.000000

0.041667

Modeling

  • 한번에 validation용 metrics를 출력할 수 있는 함수를 생성하였다.

Simple Model

Standard Scaled Model

MinMax Scaled Model

Hyperparameter Tuning

Parameters

  • n_neighbors: 검색할 이웃의 수로 default 값은 5이다.

  • Metric: 거리 측정 방식을 변경하는 매개변수로 default 값은 minkowsi이다

  • Weights: 예측에 사용하는 가중치로 uniform 은 각 이웃에 동일한 가중치를 , ‘distance’는 가까운 이웃이 멀리 있는 이웃보다 더욱 큰 영향을 미친다.

Grid Search CV

1. No Scaled

2. Standard Scaled

3. MinMax Scaled

  • Score의 결과가 가장 좋은 MinMax Scaled Data의 {'metric': 'euclidean', 'n_neighbors': 9, 'weights': 'uniform'} parameters를 선택하기로 하였다.

Final Model

Evaluation

  • 하나의 test instance를 제외하고 모두 분류해냈다.

  • 역시 setosa는 완전히 분류해냈으나 나머지 두 종을 분류해내기 힘들었던 것 같다.

Last updated

Was this helpful?