콘텐츠로 이동
Data Prep
상세

모델 해석 개요

모델 해석(Explainability/Interpretability)은 ML 모델의 예측 과정과 결과를 인간이 이해할 수 있도록 설명하는 분야다. 신뢰성, 규제 준수, 디버깅을 위해 필수적.


핵심 개념

해석가능성 vs 설명가능성

개념 정의 예시
Interpretability 모델 자체가 이해 가능 선형 회귀, 결정 트리
Explainability 복잡한 모델에 대한 사후 설명 SHAP, LIME

설명 범위

범위 설명 방법
Global 전체 모델 동작 Feature Importance, PDP
Local 개별 예측 설명 SHAP, LIME, Attention

알고리즘 분류 체계

Explainability Methods
├── Intrinsically Interpretable Models
│   ├── Linear Models
│   ├── Decision Trees
│   ├── Rule-based (RuleFit)
│   └── GAM (Generalized Additive Models)
├── Post-hoc Global Methods
│   ├── Feature Importance
│   │   ├── Permutation Importance
│   │   ├── Drop-column Importance
│   │   └── SHAP Global
│   ├── Partial Dependence Plot (PDP)
│   ├── Individual Conditional Expectation (ICE)
│   └── Global Surrogate Models
├── Post-hoc Local Methods
│   ├── LIME (Local Interpretable Model-agnostic Explanations)
│   ├── SHAP (SHapley Additive exPlanations)
│   │   ├── TreeSHAP
│   │   ├── KernelSHAP
│   │   └── DeepSHAP
│   ├── Counterfactual Explanations
│   └── Anchors
└── Neural Network Specific
    ├── Attention Visualization
    ├── Gradient-based (Saliency Maps)
    ├── CAM / Grad-CAM
    └── Integrated Gradients

SHAP (SHapley Additive exPlanations)

게임 이론의 Shapley Value를 ML에 적용:

\[\phi_i = \sum_{S \subseteq N \setminus \{i\}} \frac{|S|!(|N|-|S|-1)!}{|N|!} [f(S \cup \{i\}) - f(S)]\]

특성

  1. Local Accuracy: \(f(x) = \phi_0 + \sum_{i=1}^{M} \phi_i\)
  2. Missingness: 없는 특성은 기여도 0
  3. Consistency: 기여도가 증가하면 Shapley 값도 증가
import shap

# TreeSHAP (트리 모델용, 빠름)
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# Summary Plot (전역)
shap.summary_plot(shap_values, X_test, feature_names=feature_names)

# Beeswarm Plot
shap.plots.beeswarm(shap_values)

# Dependence Plot
shap.dependence_plot('income', shap_values, X_test)

# Force Plot (개별 예측)
shap.force_plot(explainer.expected_value, shap_values[0], X_test.iloc[0])

# Waterfall Plot
shap.plots.waterfall(shap_values[0])

KernelSHAP (모델 무관)

# 임의 모델에 적용
explainer = shap.KernelExplainer(model.predict_proba, shap.sample(X_train, 100))
shap_values = explainer.shap_values(X_test[:10])

참고 논문: - Lundberg, S.M. & Lee, S.I. (2017). "A Unified Approach to Interpreting Model Predictions". NeurIPS. - Lundberg, S.M. et al. (2020). "From Local Explanations to Global Understanding with Explainable AI for Trees". Nature Machine Intelligence.


LIME (Local Interpretable Model-agnostic Explanations)

국소적으로 해석 가능한 대리 모델 학습:

\[\xi(x) = \arg\min_{g \in G} L(f, g, \pi_x) + \Omega(g)\]
import lime
from lime.lime_tabular import LimeTabularExplainer

explainer = LimeTabularExplainer(
    X_train.values,
    feature_names=feature_names,
    class_names=['class_0', 'class_1'],
    mode='classification'
)

# 개별 예측 설명
exp = explainer.explain_instance(
    X_test.iloc[0].values,
    model.predict_proba,
    num_features=10
)

exp.show_in_notebook()
exp.as_list()

참고 논문: - Ribeiro, M.T. et al. (2016). "Why Should I Trust You? Explaining the Predictions of Any Classifier". KDD.


Partial Dependence Plot (PDP)

특성과 예측의 평균적 관계:

\[\hat{f}_S(x_S) = \frac{1}{n} \sum_{i=1}^{n} f(x_S, x_C^{(i)})\]
from sklearn.inspection import PartialDependenceDisplay

# 1D PDP
PartialDependenceDisplay.from_estimator(
    model, X_train, features=['income', 'age'],
    kind='average'
)

# 2D PDP (상호작용)
PartialDependenceDisplay.from_estimator(
    model, X_train, features=[('income', 'age')]
)

Individual Conditional Expectation (ICE)

개별 샘플의 조건부 기대값:

PartialDependenceDisplay.from_estimator(
    model, X_train, features=['income'],
    kind='both'  # PDP + ICE
)

신경망 해석

Attention Visualization

Transformer의 Attention 가중치 시각화:

from bertviz import head_view

# BERT attention 시각화
outputs = model(input_ids, attention_mask=attention_mask, output_attentions=True)
attentions = outputs.attentions

head_view(attentions, tokens)

Grad-CAM

CNN의 특성 맵 기반 시각화:

\[L_{Grad-CAM}^c = ReLU\left(\sum_k \alpha_k^c A^k\right)\]

여기서 \(\alpha_k^c = \frac{1}{Z} \sum_i \sum_j \frac{\partial y^c}{\partial A_{ij}^k}\)

import torch
from pytorch_grad_cam import GradCAM
from pytorch_grad_cam.utils.image import show_cam_on_image

# 타겟 레이어 설정
target_layers = [model.layer4[-1]]

cam = GradCAM(model=model, target_layers=target_layers)
grayscale_cam = cam(input_tensor=input_tensor, targets=None)

visualization = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True)

Integrated Gradients

기준점으로부터의 적분 그래디언트:

\[IG_i(x) = (x_i - x'_i) \times \int_{\alpha=0}^{1} \frac{\partial F(x' + \alpha(x-x'))}{\partial x_i} d\alpha\]
from captum.attr import IntegratedGradients

ig = IntegratedGradients(model)
attributions = ig.attribute(input_tensor, target=predicted_class)

참고 논문: - Selvaraju, R.R. et al. (2017). "Grad-CAM". ICCV. - Sundararajan, M. et al. (2017). "Axiomatic Attribution for Deep Networks". ICML.


Counterfactual Explanations

"무엇이 달랐다면 결과가 바뀌었을까?"

import dice_ml

# DiCE 설정
d = dice_ml.Data(dataframe=df, continuous_features=continuous, outcome_name='target')
m = dice_ml.Model(model=model, backend='sklearn')
exp = dice_ml.Dice(d, m)

# 반사실적 설명 생성
cf = exp.generate_counterfactuals(
    query_instance,
    total_CFs=4,
    desired_class="opposite"
)
cf.visualize_as_dataframe()

실무 적용

선택 가이드

상황 권장 방법
트리 모델 + 빠른 전역 TreeSHAP
임의 모델 + 국소 설명 LIME, KernelSHAP
특성-예측 관계 시각화 PDP, ICE
CNN 이미지 Grad-CAM
Transformer NLP Attention
"왜 아닌가" 설명 Counterfactual

주의사항

  1. 상관된 특성: SHAP/LIME 해석 주의
  2. 외삽 위험: PDP의 비현실적 조합
  3. 설명의 안정성: 동일 입력, 다른 설명?
  4. 인과 vs 상관: 설명 ≠ 인과

참고 문헌

서적

  • Molnar, C. (2022). "Interpretable Machine Learning". (무료 온라인: https://christophm.github.io/interpretable-ml-book/)

핵심 논문

  • Lundberg, S.M. & Lee, S.I. (2017). "SHAP". NeurIPS.
  • Ribeiro, M.T. et al. (2016). "LIME". KDD.
  • Selvaraju, R.R. et al. (2017). "Grad-CAM". ICCV.

라이브러리

  • SHAP: https://shap.readthedocs.io/
  • LIME: https://github.com/marcotcr/lime
  • Captum: https://captum.ai/
  • InterpretML: https://interpret.ml/