SHAP
SHapley Additive exPlanations
A game-theory-based model interpretation technique. Quantifies how much each feature contributed to a prediction. A core tool of XAI (explainable AI).
SHapley Additive exPlanations
A game-theory-based model interpretation technique. Quantifies how much each feature contributed to a prediction. A core tool of XAI (explainable AI).
SHAP (SHapley Additive exPlanations) is a model interpretation technique that applies the Shapley Value from game theory to machine learning. It quantifies numerically how much each feature contributed to an individual prediction, explaining "why this prediction was made." For example, when a loan is rejected, it can provide quantitative grounds such as "income contributed -0.3 and credit score contributed -0.25."
It was presented in a NIPS paper by Scott Lundberg of the University of Washington in 2017, and is currently the most widely used technique in the field of XAI (Explainable AI). Unlike LIME (Local Interpretable Model-agnostic Explanations), it has a solid theoretical foundation and inherits the axiomatic properties of the Shapley Value, such as Consistency, Local Accuracy, Efficiency, and Symmetry.
The core idea is to treat each feature as a "player" and the prediction result as the "payout," and to distribute, in a game-theoretically fair way, how much each player contributed to the team (the model). Mathematically, a SHAP value is the weighted average of the marginal contribution over all possible feature subsets (2^n of them). The computational cost is exponential, but efficient approximation algorithms exist, such as TreeSHAP (tree-based models, O(TL^2)), DeepSHAP (deep learning), and KernelSHAP (model-agnostic).
It is essential in regulated industries such as finance, healthcare, law, and insurance when there is an obligation to explain models. It can address the EU GDPR's "Right to Explanation," the U.S. FCRA/ECOA obligation to disclose reasons for loan rejection, and the Financial Supervisory Service's AI model validation guidelines. It is also used for model debugging, validating feature engineering, and detecting data drift. Recently, SHAP has also been extended to token-level attribution analysis for LLMs.
import shap
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
# ๋ฐ์ดํฐ ๋ก๋ ๋ฐ ๋ถํ
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.2, random_state=42
)
# XGBoost ๋ชจ๋ธ ํ์ต
model = xgb.XGBClassifier(n_estimators=100, max_depth=4)
model.fit(X_train, y_train)
# SHAP Explainer ์์ฑ (TreeSHAP ์ฌ์ฉ)
explainer = shap.TreeExplainer(model)
# ํ
์คํธ ๋ฐ์ดํฐ์ ๋ํ SHAP ๊ฐ ๊ณ์ฐ
shap_values = explainer.shap_values(X_test)
# ์ ์ฒด ํผ์ฒ ์ค์๋ ์๊ฐํ (Summary Plot)
shap.summary_plot(shap_values, X_test, feature_names=data.feature_names)
# ๊ฐ๋ณ ์์ธก ์ค๋ช
(Force Plot)
shap.force_plot(
explainer.expected_value,
shap_values[0],
X_test[0],
feature_names=data.feature_names
)
# Waterfall Plot (๋จ์ผ ์ํ ์์ธ ๋ถ์)
shap.waterfall_plot(
shap.Explanation(
values=shap_values[0],
base_values=explainer.expected_value,
data=X_test[0],
feature_names=data.feature_names
)
)
# SHAP ๊ฐ ํด์:
# - ์์: ํด๋น ํผ์ฒ๊ฐ ์์ธก์ ๋์ด๋ ๋ฐฉํฅ์ผ๋ก ๊ธฐ์ฌ
# - ์์: ํด๋น ํผ์ฒ๊ฐ ์์ธก์ ๋ฎ์ถ๋ ๋ฐฉํฅ์ผ๋ก ๊ธฐ์ฌ
# - ์ ๋๊ฐ: ๊ธฐ์ฌ์ ํฌ๊ธฐ
# === DeepSHAP: ๋ฅ๋ฌ๋ ๋ชจ๋ธ ์ค๋ช
===
import tensorflow as tf
# ๋ฅ๋ฌ๋ ๋ชจ๋ธ ์์ฑ
deep_model = tf.keras.Sequential([
tf.keras.layers.Dense(64, activation='relu', input_shape=(30,)),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
deep_model.compile(optimizer='adam', loss='binary_crossentropy')
deep_model.fit(X_train, y_train, epochs=10, verbose=0)
# DeepExplainer ์ฌ์ฉ
deep_explainer = shap.DeepExplainer(deep_model, X_train[:100])
deep_shap_values = deep_explainer.shap_values(X_test[:10])
# === KernelSHAP: ๋ชจ๋ธ ๋ถ๊ฐ์ง๋ก (์ด๋ค ๋ชจ๋ธ์ด๋ ์ ์ฉ) ===
def model_predict(X):
"""๋ธ๋๋ฐ์ค ๋ชจ๋ธ์ ์์ธก ํจ์"""
return model.predict_proba(X)[:, 1]
kernel_explainer = shap.KernelExplainer(model_predict, shap.sample(X_train, 100))
kernel_shap_values = kernel_explainer.shap_values(X_test[:5], nsamples=500)
# === ์ ์ญ ํผ์ฒ ์ค์๋ (Global Feature Importance) ===
# ๋ชจ๋ ์ํ์ ๋ํ SHAP ๊ฐ์ ์ ๋๊ฐ ํ๊ท
global_importance = np.abs(shap_values).mean(axis=0)
feature_ranking = sorted(
zip(data.feature_names, global_importance),
key=lambda x: x[1], reverse=True
)
print("์ ์ญ ํผ์ฒ ์ค์๋ Top 5:")
for name, importance in feature_ranking[:5]:
print(f" {name}: {importance:.4f}")
# === Dependence Plot: ํผ์ฒ ๊ฐ ์ํธ์์ฉ ๋ถ์ ===
shap.dependence_plot(
"mean radius",
shap_values, X_test,
feature_names=data.feature_names,
interaction_index="mean texture" # ์ํธ์์ฉ ํผ์ฒ
)
# === Force Plot: ๊ฐ๋ณ ์์ธก ์ค๋ช
===
# ๋จ์ผ ์ํ์ SHAP ๊ฐ์ ๋ง๋ ๊ทธ๋ํ๋ก ํ์
shap.force_plot(
explainer.expected_value,
shap_values[0],
X_test[0],
feature_names=data.feature_names,
matplotlib=True
)
# === Waterfall Plot: ๊ธฐ์ค๊ฐ์์ ์์ธก๊น์ง ===
# ๊ฐ ํผ์ฒ๊ฐ ์์ธก์ ์ด๋ป๊ฒ ๋ฐ์ด์ฌ๋ฆฌ๊ณ ๋ด๋ฆฌ๋์ง ์๊ฐํ
shap.waterfall_plot(
shap.Explanation(
values=shap_values[0],
base_values=explainer.expected_value,
data=X_test[0],
feature_names=data.feature_names
)
)
# === Batch ์ฒ๋ฆฌ ๋ฐ ์ ์ฅ ===
# ๋๊ท๋ชจ ๋ฐ์ดํฐ์
์์ ํจ์จ์ ์ผ๋ก SHAP ๊ณ์ฐ
def compute_shap_batch(model, X, batch_size=100):
"""๋ฐฐ์น ๋จ์๋ก SHAP ๊ฐ ๊ณ์ฐ"""
all_shap_values = []
explainer = shap.TreeExplainer(model)
for i in range(0, len(X), batch_size):
batch = X[i:i+batch_size]
shap_values = explainer.shap_values(batch)
all_shap_values.append(shap_values)
return np.concatenate(all_shap_values, axis=0)
# SHAP ๊ฐ ์ ์ฅ ๋ฐ ๋ก๋
import pickle
with open('shap_values.pkl', 'wb') as f:
pickle.dump(shap_values, f)
# === LLM/Transformer ๋ชจ๋ธ SHAP ===
# Transformer ๊ธฐ๋ฐ ๋ชจ๋ธ์๋ SHAP ์ ์ฉ ๊ฐ๋ฅ
# PartitionExplainer: ํ ํฐ ์์ค ๊ธฐ์ฌ๋ ๋ถ์
import shap
def explain_text_classification(text, model, tokenizer):
"""ํ
์คํธ ๋ถ๋ฅ ๋ชจ๋ธ์ SHAP ๋ถ์"""
def predict_fn(texts):
inputs = tokenizer(texts, return_tensors='pt', padding=True)
outputs = model(**inputs)
return outputs.logits.softmax(dim=-1).detach().numpy()
explainer = shap.Explainer(predict_fn, tokenizer)
shap_values = explainer([text])
return shap_values
# SHAP์ ๋ชจ๋ธ ๋๋ฒ๊น
๊ณผ ๊ท์ ๋์์ ํ์ ๋๊ตฌ์
๋๋ค
"To respond to the Financial Supervisory Service inspection, a SHAP report is a must. You need to present the reason for a loan rejection quantitatively, not as 'because the credit score is low' but as 'per SHAP analysis, credit score contributed -0.35 and delinquency history contributed -0.28.'"
"SHAP applies the Shapley Value from game theory to ML. It is theoretically fair because it averages each feature's contribution over all possible feature combinations. With TreeSHAP, you can compute efficiently in O(TL^2) for tree-based models."
"If there are cases where the model makes strange predictions, look at the SHAP waterfall plot. It immediately shows which features pushed the prediction up and by how much. You can tell right away whether it's a data outlier or a feature engineering problem."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Exact SHAP grows exponentially with the number of features. With 100 features it is infeasible to compute. Use approximation algorithms such as TreeSHAP and KernelSHAP.
For highly correlated features, SHAP values are split between them. If features A and B have a 0.95 correlation, the contribution is divided between the two, making individual interpretation difficult.
Sample the background data representatively and analyze feature correlations first. For regulatory compliance, document the feature definitions and data ranges along with the SHAP values.