Thumbnail

MS Learn - Train and evaluate classification models Lesson을 학습하고 정리한다.


Classification 이란Permalink

Classification(분류)는 특정 아이템이 어디에 속해야 할지를 예측하는 모델을 만드는 것이다.

예를 들어, 키, 몸무게, 혈압, 혈내 글루코스 등의 수치를 통해 이 사람이 당뇨를 앓고있는가를 판단할 수 있다.

response가 1, 0 과 같이 두가지라면 Binary Classification, 세 가지 이상이라면 Multi class Classification이라 부를 수 있다.

image.png

다음과 같은 Figure를 보자.

image.png

우리가 학습시킨 모델은 알고리즘에 따라 정확히 0과 1로 output을 낼 수도 있지만 확률로 값이 나온뒤 threshold 를 이용해 그 이하인 것은 0, 그 이상인 것은 1로 처리하곤 한다.

위와 같이 Sigmoidal(S-shaped)처럼 plot이 나왔을 때 파란선이 그 threshold를 의미한다.

이 threshold를 0.50.5가 아닌 다른 값으로 설정하여 모델의 예측 결과를 조절할 수도 있다.

모델이 예측한 결과를 y^\hat{y}와 같이 표현한다.

Exercise - Binary ClassificationPermalink

데이터를 불러오고 Feature 파악하기Permalink

실제 모델을 학습시켜보자. 당뇨 환자를 예측하는 Binary Classification 모델이다.

import pandas as pd

# load the training dataset
!wget https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/diabetes.csv

diabetes = pd.read_csv('diabetes.csv')
diabetes.head()

pandas로 데이터를 불러온다.

불러온 데이터를 살펴본 뒤, column(feature)들로 boxplot을 그려 response(당뇨 여부)와의 상관관계를 하나하나 그려보는것도 좋은 데이터 살펴보기 방법이다.

from matplotlib import pyplot as plt
%matplotlib inline

features = ['Pregnancies','PlasmaGlucose','DiastolicBloodPressure','TricepsThickness','SerumInsulin','BMI','DiabetesPedigree','Age']

for col in features:
    diabetes.boxplot(column=col, by='Diabetic', figsize=(6,6))
    plt.title(col)
plt.show()

임신 횟수에 따른 Diabetic 분류의 box plot 예시이다.

image.png

검은색 원은 이상치이다.

위와 같이 임신 횟수에 따라서 Box Plot의 위치가 상이하게 차이나는 경우, 이 feature(predictor)는 우리의 분류 모델에 중요한 feature임을 예측해볼 수 있다.

하지만 아래와같이 DiastolicBloodPressure(이완기혈압) BoxPlot의 모양이 크게 차이나지 않는 DiastolicBloodPressure같은 경우 크게 중요한 feature가 아니라고 예측해볼 수 있다.

그러나 이는 섣부른 판단일 수 있다. 여러 predictor가 합쳐져 작동하는 Interaction Term(교호항)이나 이걸 이용한 Derived Variable(파생변수)가 더 의미가 있는 Feature일지 아직 판단할 수 없다.

image.png

train_test_splitPermalink

sklearn.model_selection 모듈의 train_test_split 함수로 데이터를 훈련용과 테스트용으로 분리하자.

from sklearn.model_selection import train_test_split

# Split data 70%-30% into training set and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)

print ('Training cases: %d\nTest cases: %d' % (X_train.shape[0], X_test.shape[0]))

위와 같이 하면 훈련, 테스트를 7:37:3 으로 분리한 것이다.

모델 학습Permalink

sklearn.linear_modelLogisticRegression 클래스로 로지스틱 회귀를 수행할 수 있다.

# Train the model
from sklearn.linear_model import LogisticRegression

# Set regularization rate
reg = 0.01

# train a logistic regression model on the training set
model = LogisticRegression(C=1/reg, solver="liblinear").fit(X_train, y_train)
print (model)

여기서 C=1/reg 라고 설정을 해주는데, 과적합을 방지해주기위해 규제항(페널티)를 얼마나 줄것인지를 결정하게된다.

C 는 작게 줄수록 규제가 세지고 반대로 크게 주면 규제가 약해진다.

보통 규제항은 L2(릿지), L1(라쏘), ElasticNet(L1 + L2)가 있고 L2가 default로 작용된다.

이는 penalty 파라미터로 변경할 수 있다.

규제가 강해질수록 과적합 위험도가 낮아지지만 언더피팅이 일어날 가능성이 있고 모델이 단순해진다. 반대로 규제가 약해질수록 과적합 위험도가 높아진다.

따라서 적절한 규제값을 찾는것이 중요하다.

모델 예측Permalink

predictions = model.predict(X_test)
print('Predicted labels: ', predictions)
print('Actual labels:    ', y_test)

모델을 fit을 이용해 학습시켰으므로 predict로 테스트 데이터를 검증해볼수있다.

이걸 하나하나 보는것은 비효율적이므로 우리는 분류모델의 Accuracy를 얻어올 수 있다.

import sklearn.metrics import accruacy_score

print('Accuracy: ', accuracy_score(y_test, predictions))
Accuracy=TP+TNTP+FP+TN+FN Accuracy=\dfrac{TP+TN}{TP+FP+TN+FN}

인데, Accuracy 자체로는 정확하지 않은 상황이 있을 수 있으므로 다른 여러 score도 함께 판단을 하게된다. 이는 다음 글에서 정리될 것이다.

Comments