#!/usr/bin/env python3


feature selection based model(모델 기반 특성 선택)


0. 살펴보기

feature selection based model모델 기반 특성 선택지도 학습 machine learning 모델을 사용하여

1. 특성의 중요도를 평가

2. 가장 중요한 특성들만 선택함


특성 선택에 사용하는 지도 학습 모델은 최종적으로 사용할 지도 학습 모델과 같을 필요는 없음

특성 선택을 위한 모델은 각 특성의 중요도를 측정하여 순서를 매길 수 있어야


decision tree는 각 특성의 중요도가 담겨있는 feature_importances_를 제공

decision tree : [1]Decision Tree


선형 모델 계수의 절댓값도 특성의 중요도를 평가하는 데 사용할 수 있음

L1규제를 사용한 선형 모델은 일부 특성의 계수만 학습(Lasso)

이는 그 모델 자체를 위해 특성이 선택된다고 생각할 수 있지만,

다른 모델의 특성 선택을 위해 전처리 단계로 사용할 수도 있음


Lasso : Lasso



단변량 분석과는 반대로 feature selection based model

한 번에 모든 특성을 고려하므로(사용된 모델이 상호작용을 잡아낼 수 있다면)

상호작용 부분을 반영할 수 있음


SelectFromModel은 (지도 학습 모델로 계산된) 중요도가 지정한 임계치보다 큰 모든 특성을 선택

이는 매우 복잡한 모델이고 단변량분석보다 훨씬 강력한 방법



1. breast cancer 데이터를 통한 단변량 분석과 모델 기반 특성 선택의 비교

### library import

from sklearn.datasets import load_breast_cancer

from sklearn.feature_selection import SelectFromModel, SelectPercentile

from sklearn.ensemble import RandomForestClassifier

from sklearn.linear_model import LogisticRegression

from sklearn.model_selection import train_test_split

import matplotlib.pyplot as plt

import matplotlib

import numpy as np


### matplotlib 한글, 축 - 설정

matplotlib.rc('font', family='AppleGothic')

plt.rcParams['axes.unicode_minus'] = False


### datasets

cancer = load_breast_cancer()

# print(cancer.data.shape)


### noise

rnd = np.random.RandomState(seed=0)

noise = rnd.normal(size=(cancer.data.shape[0], 70))


### np.hstack

cancer_data_noise = np.hstack([cancer.data, noise])


### data 분할

x_train, x_test, y_train, y_test =\

  train_test_split(cancer_data_noise, cancer.target,

                   random_state=0, test_size=0.3)


### 특성을 고를 model 적용

randforest = RandomForestClassifier(n_estimators=100, random_state=0)

select_model = SelectFromModel(randforest, threshold='median').fit(x_train, y_train)


select_uni = SelectPercentile(percentile=50).fit(x_train, y_train)



### visualization

models = [select_uni, select_model]

_, axes = plt.subplots(3, 1)


ones = np.ones(x_train.shape[1], dtype=np.bool)

axes[0].matshow(ones.reshape(1, -1), cmap='gray')

axes[0].set_yticks([])

axes[0].set_title('full feature')


for model, ax in zip(models, [axes[1], axes[2]]):

    x_train_model = model.transform(x_train)

    x_test_model = model.transform(x_test)


    idx = model.get_support()

    ax.matshow(idx.reshape(1, -1), cmap='gray')

    ax.set_yticks([])

    ax.set_title('{}'.format(model.__class__.__name__))

plt.show()


특성의 전체 선택, 단변량 선택, 모델기반선택으로 선택한 특성



### 일반화

logreg = LogisticRegression().fit(x_train, y_train)

score = logreg.score(x_test, y_test)

print('total 특성의 정확도: {:.3f}'.format(score))

models = [select_uni, select_model]

names = ['univariate', 'model_based']

for model, name in zip(models, names):

    x_train_model = model.transform(x_train)

    x_test_model = model.transform(x_test)

    logreg = LogisticRegression().fit(x_train_model, y_train)

    score = logreg.score(x_test_model, y_test)

    print('{}의 정확도: {:.3f}'.format(name, score))

각 모델별 정확도

+ Recent posts