#!/usr/bin/env python3


Multi Linear Classification


Logistic Regression만 제외하고 많은 linear model은 binary classifier를 지원합니다.

binary classifier algorithm을 multi class classifier algorithm으로 확장하는 보편적인 기법은

one-vs.-rest일대다방법입니다.


one-vs.-rest방식은 각 class를 다른 모든 class와 구분하도록 binary classifier model을 학습합니다.

이렇게하면 class의 수만큼 binary classifier model이 만들어집니다.


예측을 할 때 이렇게 만들어진 모든 binary classifier가 작동하여 가장 높은 점수를 내는 classifier의 class를 예측값으로 선택합니다.


class별 binary classifier를 만들면 각 class가 계수 벡터(w)와 절편(b)를 하나씩 갖게 됩니다.

결국 classifer 신뢰도를 나타내는 다음 공식의 결과값이 가장 높은 class가 해당 데이터의 class 레이블로 할당됩니다.


formula :  w[0] * x[0] + w[1] * x[1] + … + w[p] * x[p] + b


multi class Logistic Regression는 one-vs.-rest 방식과는 다르지만 class마다 하나의 계수벡터와 절편을 만들며 예측방법도 같습니다.


인위적 데이터의 구조를 보기 위해 시각화를 해보겠습니다.

from sklearn.datasets import make_blobs

import matplotlib.pyplot as plt

import numpy as np


x, y = make_blobs(random_state=42)


idx_set = []

marker_set = ['o', 'v', '^']

for i in np.unique(y):

    idx = np.where(y==i)[0]

    idx_set.append(idx)


for i, m in enumerate(marker_set):

    plt.scatter(x[idx_set[i]][:, 0], x[idx_set[i]][:, 1],

                marker=m, label='class {}'.format(i))

plt.legend()

plt.xlabel('feature 0')

plt.ylabel('feature 1')

plt.show()

3개의 클래스를 가진 2차원 데이터셋



다음으로 LinearSVC의 결과의 속성을 알아보겠습니다.

from sklearn.svm import LinearSVC


linear_svc = LinearSVC().fit(x, y)


print('{}'.format(linear_svc.coef_.shape))

# (3, 2)


print('{}'.format(linear_svc.coef_))

# [[-0.17492614  0.23140501]

#  [ 0.47621354 -0.06937621]

#  [-0.18914141 -0.20400513]]


print('{}'.format(linear_svc.intercept_))

# [-1.07745335  0.13140664 -0.08604991]


print('{}'.format(linear_svc.intercept_.shape))

# (3,)



3개의 binary classifier가 만드는 경계를 시각화하는 코드는 다음과 같습니다.

from mglearn.plots import plot_2d_classification


plot_2d_classification(linear_svc, x, fill=True, alpha=0.5)


idx_set = []

market_set = ['o', '^', 'v']

for i in np.unique(y):

    idx = np.where(y==i)[0]

    idx_set.append(idx)


for i, m in enumerate(marker_set):

    plt.scatter(x[idx_set[i]][:, 0], x[idx_set[i]][:, 1], marker=m,

                label='class {}'.format(i), edgecolors='k')


line = np.linspace(-15, 15, num=50)

for i, (coef, icept) in enumerate(zip(linear_svc.coef_, linear_svc.intercept_)):

    dec_line = -(line*coef[0] + icept) / coef[1]

    plt.plot(line, dec_line, ls='--', dashes=(3, 1), label='class {} line'.format(i)) # dashes: dash간격, 3dot당 공간 1개


plt.xlabel('feature 0')

plt.ylabel('feature 1')

plt.legend(loc=(1.01, 0.9))

plt.show()

3개의 one vs.rest classifier가 만든 decision boundary

class 0에 속한 모든 포인트는 class 0을 구분하는 직선 위, 나머지 class는 아래에 있습니다.

class 1에 속한 모든 포인트는 class 1을 구분하는 직선 위, 나머지 class는 아래에 있습니다.

이런 방법으로 모든 class를 분류합니다.


중간에 삼각형 영역은 모두 나머지로 분류하는 영역입니다.

이 영역에 있는 데이터 classifier 공식의 결과가 가장 높은 class로 분류합니다.

즉 가장 가까운 직선의 class가 됩니다.


Linear model에서 주요 parameter는

regression model에서 alpha

LinearSVC, Logistic Regression에서는 C입니다.


alpha값이 클수록, C값이 작을수록 model이 단순해집니다.


Regularization: L1, L2중 선택하고 기본적으로L2를 사용합니다.(모든 특성 사용)

L1은 몇가지 특성만 사용하므로 해당 모델에 중요한 특성이 무엇이고 효과가 어느정도 인지 설명하기 쓉습니다.


데이터셋이 크다면

LogisticRegression과 Ridge에 solver='sag'옵션을 주면 더 빨리처리가 가능합니다.

sag: Stochastic Average Gradient descent(확률적 평균 경사 하강법)입니다.




참고 자료: 

[1]Introduction to Machine Learning with Python, Sarah Guido

'python 머신러닝 -- 지도학습 > Classifier' 카테고리의 다른 글

Random Forest  (0) 2018.03.15
Decision Tree  (0) 2018.03.14
Logistic Regression  (1) 2018.03.13
k_NN(k-최근접 이웃) Classifier[2]  (1) 2018.03.12
k_NN(k-최근접 이웃) Classifier[1]  (0) 2018.03.11

+ Recent posts