소소하지만 소소하지 않은 개발 공부/머신 러닝 교과서

4.6 랜덤 포레스트의 특성 중요도 사용, 머신러닝교과서, python

still..epochs 2022. 12. 7. 16:31

* 본 포스팅은 머신러닝교과서를 참조하여 작성되었습니다.

 

4.6 랜덤 포레스트의 특성 중요도 사용

랜덤 포레스트를 사용하면 앙상블에 참여한 모든 결정 트리에서 계산한 평균적인 불순도 감소로 특성 중요도를 측정할 수 있다. 편리하게도 사이킷런의 랜덤 포레스트의 구현은 특성 중요도 값을 이미 수집하고 있다. RandomForestClassifier 모델을 훈련한 후 feature_importances_ 속성에서 확인할 수 있다.

 

다음 코드에서 Wine 데이터셋에서 500개의 트리를 가진 랜덤 포레스트를 훈련하고 각각 중요도에 따라 13개의 특성에 순위를 매긴다.

 

* 트리 기반 모델은 표준화나 정규화를 할 필요가 없다.

from sklearn.ensemble import RandomForestClassifier

feat_labels = df_wine.columns[1:]

forest = RandomForestClassifier(n_estimators=500,
                                random_state=1)

forest.fit(X_train, y_train)
importances = forest.feature_importances_

indices = np.argsort(importances)[::-1]

for f in range(X_train.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30, 
                            feat_labels[indices[f]], 
                            importances[indices[f]]))

plt.title('Feature Importance')
plt.bar(range(X_train.shape[1]), 
        importances[indices],
        align='center')

plt.xticks(range(X_train.shape[1]), 
           feat_labels[indices], rotation=90)
plt.xlim([-1, X_train.shape[1]])
plt.tight_layout()
# plt.savefig('images/04_09.png', dpi=300)
plt.show()

랜덤 포레스트 모델의 특성 중요도

 

특성 중요도에 관한 이 절을 마무리하기 위해 사이킷런의 SelectFromModel을 살펴보자.

 

이 클래스는 모델 훈련이 끝난 후 사용자가 지정한 임계 값을 기반으로 특성을 선택한다. Pipeline의 중간 단계에서 RandomForestClassifier를 특정 선택기로 사용할 때 유용하다. Pipeline 클래스는 여러 전처리 단계를 하나의 추정기 인터페이스로 연결해 준다.

from sklearn.feature_selection import SelectFromModel

sfm = SelectFromModel(forest, threshold=0.1, prefit=True)
X_selected = sfm.transform(X_train)

print('이 임계 조건을 만족하는 샘플의 수:', X_selected.shape[1])\


>> 이 임계 조건을 만족하는 샘플의 수: 5



for f in range(X_selected.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30,
                           feat_labels[indices[f]],
                           importances[indices[f]]))
                           
                           
>>  1) Proline                        0.185453
    2) Flavanoids                     0.174751
    3) Color intensity                0.143920
    4) OD280/OD315 of diluted wines   0.136162
    5) Alcohol                        0.118529

 

 

4.7 요약

  • 머신 러닝 알고리즘에 데이터를 중비하기 전에 범주형 변수를 올바르게 인코딩 해야 한다.
  • 모델 복잡도를 감소시킴으로써 과대적합을 피하는 데 도움이 되는 L1 규제를 배웠다.
  • 관련 없는 특성을 제거하는 순차 특성 선택 알고리즘을 사용하여 데이터셋에서 의미 있는 특성을 선택할 수 있다.