본문 바로가기
데이터 분석/Kaggle

House Price (4) - 변수 선택

by 너굴맨_ 2022. 1. 4.

변수 선택법으로 PCA, 변수 선택법 등 다양한 방법이 있지만 이 장에서는 SalePrice와 상관관계가 있는 변수와 (3)에서 관련성이 있어보이는 변수를 전진선택법을 통해 79개의 변수 중 몇개만 추려보자

 

1. 상관관계가 높은 변수 확인

## 상관관계가 0.4 이상인 관계가 있는 것만 확인하기
corr = train_data.corr()
plt.subplots(figsize = (15, 12))
sns.heatmap(corr[(corr >= 0.5) | (corr <= -0.4)], cmap = 'viridis', vmax = 0.9, linewidth = 0.1, annot = True, annot_kws = {'size': 8}, square = True)

## 상관관계가 큰 칼럼 10개 찾아내기
k = 10
cols = corr.nlargest(k, 'SalePrice')['SalePrice'].index
print('top 10 relative variables \n', train_data[cols].columns)
cm = np.corrcoef(train_data[cols].values.T)
sns.set(font_scale = 1.5)
hm = sns.heatmap(cm, cmap = 'Greens', annot = True, cbar = True, square = True, fmt = '.2f', annot_kws = {'size': 10}, yticklabels = cols.values, xticklabels = cols.values)

2. 변수 선택

  • 변수 추가
## 위에서 알게된 관련성이 높은 변수 사이
cols = cols.drop('SalePrice') 

## 위의 plot을 통해 추가하고 싶은 cols
temp = pd.Index(['YearRemodAdd']) # 추가할 변수
cols = cols.append(temp)

print(cols)

var = train_data[cols]
X_train = var[:train_data.shape[0]]
X_test = var[:test_data.shape[0]]

y_train = train_data["SalePrice"]

mlxd 모듈의 SFS 함수를 써서 변수 선택

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestRegressor
from mlxtend.feature_selection import SequentialFeatureSelector

pipe = make_pipeline(StandardScaler(), RandomForestRegressor(random_state=0))

cv = KFold(n_splits=10, shuffle=False)

sfs = SequentialFeatureSelector(pipe, k_features=var.shape[1], forward=True, scoring="neg_root_mean_squared_error", cv=cv)
sfs.fit(X_train, y_train)
sfs.subsets_

※ Scoring 방식은 Negative Root Mean Square Error로 예측값과 실제값의 차이(오차) 값이 적을수록 좋은 지표

avg_scores 값이 제일 적은 8개의 변수를 채택

 

# avg_score값이 제일 작은 변수
sfs.subsets_[8].get("feature_names")

features = ['OverallQual',
 'GrLivArea',
 'GarageCars',
 'TotalBsmtSF',
 'FullBath',
 'YearBuilt']

위와 같은 변수를 채택

댓글