2021. 1. 13. 23:19ㆍ머신러닝
Subset Selection은 우리가 활용할 수 있는 Dependant variable들이 많으나 어떤 것이 유의한 변수인지 결정하기 어려울 때 활용할만한 변수를 선정하기 위해 적용하는 방법입니다.
많이 활용되고 있는 방법으로 1) Best Subset Selection 2) Stepwise Selection이 있습니다.
이러한 기계적인 방법이 변수를 선정하는데 최선의 방법이라고 보긴 어렵겠지만, 쉽게 활용할 수 있는 방법입니다.
[Best Subset Selection]
Best Subset Selection은 가능한 모든 모델을 고려하여 가장 좋은 모델을 선택하는 방법입니다. 가장 좋은 모델을 선택하는 Step은 아래와 같습니다.
Step1) 변수의 사이즈 k=0,1,2,..,p에 대하여 각 변수 사이즈에서 최적의 모델 p+1(($M_0$,$M_1$,...,$M_p$)개를 정의함
Step2) 각 변수 사이즈(k=0,1,2,..,p)에서 정의된 최적의 모델($M_0$,$M_1$,...,$M_p$)을 서로 비교하여 하나의 Best Model을 선택함(비교기준은 AIC, $R^2$, accuracy 등 다양하게 정의할 수 있음)
[Stepwise Selection]
Best Subset Selection은 말그대로 모든 모델을 고려하여 가장 좋은 모델을 선택하는 방안이기 때문에, 계산효율이 떨어지게 됩니다. 따라서 우리가 Selection해야하는 변수 k의 수가 많을 때는 Stepwise Selection 방법을 적용합니다.
Stepwise Selection은 크게 Forward Stepwise Selection과 Backward Stepwise Selection으로 구분될 수 있습니다.
먼저 Forward Stepwise Selection은 변수의 사이즈 0부터 시작하여, 하나씩 변수를 추가해가면서 Model을 선택하게 됩니다. Backward Stepwise Selection은 Full model로 시작하여 하나씩 변수를 제거하면서 최적의 Model을 선택하게 됩니다.
위와 같은 Grid Search기반에 Subset Selection은 Discrete Process이기 때문에 종종 중요한 변수를 놓치거나 중요하지 않은 변수를 포함하는 경우가 있습니다. 또한 단순히 이론적이나 Biusiness 도메인 전문성을 모델에 반영하는 것이 아니라 기계적으로 결정하는 것이기 때문에 변수 선정의 타당성을 설명하기가 어려운 경우도 있습니다.
for loop과 itertools을 활용하여 Best Selection, Foward/Backward Selection을 파이썬으로 구현한 내용은 아래 싸이트를 참고하시면 좋을 것 같습니다.
https://xavierbourretsicotte.github.io/subset_selection.html
이번 포스팅에서는 Python의 mlxtend 패키지를 활용해서 쉽게 변수를 탐색해보겠습니다. sklearn의 RFE도 기계적인 Feature Selection하는데 활용할 수 있습니다. Subset Selection과 같은 방법론을 적용할때는 이론적 함의보단 패키지를 활용해서 빠르게 탐색하는게 더 효율적인 것 같습니다.
import itertools
import time
import numpy as np
import pandas as pd
import seaborn as sns
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
data = pd.read_csv("Credit.csv")
credit = data.drop(columns=["Unnamed: 0"])
credit.head()
credit = pd.get_dummies(credit, columns = ['Gender', 'Student','Married','Ethnicity'],drop_first = True)
credit.head(3)
def fit_linear_reg(X,Y):
#Fit linear regression model and return RSS and R squared values
model_k = linear_model.LinearRegression(fit_intercept = True)
model_k.fit(X,Y)
RSS = mean_squared_error(Y,model_k.predict(X)) * len(Y)
R_squared = model_k.score(X,Y)
return RSS, R_squared
from tqdm import tnrange, tqdm_notebook
from ipywidgets import IntProgress
#Initialization variables
Y = credit.Balance
X = credit.drop(columns = 'Balance', axis = 1)
k = 11
RSS_list, R_squared_list, feature_list = [],[], []
numb_features = []
#Looping over k = 1 to k = 11 features in X
for k in range(1,len(X.columns) + 1):
#Looping over all possible combinations: from 11 choose k
for combo in itertools.combinations(X.columns,k):
tmp_result = fit_linear_reg(X[list(combo)],Y) #Store temp result
RSS_list.append(tmp_result[0]) #Append lists
R_squared_list.append(tmp_result[1])
feature_list.append(combo)
numb_features.append(len(combo))
#Store in DataFrame
df = pd.DataFrame({'numb_features': numb_features,'RSS': RSS_list, 'R_squared':R_squared_list,'features':feature_list})
일단 위에 첨부드린 블로그에서 코드를 Copy하여 Best Subset Selection을 수행하였습니다. 후에 Mlxtend로 얻은 feature selection결과와 비교하기 위함입니다.
from mlxtend.feature_selection import SequentialFeatureSelector as SFS
lin_model= linear_model.LinearRegression()
sfs1 = SFS(lin_model,
k_features=3,
forward=True,
floating=False,
scoring='r2',
cv=0)
sfs1 = sfs1.fit(X, Y)
print(sfs1.k_feature_idx_)
##### num_feature =3일 때 Best subset selection과 mxltend 활용 결과 비교
## Best Subset Selection
max_in_three=df.query("numb_features==3")["R_squared"].max()
df.loc[df["R_squared"]==max_in_three]["features"]
''' (Income, Rating, Student_Yes)'''
X.columns[[sfs1.k_feature_idx_]]
''' Index(['Income', 'Rating', 'Student_Yes'], dtype='object')'''
위의 결과를 보면 결과가 (Income, Rating, Student_Yes)로 둘이 동일함을 알 수 있습니다. 어떤 경우에 따라서는 결과가 달라질 수 있습니다. 앞에서 정리한 것과 같이 이러한 기계적인 변수 Selection은 큰 고민 없이 적용할 수 있는데 큰 장점이 있습니다.
'머신러닝' 카테고리의 다른 글
선형 분류 모형(Linear Methods for Classification) (0) | 2021.02.20 |
---|---|
Dimension Reduction Method(Principal Components Regression, Partial Least Squares) (0) | 2021.02.03 |
Shrinkage Method2(Elastic Net, LARS) (0) | 2021.01.24 |
Shrinkage Method (0) | 2021.01.23 |
선형 모형(Linear Methods for Regression) (0) | 2021.01.10 |