[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,117 +1,244 @@
|
||||
---
|
||||
id: wiki-2026-0508-explainable-ai-xai
|
||||
title: Explainable AI XAI
|
||||
title: Explainable AI (XAI)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [XAI, interpretability, SHAP, LIME, attention, mechanistic interpretability, saliency]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-consolidated, technical-documentation]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [ai, interpretability, xai, shap, lime, attention, mechanistic, transparency]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Python
|
||||
framework: SHAP / LIME / Captum / TransformerLens
|
||||
---
|
||||
|
||||
# [[Explainable-AI (XAI)|Explainable-AI (XAI)]]
|
||||
# Explainable AI (XAI)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "블랙박스의 뚜껑을 열다: AI가 복잡한 신경망 속에서 내린 결론의 근거를 인간이 이해할 수 있는 언어와 시각 자료로 설명함으로써, 기계에 대한 신뢰를 구축하고 오류를 검증 가능하게 만드는 투명성의 기술."
|
||||
## 매 한 줄
|
||||
> **"매 black-box 의 decision 의 understand"**. 매 SHAP / LIME (post-hoc), 매 attention / saliency, 매 mechanistic interpretability (modern). 매 EU AI Act 의 high-risk 의 require. 매 trade-off: 매 accuracy ↔ interpretability (often false dichotomy).
|
||||
|
||||
---
|
||||
## 매 핵심
|
||||
|
||||
> "모델이 '왜' 그런 판단을 내렸는지 인간의 언어로 증명하라" — 결과뿐만 아니라 그 결과에 도출된 과정과 근거를 인간이 이해할 수 있도록 제공하여, AI의 블랙박스 문제를 해결하고 신뢰성을 확보하는 기술.
|
||||
### 매 dimension
|
||||
- **Local vs global**: 매 single prediction vs overall model.
|
||||
- **Model-specific vs agnostic**: 매 internals vs black-box.
|
||||
- **Post-hoc vs intrinsic**: 매 after training vs by design.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
설명 가능한 AI(XAI, Explainable-AI)는 AI 모델의 결과물에 대해 인간이 이해할 수 있는 설명을 제공하는 것을 목표로 합니다.
|
||||
### 매 method
|
||||
- **Feature importance**: SHAP, LIME, permutation.
|
||||
- **Saliency**: Grad-CAM, Integrated Gradients.
|
||||
- **Attention**: 매 transformer.
|
||||
- **Counterfactual**: 매 minimal change.
|
||||
- **Mechanistic**: 매 circuit, SAE, attribution.
|
||||
- **Concept-based**: TCAV.
|
||||
|
||||
1. **왜 필요한가?**:
|
||||
* **Trust**: 의료, 금융 등 생명/자산과 직결된 분야에서는 "왜"라는 질문에 답할 수 있어야 함. ([[Ethics & AI|Ethics & AI]]와 연결)
|
||||
* **Debugging**: 모델이 엉뚱한 곳을 보고 학습하는지(예: 배경을 보고 늑대를 분류) 확인.
|
||||
* **Regulatory Compliance**: AI의 결정에 대해 사용자가 '설명받을 권리'를 법적으로 보장받는 추세.
|
||||
2. **주요 기법**:
|
||||
* **LIME/SHAP**: 입력값의 변화가 결과에 미치는 영향을 측정하여 중요도 표시.
|
||||
* **Attention Maps**: 모델이 이미지의 어느 부분이나 텍스트의 어느 단어에 집중했는지 가시화.
|
||||
### 매 modern (mechanistic)
|
||||
- **TransformerLens** (Anthropic).
|
||||
- **Sparse Autoencoders** (SAE).
|
||||
- **Activation Patching**.
|
||||
- **Probing**.
|
||||
- **Anthropic Circuits**: 매 Towards Monosemanticity.
|
||||
|
||||
---
|
||||
### 매 응용
|
||||
1. **Healthcare**: 매 diagnostic explain.
|
||||
2. **Finance**: 매 credit decision.
|
||||
3. **Justice**: 매 risk score.
|
||||
4. **Debugging**: 매 model failure.
|
||||
5. **Compliance**: 매 EU AI Act.
|
||||
6. **AI safety**: 매 alignment audit.
|
||||
|
||||
- **추출된 패턴:** 모델 내부의 복잡한 연산 과정을 중요도 맵(Heatmap), 특징 기여도(Feature Attribution), 혹은 자연어 설명으로 변환하여 사용자에게 투명성을 제공하는 해석 패턴.
|
||||
- **주요 기법:**
|
||||
- **LIME / SHAP:** 모델의 종류와 상관없이 특정 입력에 대한 예측 근거를 분석 (Post-hoc).
|
||||
- **Attention Visualization:** 트랜스포머 모델이 어떤 단어나 이미지 영역에 집중했는지 시각화.
|
||||
- **CAM (Class Activation Map):** 이미지 분류 시 어떤 픽셀 영역이 결정에 결정적이었는지 노출.
|
||||
- **Rule-based Surro[[Gates|Gates]]:** 복잡한 모델을 단순한 의사결정 나무 등으로 근사하여 설명.
|
||||
- **의의:** 의료, 금융, 법률 등 고위험 의사결정 분야에서 AI 도입을 가능하게 하는 필수 조건.
|
||||
## 💻 패턴
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 성능(Accuracy)과 설명력(Interpretability)이 반비례 관계라는 정책이 주류였으나, 현대 정책은 지능이 높으면서도 스스로의 논리 구조를 브리핑하는 '내재적 설명 정책'을 추구함(RL Update).
|
||||
- **정책 변화(RL Update)**: 단순 가시화를 넘어, AI가 자신의 사고 과정을 단계별로 풀어서 설명하는 CoT(Chain-of-Thought) 정책이 LLM 시대의 핵심 XAI 방법론으로 부상함. (Chain-of-Thought와 연결)
|
||||
### SHAP (TreeExplainer)
|
||||
```python
|
||||
import shap
|
||||
import xgboost as xgb
|
||||
|
||||
---
|
||||
|
||||
- **과거 데이터와의 충돌:** 단순히 성능(Accuracy)만 높으면 된다는 관점에서, 성능을 조금 희생하더라도 '설명 가능성(Interpretability)'이 담보되어야 한다는 신뢰 중심 관점으로 전환.
|
||||
- **정책 변화:** Antigravity 프로젝트는 에이전트가 제안한 코드나 지식 보강 내용에 대해, 참고한 소스 문서와 추론 과정을 'Rationale' 세션으로 명시하여 사용자 검증을 돕도록 설계함.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Ethics & AI|Ethics & AI]], [[Chain-of-Thought (CoT 사고 사슬)|Chain-of-Thought (CoT 사고 사슬)]], Trust and Perspective, Transparency, Bias-Variance Tradeoff
|
||||
- **Modern Tech/Tools**: SHAP, LIME, Captum (PyTorch), Integrated Gradients.
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
- [[Trustworthy-AI|Trustworthy-AI]], AI-Ethics, Decision-Making, [[Feature-Engineering|Feature-Engineering]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Explainable-AI-XAI.md
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
model = xgb.XGBClassifier().fit(X, y)
|
||||
explainer = shap.TreeExplainer(model)
|
||||
shap_values = explainer.shap_values(X_test)
|
||||
shap.summary_plot(shap_values, X_test)
|
||||
shap.force_plot(explainer.expected_value, shap_values[0], X_test.iloc[0])
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### LIME
|
||||
```python
|
||||
from lime.lime_tabular import LimeTabularExplainer
|
||||
explainer = LimeTabularExplainer(X_train, feature_names=cols, class_names=['neg', 'pos'])
|
||||
exp = explainer.explain_instance(X_test[0], model.predict_proba, num_features=10)
|
||||
exp.show_in_notebook()
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Integrated Gradients (Captum)
|
||||
```python
|
||||
import captum
|
||||
from captum.attr import IntegratedGradients
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
ig = IntegratedGradients(model)
|
||||
attributions = ig.attribute(input_tensor, target=label_idx, n_steps=50)
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Grad-CAM (vision)
|
||||
```python
|
||||
from captum.attr import LayerGradCam
|
||||
import torchvision.models as models
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
model = models.resnet50(pretrained=True).eval()
|
||||
gc = LayerGradCam(model, model.layer4[-1])
|
||||
attribution = gc.attribute(input_image, target=class_idx)
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Attention visualization (transformer)
|
||||
```python
|
||||
import torch
|
||||
def attention_rollout(attentions, layer):
|
||||
"""매 average heads, multiply layers."""
|
||||
A = attentions[layer] # 매 [B, H, T, T]
|
||||
A = A.mean(dim=1) # 매 average heads
|
||||
return A
|
||||
```
|
||||
|
||||
### Counterfactual explanation
|
||||
```python
|
||||
def counterfactual(model, x, target_class, max_iter=100):
|
||||
"""매 minimum change to flip prediction."""
|
||||
x_cf = x.clone().detach().requires_grad_(True)
|
||||
optim = torch.optim.Adam([x_cf], lr=0.01)
|
||||
for _ in range(max_iter):
|
||||
pred = model(x_cf)
|
||||
if pred.argmax() == target_class: return x_cf
|
||||
loss = F.cross_entropy(pred, torch.tensor([target_class])) + 0.1 * (x_cf - x).norm()
|
||||
optim.zero_grad(); loss.backward(); optim.step()
|
||||
return x_cf
|
||||
```
|
||||
|
||||
### Permutation importance
|
||||
```python
|
||||
from sklearn.inspection import permutation_importance
|
||||
result = permutation_importance(model, X_val, y_val, n_repeats=10, random_state=0)
|
||||
sorted_idx = result.importances_mean.argsort()[::-1]
|
||||
for i in sorted_idx[:10]:
|
||||
print(f'{cols[i]}: {result.importances_mean[i]:.4f}')
|
||||
```
|
||||
|
||||
### TCAV (concept-based)
|
||||
```python
|
||||
def tcav_score(model, layer, concept_examples, random_examples, target_class):
|
||||
cav = train_cav(layer.activations(concept_examples), layer.activations(random_examples))
|
||||
sensitivities = []
|
||||
for x in target_class_examples:
|
||||
grad = compute_gradient_at_layer(model, x, target_class, layer)
|
||||
sensitivities.append((grad @ cav) > 0)
|
||||
return np.mean(sensitivities)
|
||||
```
|
||||
|
||||
### Mechanistic — activation patching
|
||||
```python
|
||||
import transformer_lens as tl
|
||||
|
||||
model = tl.HookedTransformer.from_pretrained('gpt2')
|
||||
def patched_forward(prompt_clean, prompt_corrupt, layer):
|
||||
_, clean_cache = model.run_with_cache(prompt_clean)
|
||||
|
||||
def patch_hook(activation, hook):
|
||||
return clean_cache[hook.name]
|
||||
|
||||
return model.run_with_hooks(prompt_corrupt, fwd_hooks=[(f'blocks.{layer}.attn.hook_z', patch_hook)])
|
||||
```
|
||||
|
||||
### Sparse Autoencoder (SAE)
|
||||
```python
|
||||
class SAE(nn.Module):
|
||||
def __init__(self, d_model, d_sae=32768, l1_coef=1e-3):
|
||||
super().__init__()
|
||||
self.W_enc = nn.Linear(d_model, d_sae)
|
||||
self.W_dec = nn.Linear(d_sae, d_model, bias=False)
|
||||
self.l1_coef = l1_coef
|
||||
|
||||
def forward(self, x):
|
||||
z = F.relu(self.W_enc(x))
|
||||
x_recon = self.W_dec(z)
|
||||
recon_loss = F.mse_loss(x_recon, x)
|
||||
sparsity_loss = self.l1_coef * z.abs().sum(-1).mean()
|
||||
return x_recon, recon_loss + sparsity_loss
|
||||
```
|
||||
|
||||
### Probing classifier
|
||||
```python
|
||||
def probe(activations, labels, layer):
|
||||
X = activations[layer].detach().numpy()
|
||||
clf = LogisticRegression(max_iter=1000).fit(X, labels)
|
||||
return clf.score(X_val, y_val)
|
||||
```
|
||||
|
||||
### Model card explainability
|
||||
```yaml
|
||||
explainability:
|
||||
method: SHAP TreeExplainer
|
||||
global_top_features:
|
||||
- credit_score: 0.34
|
||||
- debt_to_income: 0.18
|
||||
- employment_years: 0.12
|
||||
per_decision_explanation: available_in_ui
|
||||
counterfactual_offered: yes
|
||||
```
|
||||
|
||||
### LLM explanation prompt
|
||||
```python
|
||||
def llm_explain_decision(prediction, features):
|
||||
prompt = f"""You are explaining an ML decision. Use ONLY the features given.
|
||||
Prediction: {prediction}
|
||||
Features: {features}
|
||||
|
||||
Output:
|
||||
1. Top 3 reasons
|
||||
2. What change would flip the decision
|
||||
3. Limitations of this explanation"""
|
||||
return llm.generate(prompt)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Method |
|
||||
|---|---|
|
||||
| Tabular ML | SHAP TreeExplainer |
|
||||
| Black-box agnostic | LIME / SHAP KernelExplainer |
|
||||
| Vision | Grad-CAM / Integrated Gradients |
|
||||
| NLP | Attention + token attribution |
|
||||
| LLM internals | TransformerLens / SAE |
|
||||
| User-facing | Counterfactual + plain language |
|
||||
| Compliance | Model card + global + local |
|
||||
|
||||
**기본값**: 매 SHAP global + local + 매 counterfactual + 매 model card. 매 LLM internals = SAE + activation patching.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[AI]] · [[Interpretability]]
|
||||
- 변형: [[SHAP]] · [[LIME]] · [[Mechanistic-Interpretability]]
|
||||
- 응용: [[Model-Card]] · [[EU-AI-Act]] · [[AI-Safety]]
|
||||
- Adjacent: [[Saliency-Map]] · [[Integrated-Gradients]] · [[Sparse-Autoencoder]] · [[TransformerLens]] · [[Ethics & AI]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 high-risk EU. 매 healthcare / finance. 매 model debug.
|
||||
**언제 X**: 매 low-stakes. 매 explanation 의 misleading 의 risk.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single number trust**: 매 SHAP 의 misuse.
|
||||
- **Saliency as causal**: 매 correlation only.
|
||||
- **Attention = explanation**: 매 not always (Jain & Wallace 2019).
|
||||
- **Post-hoc only**: 매 design 의 ignore.
|
||||
- **Explanation 의 misleading**: 매 false confidence.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Lundberg SHAP 2017, Ribeiro LIME 2016, Olah Anthropic 2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — XAI methods + 매 SHAP / LIME / IG / counterfactual / SAE / probing code |
|
||||
|
||||
Reference in New Issue
Block a user