SHAP 값: 전역 및 국소 특성 중요도
그래디언트 부스팅 모델의 SHAP 값을 계산하고, 벌집 모양 및 막대 요약 그래프를 그리며, 단일 예측 결과를 비기술 이해관계자에게 설명하는 방법을 학습합니다.
SHAP 값: 전역 및 국소 특성 중요도은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Machine Learning Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Model Explainability Matters
Explainability is the ability to understand why a model made a specific prediction. In high-stakes domains like lending, healthcare, and hiring, regulators and users demand explanations — not just accurate predictions. SHAP (SHapley Additive exPlanations) provides a mathematically principled framework rooted in cooperative game theory to deliver these explanations for any model.
Shapley Values: The Game Theory Origin
SHAP values borrow from Shapley values in cooperative game theory, where players (features) collaborate to produce an outcome (prediction). Each feature receives a fair share of credit by averaging its marginal contribution across all possible feature orderings. This makes SHAP the only additive attribution method satisfying the axioms of efficiency, symmetry, dummy, and additivity.
Installing and Importing SHAP
The shap library supports tree models, neural networks, and any black-box model. Install it with pip install shap and import it alongside your trained model. SHAP's explainers are model-type-aware: TreeExplainer for gradient boosting and random forests gives exact values in O(T·D²) time, far faster than the naive exponential-time Shapley computation.
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
)
model = xgb.XGBClassifier(n_estimators=100, use_label_encoder=False, eval_metric='logloss')
model.fit(X_train, y_train)
explainer = shap.TreeExplainer(model)Computing SHAP Values for the Test Set
Call explainer.shap_values(X_test) to produce a matrix where each row is a sample and each column is a feature. The SHAP value for feature j in sample i represents the contribution of feature j to pushing the prediction away from the expected base value. Positive values push toward the positive class; negative values push toward the negative class.
shap_values = explainer.shap_values(X_test)
print('SHAP values shape:', shap_values.shape) # (n_samples, n_features)
print('Base value (expected prediction):', explainer.expected_value)
print('First sample SHAP values:', shap_values[0])Global Importance: Bar Plot
Global feature importance summarises which features matter most across all predictions. The SHAP summary_plot in bar mode shows the mean absolute SHAP value per feature, ranking them from most to least important. This replaces the naive built-in feature importance that only counts split counts, which is biased toward high-cardinality features.
import matplotlib.pyplot as plt
# Bar plot: mean |SHAP| per feature
shap.summary_plot(shap_values, X_test,
feature_names=data.feature_names,
plot_type='bar')
plt.tight_layout()
plt.savefig('shap_bar.png', dpi=150)Global Importance: Beeswarm Plot
The beeswarm plot (default summary_plot) is richer than a bar chart: each dot represents one sample, coloured by feature value (red = high, blue = low). The x-axis shows the SHAP value, so you can see not only which features matter but also in which direction a high or low feature value pushes predictions. This reveals nonlinear and interaction effects at a glance.
shap.summary_plot(shap_values, X_test,
feature_names=data.feature_names)
# Dots to the right = positive contribution to predicted class
# Red dots far right = high feature value strongly increases predictionLocal Explanation: Force Plot
A force plot explains a single prediction. It shows the base value on the left and the final prediction on the right, with features as arrows that push the output higher (red) or lower (blue). The width of each arrow is proportional to the feature's SHAP value. This is the explanation you would show a loan officer asking 'why was this application denied?'
# Explain the first test sample
i = 0
shap.force_plot(
explainer.expected_value,
shap_values[i],
X_test[i],
feature_names=data.feature_names,
matplotlib=True
)Local Explanation: Waterfall Plot
The waterfall plot is a cleaner alternative to the force plot for a single sample. It stacks SHAP contributions vertically from the base value, showing each feature's contribution as a bar segment. Positive contributions are red and push toward the top; negative contributions are blue and pull down. The final stack total equals the model's raw output for that sample.
import shap
explanation = shap.Explanation(
values=shap_values[0],
base_values=explainer.expected_value,
data=X_test[0],
feature_names=list(data.feature_names)
)
shap.waterfall_plot(explanation)Dependence Plot: Feature Interactions
A SHAP dependence plot shows how a single feature's SHAP value changes as its raw value changes, coloured by a second feature to reveal interactions. For example, plotting 'worst radius' coloured by 'mean texture' reveals whether the effect of radius depends on texture. This goes beyond ordinary partial-dependence plots by accounting for all feature interactions naturally.
shap.dependence_plot(
'worst radius', # feature to plot on x-axis
shap_values,
X_test,
feature_names=list(data.feature_names),
interaction_index='mean texture' # colour by this feature
)SHAP with Any Model: KernelExplainer
When the model is a black box (SVM, neural network, any sklearn estimator), use shap.KernelExplainer, which approximates Shapley values by sampling coalitions and fitting a weighted linear model locally. It is model-agnostic but slower than TreeExplainer. Provide a background dataset summary (e.g., K-Means centroids) to speed up computation on large datasets.
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import shap
import numpy as np
pipeline = Pipeline([('scaler', StandardScaler()), ('svm', SVC(probability=True))])
pipeline.fit(X_train, y_train)
# Use 50 background samples for speed
background = shap.kmeans(X_train, 50)
explainer_k = shap.KernelExplainer(pipeline.predict_proba, background)
shap_vals_k = explainer_k.shap_values(X_test[:10]) # Explain 10 samplesValidation: SHAP Values Sum to Prediction
A key property of SHAP is efficiency: the sum of all SHAP values for a sample plus the base value must equal the model's raw output. Verifying this sanity check confirms the explainer is working correctly. Any discrepancy indicates a mismatch between the explainer type and the model, or incorrect background data.
import numpy as np
# For tree models, verify SHAP values sum to log-odds output
base = explainer.expected_value
for i in range(5):
shap_sum = shap_values[i].sum() + base
raw_pred = model.predict(X_test[i:i+1], output_margin=True)[0]
print(f'Sample {i}: SHAP sum={shap_sum:.4f}, model output={raw_pred:.4f}, match={abs(shap_sum-raw_pred)<1e-4}')Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: SHAP values quantify each feature's contribution to a prediction using Shapley values from game theory, global summaries (bar and beeswarm plots) reveal overall feature importance and direction, and local explanations (force and waterfall plots) justify individual predictions. Next up we explore LIME as an alternative model-agnostic explanation approach.
자주 묻는 질문
“SHAP 값: 전역 및 국소 특성 중요도” 강의는 무료인가요?
네 — “SHAP 값: 전역 및 국소 특성 중요도” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“SHAP 값: 전역 및 국소 특성 중요도”에서 뭘 배우나요?
그래디언트 부스팅 모델의 SHAP 값을 계산하고, 벌집 모양 및 막대 요약 그래프를 그리며, 단일 예측 결과를 비기술 이해관계자에게 설명하는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“SHAP 값: 전역 및 국소 특성 중요도” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- SHAP 값: 전역 및 국소 특성 중요도
- LIME: 국소 해석 가능한 모델 불문 설명
- 공정성 지표: 인구통계학적 동등성과 동등한 기회
- 편향 완화 전략: 전처리, 학습 중 처리, 후처리