πŸ€– AI/ML

XAI

Explainable AI

Explainable AI. Interprets a model's decision-making process. LIME, SHAP.

πŸ“– Detailed Explanation

XAI (Explainable AI) is a technology field that interprets and explains the decision-making process of AI models so that humans can understand it. As deep learning models have become more complex, the 'black box' problem has emerged, and there are now many situations in which it is impossible to understand why a model made a particular decision. XAI resolves this opacity to build trust in AI systems, meet regulatory requirements, and provide the insights needed to improve models.

XAI techniques are broadly classified into two types. First, **Intrinsic methods**, in which the model itself is interpretable, use models whose structure is transparent in itself, such as decision trees or linear regression. Second, **Post-hoc methods** explain a complex black-box model with a separate technique after training. LIME (Local Interpretable Model-agnostic Explanations) and SHAP (SHapley Additive exPlanations) are representative post-hoc techniques.

LIME generates explanations by training a locally interpretable model for each individual prediction. It generates samples around the input data and uses the original model's predictions to train a simple interpretable model (e.g., a linear model). SHAP mathematically quantifies the degree to which each feature contributed to a prediction, based on the Shapley value from game theory. SHAP values satisfy theoretical properties such as consistency, local accuracy, and missingness.

XAI is essential in domains that require accountability for explanations, such as medical diagnosis, financial credit scoring, legal decision-making, and autonomous driving. Regulations such as the EU AI Act are also strengthening transparency requirements for high-risk AI systems, so the importance of XAI continues to grow. Domain-specific XAI techniques such as Grad-CAM (image classification), Attention Visualization (NLP), and Feature Importance (structured data) are also being actively researched.

πŸ’» Code Example

# XAI 예제: SHAPκ³Ό LIME을 μ‚¬μš©ν•œ λͺ¨λΈ μ„€λͺ…
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import shap
import lime.lime_tabular

# 데이터 λ‘œλ“œ 및 μ€€λΉ„
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# λͺ¨λΈ ν•™μŠ΅
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)

print(f"λͺ¨λΈ 정확도: {model.score(X_test, y_test):.4f}")

# ============================================
# SHAP (SHapley Additive exPlanations)
# ============================================
# TreeExplainer: 트리 기반 λͺ¨λΈμ— μ΅œμ ν™”
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_test)

# 단일 μ˜ˆμΈ‘μ— λŒ€ν•œ SHAP μ„€λͺ…
sample_idx = 0
print(f"\n[SHAP] μƒ˜ν”Œ {sample_idx}의 예츑: {model.predict(X_test.iloc[[sample_idx]])[0]}")
print("μ£Όμš” κΈ°μ—¬ νŠΉμ„±:")
feature_importance = pd.DataFrame({
    'feature': X.columns,
    'shap_value': shap_values[1][sample_idx]  # class 1에 λŒ€ν•œ κΈ°μ—¬
}).sort_values('shap_value', key=abs, ascending=False)
print(feature_importance.head(5))

# 전체 데이터에 λŒ€ν•œ νŠΉμ„± μ€‘μš”λ„ μš”μ•½
print("\n[SHAP] μ „μ—­ νŠΉμ„± μ€‘μš”λ„ (평균 μ ˆλŒ€κ°’):")
mean_shap = np.abs(shap_values[1]).mean(axis=0)
global_importance = pd.DataFrame({
    'feature': X.columns,
    'importance': mean_shap
}).sort_values('importance', ascending=False)
print(global_importance.head(10))

# ============================================
# LIME (Local Interpretable Model-agnostic Explanations)
# ============================================
lime_explainer = lime.lime_tabular.LimeTabularExplainer(
    training_data=X_train.values,
    feature_names=X.columns.tolist(),
    class_names=['μ•…μ„±', 'μ–‘μ„±'],
    mode='classification'
)

# 단일 μ˜ˆμΈ‘μ— λŒ€ν•œ LIME μ„€λͺ…
lime_exp = lime_explainer.explain_instance(
    data_row=X_test.iloc[sample_idx].values,
    predict_fn=model.predict_proba,
    num_features=10
)

print(f"\n[LIME] μƒ˜ν”Œ {sample_idx}의 μ„€λͺ…:")
print("νŠΉμ„±λ³„ 기여도:")
for feature, weight in lime_exp.as_list():
    print(f"  {feature}: {weight:.4f}")

# ============================================
# Permutation Importance (μˆœμ—΄ μ€‘μš”λ„)
# ============================================
from sklearn.inspection import permutation_importance

perm_importance = permutation_importance(
    model, X_test, y_test, n_repeats=30, random_state=42
)

print("\n[Permutation Importance] νŠΉμ„± μ€‘μš”λ„:")
perm_df = pd.DataFrame({
    'feature': X.columns,
    'importance_mean': perm_importance.importances_mean,
    'importance_std': perm_importance.importances_std
}).sort_values('importance_mean', ascending=False)
print(perm_df.head(10))

πŸ“Š Performance & Cost

Technique Computational Complexity Applicable Scope Explanation Scope
SHAP (TreeExplainer) O(T*L*D) - Fast Tree-based models Global + Local
SHAP (KernelExplainer) O(N*2^M) - Slow All models Global + Local
LIME O(N*M) - Medium All models Local
Grad-CAM O(1) - Fast CNN models Local (image)
Permutation Importance O(M*R) - Medium All models Global

* T: number of trees, L: maximum leaf nodes, D: feature dimension, N: number of samples, M: number of features, R: number of iterations

Performance tip: SHAP TreeExplainer can compute within seconds on tree-based models such as XGBoost and LightGBM. For deep learning models, use DeepExplainer or GradientExplainer. LIME requires hundreds of model calls per sample, so parallel processing is recommended for large-scale batch analysis.

πŸ—£ How It's Said in Practice

"Please attach an XAI explanation to this loan rejection decision."

-> When you need to explain the reason for rejection to the customer for regulatory compliance

"Looking at the SHAP summary plot, this feature has the greatest impact on the prediction."

-> When debugging the model or deciding the direction of feature engineering

"Let's use Grad-CAM to visualize where the model looked to make its judgment."

-> When checking the attention regions of an image classification model

"An XAI report is mandatory for EU AI Act compliance."

-> When discussing regulatory compliance for high-risk AI systems

⚠ Common Mistakes & Cautions

Misinterpreting SHAP values as causal relationships

SHAP values are correlation-based contributions and do not imply causal impact. A high SHAP value for feature A does not guarantee that changing A will change the outcome.

Ignoring LIME's instability

Because LIME is based on random sampling, the explanation may differ each time it is run on the same input. For important decisions, run it multiple times to check consistency.

Indiscriminate use of KernelExplainer on complex models

KernelExplainer is model-agnostic but very slow. Use TreeExplainer for tree models and DeepExplainer for deep learning.

Correct approach: choose an XAI technique that fits the purpose

Choose according to the use case: SHAP summary plot when global understanding is needed, LIME or SHAP force plot for explaining individual predictions, Grad-CAM for image models, and so on.

πŸ”— Related Terms

πŸ“š Learn More