[파이썬][scikit-learn] scikit-learn에서 모델 해석

scikit-learnPython에서 machine learning을 쉽게 구현할 수 있는 라이브러리입니다. 그러나 모델이 어떻게 작동하는지 이해하고 모델의 예측을 해석하는 것은 매우 중요합니다. 이 블로그 게시물에서는 scikit-learn을 사용하여 모델을 해석하는 방법을 알아보겠습니다.

특성 중요도 (Feature Importance)

특성 중요도는 모델의 각 특성이 예측에 얼마나 중요한지를 알려줍니다. 이는 모델이 어떤 특성에 가장 의존하는지를 알려주는데 도움이 됩니다. scikit-learn에서는 feature_importances_ 속성을 통해 특성 중요도를 확인할 수 있습니다.

from sklearn.ensemble import RandomForestClassifier

# 데이터 로드 및 전처리
X, y = load_data()
X = preprocess_data(X)

# RandomForestClassifier 모델 훈련
model = RandomForestClassifier()
model.fit(X, y)

# 특성 중요도 확인
importance = model.feature_importances_

# 특성 중요도 출력
for feature, importance in zip(X.columns, importance):
    print(f"{feature}: {importance}")

PDP (Partial Dependence Plot)

PDP는 특정 특성의 값이 모두 동일한 상태에서 다른 특성의 값을 변경하여 모델의 예측에 대한 변화를 시각화합니다. 이를 통해 특성 간의 상호작용이나 특성의 영향력을 파악할 수 있습니다. scikit-learn에서는 plot_partial_dependence 함수를 통해 PDP를 그릴 수 있습니다.

from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import load_boston
from sklearn.inspection import plot_partial_dependence

# 보스턴 주택 가격 데이터 로드
X, y = load_boston(return_X_y=True)

# RandomForestRegressor 모델 훈련
model = RandomForestRegressor()
model.fit(X, y)

# PDP 그리기
plot_partial_dependence(model, X, features=[0, 5, (0, 5)])

SHAP (SHapley Additive exPlanations)

SHAP은 SHapley Additive exPlanations의 약자로, 모델의 예측을 개별 특성들의 기여도로 설명해줍니다. SHAP 값을 통해 모델의 예측이 어떤 특성들에 의해 주도되는지를 파악할 수 있습니다. scikit-learn에서는 shap 라이브러리를 통해 SHAP 값을 구할 수 있습니다.

import shap
from sklearn.ensemble import RandomForestClassifier

# 데이터 로드 및 전처리
X, y = load_data()
X = preprocess_data(X)

# RandomForestClassifier 모델 훈련
model = RandomForestClassifier()
model.fit(X, y)

# SHAP 값을 계산
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X)

# SHAP summary plot 그리기
shap.summary_plot(shap_values, X)

위 예제 코드에서 shap.summary_plot 함수는 SHAP summary plot을 그립니다. 이 그래프는 각 특성의 기여도를 시각화하여 해석을 도와줍니다.

scikit-learn을 사용하여 모델을 해석하는 방법을 간단히 알아보았습니다. 특성 중요도, PDP, SHAP 등의 기능을 적절히 활용하면 모델의 예측을 해석하고 신뢰성 있는 결정을 내릴 수 있습니다.