SHAP vs LIME vs feature importance: which explanation should you trust?
SHAP, LIME and built-in feature importance answer different questions. A side-by-side comparison on one decision-tree classifier, with the maths, runnable Python and a table for choosing between them.
SHAP splits one prediction into exact shares per feature, using Shapley values from cooperative game theory, and those shares add up to the model’s output. LIME fits a small linear model around one prediction and reads its weights. Conventional feature importance describes the whole model, never a single prediction. Use SHAP when you need consistent local and global explanations, LIME when you need a quick model-agnostic look at one case, and feature importance for a first overview of a tree model.
This is the comparison behind our paper Exploring Explainable Artificial Intelligence: A Comparative Analysis of Interpretability Techniques (IJARCCE 13(3), 2024). We applied all three techniques to the same decision-tree classifier, so any difference comes from the explainer rather than the model. This article rebuilds that set-up with code you can run, and adds the maths that explains why the answers differ.
Key points
- SHAP is additive: the base value plus every feature’s contribution equals the prediction, exactly.
- LIME is local and approximate: it explains a surrogate model, so its faithfulness depends on how well that surrogate fits.
- Impurity-based feature importance is global and unsigned: it says how much the model leans on a feature, not in which direction.
- For tree models, TreeSHAP is exact and fast, which removes most of the usual cost argument against SHAP.
What does SHAP compute?
SHAP (SHapley Additive exPlanations) treats the features of one input as players in a game whose payout is the model’s prediction. A feature’s Shapley value is its average marginal contribution over every possible order in which features could join:
Here F is the set of all features, S is a subset that excludes feature i, and f_S(x) is the model’s expected output when only the features in S are known. The weight in front counts how many orderings place exactly the features of S before i. The result is the only attribution that satisfies efficiency, symmetry, dummy and additivity together, which is why SHAP values can be trusted to add up:
φ₀ is the average prediction over the background data. Every other φᵢ says how far feature i pushed this particular prediction away from that average, and in which direction.
TreeSHAP or KernelSHAP?
Computing the sum above directly needs 2^M model evaluations. KernelSHAP approximates it by sampling coalitions and fitting a weighted linear regression, which works for any model but is slow. TreeSHAP walks the paths of a tree ensemble and computes exact values in polynomial time. For decision trees, Random Forests and XGBoost, always use TreeSHAP.
What does LIME compute?
LIME (Local Interpretable Model-agnostic Explanations) perturbs the input, asks the black-box model to score the perturbed samples, and fits a simple interpretable model g (usually sparse linear) that imitates f near x:
L is the error between f and g on the samples, weighted by π_x, a proximity kernel that gives nearby samples more say. Ω(g) penalises complexity, for example by capping the number of features. The explanation is the weights of g. Two consequences follow: LIME only ever explains one neighbourhood, and the answer depends on how that neighbourhood is sampled and how wide the kernel is.
What does conventional feature importance measure?
For a decision tree, scikit-learn’s feature_importances_ sums the impurity reduction each feature achieves across all the splits that use it, weighted by the share of samples reaching each split:
p(t) is the fraction of samples reaching node t and Δi(t) is the drop in Gini impurity (or entropy) at that node. It is free to compute and describes the model as a whole. It has no sign, says nothing about an individual case, and is known to favour features with many possible split points. Permutation importance, which measures how much a metric drops when one feature is shuffled, is a sturdier global alternative.
Three explainers, one model: the code
The script below trains one decision tree and explains it three ways. It uses scikit-learn’s built-in breast-cancer dataset only so that it runs anywhere; it is not the data from the paper.
# pip install scikit-learn shap lime
import numpy as np
import shap
from lime.lime_tabular import LimeTabularExplainer
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.25, stratify=data.target, random_state=0)
model = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X_train, y_train)
names = data.feature_names
# 1. Conventional (impurity-based) feature importance: global, unsigned
global_rank = sorted(zip(model.feature_importances_, names), reverse=True)[:5]
# 2. SHAP: exact for trees, local and additive
explainer = shap.TreeExplainer(model)
sv = explainer(X_test) # shape: (samples, features, classes)
case = 0
local_shap = sorted(zip(sv.values[case, :, 1], names), key=lambda t: -abs(t[0]))[:5]
global_shap = np.abs(sv.values[:, :, 1]).mean(axis=0) # mean |SHAP| as a global view
# 3. LIME: local surrogate around the same case
lime = LimeTabularExplainer(X_train, feature_names=names,
class_names=data.target_names, mode="classification",
random_state=0)
local_lime = lime.explain_instance(X_test[case], model.predict_proba,
num_features=5).as_list()
print("Feature importance:", global_rank)
print("SHAP (this case): ", local_shap)
print("LIME (this case): ", local_lime)
Run it twice with a different random_state for LIME and you will see its weights move a little. Run it twice for SHAP and nothing changes: TreeSHAP is deterministic for a fitted tree.
Why do SHAP and LIME give different answers?
Disagreement is normal and usually informative. The common causes:
- Sampling noise. LIME’s explanation depends on random perturbations, so it varies between runs unless you fix the seed and draw many samples.
- Neighbourhood width. LIME’s kernel width decides how “local” the explanation is. A wide kernel drifts towards a global summary; a narrow one becomes noisy.
- Linear surrogate versus exact attribution. A tree’s decision surface is a staircase. A straight line fitted to a staircase can rank features differently from an exact decomposition of the same prediction.
- Correlated features. When two features carry the same information, both methods may split the credit between them in unstable ways. Published comparisons of SHAP and LIME report that both are sensitive to collinearity, so check correlations before reading the ranking.
- Different baselines. SHAP explains the gap from the average prediction over the background data; LIME explains the local slope. They are answering slightly different questions.
SHAP vs LIME vs feature importance at a glance
| SHAP | LIME | Feature importance | |
|---|---|---|---|
| Question it answers | How far did each feature move this prediction from the average? | Which features does a simple model use near this point? | Which features does the model rely on overall? |
| Scope | Local, and global by averaging | Local only | Global only |
| Theory | Shapley values (cooperative game theory) | Local surrogate model | Impurity decrease in the tree |
| Adds up to the prediction | Yes | No | Not applicable |
| Direction (sign) | Yes | Yes | No |
| Stability | Deterministic with TreeSHAP | Varies with sampling | Deterministic |
| Speed on tree models | Fast with TreeSHAP | Fast per case | Instant |
| Model-agnostic | KernelSHAP yes; TreeSHAP for trees | Yes | No (permutation importance is) |
How to choose
- Start with the question. If someone needs to know why this applicant, patient or day received this score, you need a local method: SHAP or LIME. If you are auditing the model, start global.
- Use TreeSHAP for any tree model. It is exact, fast and stable, and its global summary (mean |SHAP|) is more reliable than impurity importance.
- Use LIME when the model is a black box you cannot open, for example a model behind an API, and fix the seed, increase the number of samples and report the kernel width.
- Treat impurity importance as a sketch, not evidence. Confirm it with permutation importance on held-out data.
- Check feature correlations first. If features are strongly collinear, group them or explain at the group level.
- Explain for the reader. In health and public-policy settings, an explanation is only useful if the person acting on the prediction can read it, which is why we pair explainers with plain-language summaries in our digital-health work.
Frequently asked questions
Is SHAP better than LIME?
For tree models, usually yes: TreeSHAP is exact, deterministic and additive, while LIME approximates the model locally and varies with sampling. LIME remains useful for quick, model-agnostic explanations of a single case when the model cannot be opened.
Does feature importance show whether a feature increases or decreases the prediction?
No. Impurity-based importance is unsigned and global. It shows how much the model relies on a feature, not the direction of its effect for any case. SHAP and LIME both give a direction.
Can SHAP explain deep learning models?
Yes. DeepSHAP and GradientSHAP approximate Shapley values for neural networks, and KernelSHAP works for any model but is slower. For images and text, the choice of background data strongly affects the result.
Why do my SHAP and LIME rankings differ for the same prediction?
They answer different questions: SHAP decomposes the gap from the average prediction, LIME reads the slope of a local linear fit. Random sampling in LIME and correlated features make the gap larger.
The full comparison, with the selection criteria we proposed, is in the IJARCCE paper and the code repository. The project page has the background: Comparing interpretability techniques.
Related articles
Measuring vehicle speed from a roadside camera: from pixels to km/h
Detect, track, calibrate, measure: the full pipeline for estimating vehicle speed and spotting lane changes in traffic video, with the homography maths, OpenCV code and lessons for placing cameras on mixed-traffic roads.
Forecasting dengue from open weather data: lags, leakage and lead time
Weather shapes dengue with a delay of weeks, and that delay is what makes early warning possible. How to build lagged weather features, validate a forecaster in time order and judge it by lead time, with Malaysia as the example.
Why AQI models report R² = 0.99, and how to evaluate them honestly
Near-perfect scores in air-quality papers usually say more about the evaluation than the model. Target leakage, random splits and seasonal blind spots explained, with the seasonally stratified set-up from our Dhaka study.