ML/분류(Classification)

특성 중요도(feature_importances_)

야뤼송 2024. 4. 22. 08:32
반응형

 

1. feature_importances_란?

 

feature_importances_는 특성의 중요도를 나타내는 속성이다. 높은 중요도를 가진 특성은 모델의 예측에 큰 영향을 미치며, 반대로 낮은 중요도를 가진 특성은 모델의 예측에 크기  기여하지 않는다.

 

결정트리에서는 각 특성이 분기 결정에 얼마나 중요한 역할을 하는지를 나타낸다. 이 값은 모델이 데이털츨 분할할 때 각 특성을 기준으로 얼마나 정보가 향상되는지를 측정하여 계산된다.

feature_importances_값은 각 특성이 불손도(지니 계수, 엔트로피 등) 감소에 얼마나 기여하는지를 나타낸다. 즉, 높은 중요도를 가진 특성은 모델이 데이터를 분할할 때 불손도를 크게 감소시키는데 중요한 역할을 한다는 것을 의미한다.

 

 실습

먼저 붓꽃  데이터를 불러오고 붓꽃 데이터 Feature를 살펴보고 중요도를 계산한다. 그리고 graphviz를 통해 시각화한 결과를 살펴보자.

 

먼저 붓꽃 데이터의 feature를 살펴보면 꽃잎 길이, 꽃잎 너비, 꽃받침 길이, 꽃받침 너비 이렇게 4개의 feature를 가지고 있다.

from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

import graphviz

# DecisionTree Classifier 생성
dt_clf = DecisionTreeClassifier(random_state=156)

# 붓꽃 데이터를 로딩하고, 학습과 테스트 데이터 셋으로 분리
iris_data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris_data.data, iris_data.target,
                                                    test_size=0.2, random_state=11)

# DecisionTreeClassifer 학습. 
dt_clf.fit(X_train, y_train)

iris_data.feature_names

▶ Out

['sepal length (cm)',
 'sepal width (cm)',
 'petal length (cm)',
 'petal width (cm)']

 

 

이제 feature_importances_ 를 호출하여 간단하게 특성별 중요도를 구할 수 있다.

dt_clf.feature_importances_

▶ Out

array([0.02500521, 0.        , 0.55490281, 0.42009198])

 

 

각각의 특성별로 중요도를 맵핑하고 시각화까지 해보자.

데이터를 살펴보면 petal length와 petal width 봇꽃 분류 문제에서 결정 트리 모델에 있어 가장 중요한 특성으로 작용하고 있고

sepal length sepal width 모델의 예측에 영향을 미치지 않는 것을 알 수 있다.

import seaborn as sns
import numpy as np
%matplotlib inline

# feature importance 추출 
#print("Feature importances:\n{0}".format(np.round(dt_clf.feature_importances_, 3)))

# feature별 importance 매핑
for name, value in zip(iris_data.feature_names , dt_clf.feature_importances_):
    print('{0} : {1:.3f}'.format(name, value))

# feature importance를 column 별로 시각화 하기 
sns.barplot(x=dt_clf.feature_importances_ , y=iris_data.feature_names)

▶ Out

sepal length (cm) : 0.025
sepal width (cm) : 0.000
petal length (cm) : 0.555
petal width (cm) : 0.420

 

반응형