XAI
Explainable AI
Explainable AI. Interprets a model's decision-making process. LIME, SHAP.
Explainable AI
Explainable AI. Interprets a model's decision-making process. LIME, SHAP.
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.
# 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))
| 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.
"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
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.