오답노트

[ML] 모델에 대한 설명 - Shapley Additive Explanations(SHAP) 본문

Python/ML

[ML] 모델에 대한 설명 - Shapley Additive Explanations(SHAP)

권멋져 2022. 9. 6. 20:05

Shapley Additive Explanations (SHAP)

Shapley Value

Feature의 가능한 모든 조합에서 하나의 Feature에 대한 평균 기여도를 계산한 값을 Shapley Value라고 한다.

가중 평균을 통해 Feature의 기여도를 계산한다.

 

기여도 계산은 다음과 같다.

 

(모든 Feature를 사용한 모델링의 예측 값) - (
기여도를 알고 싶은 Feature가 존재하는 Feature들의 조합들 중 한 조합을 사용한 모델링의 예측 값)

 

수식은 내가 이해하지 못하므로 올리지 않겠다.

https://arxiv.org/pdf/1705.07874.pdf

나중에 실력이 생기면 위 논문을 읽어보자

 

실습 (회귀 모델)

!pip install shap

from sklearn.ensemble import RandomForestRegressor
import shap

model = RandomForestRegressor()
model.fit(x_train, y_train)

explainer1 = shap.TreeExplainer(model1)
shap_values1 = explainer1.shap_values(x_train)


shap.initjs()
index = 0

shap.force_plot(explainer1.expected_value, shap_values1[index, :], x_train.iloc[index,:])

shap 라이브러리를 설치하고, shap.TreeExplainer 에 모델을 입력하여 explainer를 만들고 shap 값을 확인하고 싶은 데이터 셋을 explainer의 shap_values 함수에 입력하면 explainer의 입력된 모델로 부터 데이터 셋에 예측 대한 Shapley Value를 반환한다.

 

shap 그래프는 js로 그리게 되는데 shap을 그리기 위한 js를 init 하는 함수가 shap.initjs()이다.

 

force_plot에 force_plot(전체평균, shapley_values, input) 순으로 인자를 넣으면 차트가 출력된다.

 

 

실습 (분류 모델)

model = RandomForestClassifier()
model.fit(x_train,y_train)

explainer1 = shap.TreeExplainer(model)
shap_values1 = explainer1.shap_values(x)

shap.initjs() 
index = 932

shap.force_plot(explainer1.expected_value[1], shap_values1[1][index, :], x_val.loc[index,:])

분류 모델에서는 예측 결과가 0과 1로 나뉘게 된다. 그래서 expected_value와 shap_values에 0 과 1의 인덱스로 들어가게 된다. 그래서 원하는 예측 결과에 따라 인덱스로 선택하여 force_plot을 진행해야한다.

 

 

SVM 모델

SVM 모델에서는 KernelExplainer를 통해 Shapley Value를 확인할 수 있다.

model2 = SVR()
model2.fit(x_train_s, y_train)

explainer2 = shap.KernelExplainer(model2.predict, x_train_s)
shap_values2 = explainer2.shap_values(x_train_s[:10])

shap.initjs()
shap.force_plot(explainer2.expected_value, shap_values2[0], x_train.iloc[0])

 

다양한 시각화

전체 변수에 대한 시각화

shap_values1 = explainer1.shap_values(x_train)
shap.summary_plot(shap_values1, x_train)

빨간색은 변수의 값이 높음을 파란색은 변수의 값이 낮음을 의미하고 왼쪽은 예측 값을 낮추는데 오른쪽은 예측 값을 높이는데 영향을 준다는 의미다.

 

lstat 같은 경우 lstat가 높을 경우 예측 값을 낮추고 lstat가 낮을 경우 예측 값을 높히게 된다.

 

특정 관점으로 정렬

shap.initjs()
shap.force_plot(explainer1.expected_value, shap_values1, x_train)

force_plot 에 shap vlaue와 데이터 셋의 index를 지정하지 않고 시행시킬 경우 좌측과 상단 드롭 박스를 통해 원하는 관점으로 Shapley Value를 확인할 수 있다.