Explainable AI (XAI): SHAP, LIME & Feature Importance
Machine learning models can make highly accurate predictions, but understanding why a model makes a particular prediction is often just as important as the prediction itself.
Imagine a bank uses a machine learning model to predict whether a customer should receive a loan. The model rejects an application, but the customer asks:
- Why was my loan rejected?
- Which factors influenced the decision?
- Would a higher income or lower debt improve my chances?
A prediction alone cannot answer these questions. We need techniques that help explain how the model arrived at its output.
This is where Explainable AI (XAI) becomes important.
In this article, we will explore:
- What Explainable AI is and why it matters.
- Global vs. local model explanations.
- Feature importance and its limitations.
- LIME: Local Interpretable Model-Agnostic Explanations.
- SHAP: SHapley Additive exPlanations.
- Python implementations using Scikit-learn, LIME, and SHAP.
- How to choose the right explanation technique.
1. What Is Explainable AI (XAI)?
Explainable AI refers to techniques and approaches that help people understand how an AI or machine learning system produces its predictions.
The objective is to make model behavior easier to interpret, analyze, and communicate.
XAI is particularly useful when machine learning decisions affect people, businesses, or critical systems.
Why Is Explainability Important?
Consider two models predicting customer loan defaults.
| Model | Accuracy | Explainability |
|---|---|---|
| Model A | 96% | Difficult to interpret |
| Model B | 94% | Easier to interpret |
Model A achieves higher accuracy, but Model B may be easier to audit and communicate.
Depending on the application, a small difference in accuracy may be less important than the ability to understand model behavior.
Explainability can help with:
- Trust: Users can better understand model predictions.
- Debugging: Developers can identify unexpected model behavior.
- Fairness analysis: Teams can investigate whether predictions depend on problematic features.
- Compliance: Organizations can provide more meaningful explanations where required.
- Model improvement: Feature explanations can reveal data quality issues or unexpected relationships.
However, explainability does not automatically make a model fair, correct, or trustworthy. Explanations must be interpreted carefully.
2. Black-Box vs. Interpretable Models
Some machine learning models are easier to understand directly than others.
Interpretable Models
Examples include:
- Linear Regression.
- Logistic Regression.
- Small Decision Trees.
- Rule-based models.
For example, a linear regression model predicts:
\[ \hat{y} = w_1x_1+w_2x_2+\cdots+w_nx_n+b \]
Each coefficient \(w_i\) indicates how the prediction changes with a feature, assuming other features remain fixed.
Black-Box Models
Examples include:
- Random Forests with many trees.
- Gradient Boosting models.
- XGBoost.
- Deep Neural Networks.
- Large Language Models.
These models may learn complex relationships that are difficult to understand by inspecting their internal parameters directly.
XAI techniques help explain these models by analyzing their behavior.
Important distinction: A model can be highly predictive without being inherently interpretable. Post-hoc explainability methods attempt to explain a model after it has been trained.
3. Global vs. Local Explainability
Explainability techniques generally answer two different types of questions.
Global Explainability
Global explanations describe the overall behavior of a model.
They answer questions such as:
- Which features are most important across the dataset?
- What patterns does the model generally learn?
- How does the model behave across different ranges of a feature?
For example, a loan prediction model might rely heavily on:
- Credit history.
- Debt-to-income ratio.
- Annual income.
- Loan amount.
A global explanation helps understand the model as a whole.
Local Explainability
Local explanations focus on a single prediction.
They answer questions such as:
- Why was this particular loan application rejected?
- Why did this customer receive a high-risk score?
- Why did the model classify this image as a cat?
For example:
| Feature | Contribution to This Prediction |
|---|---|
| High debt-to-income ratio | Increased risk |
| Low credit score | Increased risk |
| Stable employment | Reduced risk |
| High income | Reduced risk |
Local explanations help communicate the factors that influenced an individual prediction.
Global vs. Local Explanation
| Feature | Global Explanation | Local Explanation |
|---|---|---|
| Scope | Entire model or dataset | One prediction |
| Main purpose | Understand general behavior | Understand a specific result |
| Example | Overall feature importance | SHAP explanation for one customer |
| Common techniques | Permutation importance, aggregated SHAP | LIME, individual SHAP values |
Some methods, including SHAP, can provide both global and local explanations.
4. Feature Importance: Understanding Important Features
Feature importance is one of the simplest ways to understand which input variables influence a machine learning model.
For example, a model predicting house prices might use:
- House size.
- Number of bedrooms.
- Location.
- Property age.
- Distance from the city center.
Feature importance helps determine which variables are most influential.
However, different feature importance techniques measure importance differently.
4.1 Built-In Feature Importance
Many tree-based models provide a built-in feature importance attribute.
For example, Scikit-learn's Random Forest classifier provides:
model.feature_importances_
For many tree-based estimators, this measures the total reduction in impurity attributed to each feature, normalized across the model.
This is often called Mean Decrease in Impurity (MDI).
Python Example: Random Forest Feature Importance
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load dataset
data = load_breast_cancer()
X = pd.DataFrame(
data.data,
columns=data.feature_names
)
y = data.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
# Train Random Forest
model = RandomForestClassifier(
n_estimators=100,
random_state=42
)
model.fit(X_train, y_train)
# Extract feature importance
importance = pd.Series(
model.feature_importances_,
index=X.columns
)
# Sort importance
importance = importance.sort_values(
ascending=False
)
print(importance.head(10))
What Does the Output Mean?
The output might look like:
mean concave points 0.14
worst perimeter 0.12
worst concave points 0.11
worst radius 0.10
mean perimeter 0.08
These values represent the model's relative impurity-based importance scores.
They do not mean that a feature causes the prediction or that its importance is the same across all individual predictions.
Limitations of Built-In Feature Importance
Impurity-based feature importance has several limitations:
- It can favor features with many possible split points.
- Correlated features can divide importance between themselves.
- It does not directly explain the direction of a feature's influence.
- It does not explain a particular prediction.
- It may not reflect how much predictive performance would decline if a feature were unavailable.
For these reasons, other techniques are often useful.
5. Permutation Feature Importance
Permutation Feature Importance measures how much a model's performance changes when the values of one feature are randomly shuffled.
The basic idea is:
If a feature is important, disrupting its relationship with the target should reduce model performance.
How Does Permutation Importance Work?
Suppose a model predicts customer churn using:
- Age.
- Monthly charges.
- Contract type.
- Customer tenure.
The original model achieves an accuracy of 92%.
Now shuffle the values of Contract type while keeping all other features unchanged.
The model's accuracy decreases to 80%.
The resulting performance reduction suggests that contract type is useful to the model.
A common formulation is:
\[ I_j = S_{\text{original}} - S_{\text{permuted},j} \]
Where:
- \(I_j\) = Permutation importance of feature \(j\).
- \(S_{\text{original}}\) = Original model score.
- \(S_{\text{permuted},j}\) = Score after shuffling feature \(j\).
Python Implementation
import pandas as pd
from sklearn.inspection import permutation_importance
from sklearn.metrics import accuracy_score
# Predict on test data
y_pred = model.predict(X_test)
print(
"Test Accuracy:",
accuracy_score(y_test, y_pred)
)
# Calculate permutation importance
result = permutation_importance(
model,
X_test,
y_test,
scoring="accuracy",
n_repeats=10,
random_state=42,
n_jobs=-1
)
# Display results
importance = pd.Series(
result.importances_mean,
index=X_test.columns
).sort_values(ascending=False)
print(importance.head(10))
Advantages of Permutation Importance
- Works with many model types.
- Can be calculated using a validation or test dataset.
- Measures the effect of a feature on model performance.
- Does not require access to the model's internal structure.
Limitations
- Can be computationally expensive.
- Correlated features can make individual importance scores misleading.
- Results depend on the evaluation metric.
- Shuffling can create unrealistic combinations of feature values.
Best Practice: Use permutation importance on data that was not used to train the model, and interpret correlated features carefully.
6. LIME: Local Interpretable Model-Agnostic Explanations
LIME is an explainability technique that explains an individual prediction by approximating the model's behavior near that prediction.
LIME stands for:
Local Interpretable Model-Agnostic Explanations
It works with many types of models because it does not require access to their internal architecture.
The Main Idea Behind LIME
Imagine a complex machine learning model that predicts whether a customer will default on a loan.
The model is difficult to interpret directly.
LIME focuses on one customer and asks:
"What simple model can approximate the original model's behavior around this particular customer?"
It creates perturbed versions of the customer's input, obtains predictions from the original model, and fits a simple interpretable model to those nearby examples.
LIME Workflow
Original Input
|
v
Get Original Model Prediction
|
v
Generate Nearby Perturbed Samples
|
v
Obtain Predictions from Original Model
|
v
Weight Samples by Proximity
|
v
Fit Simple Interpretable Model
|
v
Explain Important Local Features
How Does LIME Work?
LIME generally follows these steps:
- Select the instance to explain.
- Generate perturbed samples around the instance.
- Obtain predictions from the original model for those samples.
- Assign higher weights to samples closer to the original instance.
- Fit a simple interpretable model, such as a sparse linear model.
- Use the local model's coefficients to explain the prediction.
A simplified LIME objective can be written as:
\[ \xi(x)=\arg\min_{g\in G} \left[ L(f,g,\pi_x)+\Omega(g) \right] \]
Where:
- \(f\) = Original complex model.
- \(g\) = Interpretable local model.
- \(L\) = Local approximation loss.
- \(\pi_x\) = Proximity weighting around instance \(x\).
- \(\Omega(g)\) = Complexity penalty for the explanation.
The objective balances local accuracy and explanation simplicity.
Python Implementation: LIME
Install the package:
pip install lime scikit-learn
Example:
import numpy as np
from lime.lime_tabular import LimeTabularExplainer
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load dataset
data = load_breast_cancer()
X = data.data
y = data.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
# Train model
model = RandomForestClassifier(
n_estimators=100,
random_state=42
)
model.fit(X_train, y_train)
# Create LIME explainer
explainer = LimeTabularExplainer(
training_data=X_train,
feature_names=data.feature_names,
class_names=data.target_names,
mode="classification",
random_state=42
)
# Select one instance
instance = X_test[0]
# Explain prediction
explanation = explainer.explain_instance(
data_row=instance,
predict_fn=model.predict_proba,
num_features=10
)
# Display explanation
print(explanation.as_list())
# Visualize explanation
explanation.show_in_notebook()
Understanding the Output
A LIME explanation might look like:
worst radius > 16.5 +0.24
worst perimeter > 110.0 +0.18
mean concave points > 0.05 +0.12
mean texture <= 20.0 -0.08
The values indicate the direction and relative contribution within the fitted local explanation.
Positive and negative signs depend on the class being explained and the local model's output convention.
These are not necessarily causal effects.
Advantages of LIME
- Model-agnostic.
- Useful for explaining individual predictions.
- Produces relatively simple explanations.
- Supports tabular, text, and image data through suitable explainers.
Limitations of LIME
- Explanations can change with random sampling.
- Results depend on the perturbation strategy.
- The local approximation may be inaccurate.
- Correlated features can make interpretation difficult.
- Different configurations may produce different explanations.
Best Use Case: LIME is useful when you need a relatively simple local explanation for a specific prediction from a model that is otherwise difficult to interpret.
7. SHAP: SHapley Additive exPlanations
SHAP is one of the most widely used approaches for explaining machine learning predictions.
SHAP is based on Shapley values from cooperative game theory.
In game theory, Shapley values estimate how much each participant contributes to the outcome of a group.
In machine learning, features are treated as contributors to a prediction.
SHAP estimates how much each feature contributes to moving a model's prediction away from a baseline.
The Main Idea Behind SHAP
Imagine a model predicting whether a customer will default on a loan.
The model produces a risk score of 0.80.
SHAP explains how the individual features contribute to this prediction.
For example:
| Feature | SHAP Contribution |
|---|---|
| High debt-to-income ratio | +0.20 |
| Low credit score | +0.15 |
| Stable employment | -0.10 |
| High income | -0.05 |
The SHAP contributions are relative to the chosen baseline and model output scale.
Positive contributions push the explained output higher, while negative contributions push it lower.
SHAP Additive Explanation
SHAP represents a prediction as:
\[ f(x)=\phi_0+\sum_{i=1}^{M}\phi_i \]
Where:
- \(f(x)\) = Model output being explained.
- \(\phi_0\) = Baseline output.
- \(\phi_i\) = SHAP value for feature \(i\).
- \(M\) = Number of features.
For example:
\[ 0.50+0.20+0.15-0.10-0.05=0.70 \]
The explained model output is 0.70.
This is an illustrative additive example. In real applications, the output scale may be probability, log-odds, or another model output.
How Are SHAP Values Calculated?
Shapley values consider how a feature contributes across different possible subsets of features.
A simplified Shapley value formula is:
\[ \phi_i = \sum_{S\subseteq F\setminus\{i\}} \frac{|S|!(M-|S|-1)!}{M!} \left[ v(S\cup\{i\})-v(S) \right] \]
Where:
- \(F\) = Set of all features.
- \(S\) = A subset of features excluding feature \(i\).
- \(v(S)\) = Value associated with the subset.
- \(M\) = Total number of features.
The formula averages a feature's marginal contribution over different feature subsets.
Exact computation can become expensive as the number of features increases, so practical SHAP explainers use specialized algorithms and approximations.
Python Implementation: SHAP
Install SHAP:
pip install shap scikit-learn
Example:
import shap
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load dataset
data = load_breast_cancer()
X = data.data
y = data.target
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42,
stratify=y
)
# Train model
model = RandomForestClassifier(
n_estimators=100,
random_state=42
)
model.fit(X_train, y_train)
# Create SHAP explainer
explainer = shap.TreeExplainer(model)
# Calculate SHAP values
shap_values = explainer(X_test)
# Display global feature importance
shap.plots.bar(shap_values)
# Explain one prediction
shap.plots.waterfall(shap_values[0, :, 1])
The exact shape and class indexing of SHAP values can vary by SHAP version and model type. For binary classification, the selected output should correspond to the class you intend to explain. Confirm the returned dimensions before selecting a class-specific explanation.
Understanding SHAP Visualizations
SHAP provides several useful visualizations.
1. SHAP Bar Plot
A SHAP bar plot summarizes global feature importance.
For many tabular classification problems, it uses the mean absolute SHAP value:
\[ I_i = \frac{1}{N}\sum_{j=1}^{N}|\phi_{ij}| \]
Where:
- \(N\) = Number of explained observations.
- \(\phi_{ij}\) = SHAP value for feature \(i\) and observation \(j\).
A larger mean absolute SHAP value indicates a larger average contribution magnitude on the explained output scale.
2. SHAP Beeswarm Plot
A beeswarm plot shows the distribution of SHAP values for each feature across many observations.
It can help answer:
- Which features have large effects?
- Do high feature values tend to push predictions upward or downward?
- Is a feature's influence different across observations?
shap.plots.beeswarm(shap_values)
For multi-output models, select the appropriate output before plotting if needed.
3. SHAP Waterfall Plot
A waterfall plot explains one prediction.
It begins with a baseline and shows how individual feature contributions move the output toward the final prediction.
shap.plots.waterfall(shap_values[0, :, 1])
This is particularly useful for understanding individual predictions.
Advantages of SHAP
- Provides local and global explanations.
- Has a strong theoretical foundation.
- Supports many model types.
- Offers useful visualization tools.
- Can provide consistent additive feature attributions under its defined assumptions.
Limitations of SHAP
- Exact calculations can be computationally expensive.
- Results depend on the background data and feature dependence assumptions.
- Correlated features can make attribution difficult.
- A feature's SHAP value does not establish causation.
- Different explainers may use different approximation methods.
Best Use Case: SHAP is useful when you need detailed explanations of individual predictions and an aggregated view of feature influence across a dataset.
8. Feature Importance vs. LIME vs. SHAP
These techniques provide different types of information.
| Feature | Feature Importance | LIME | SHAP |
|---|---|---|---|
| Main purpose | Rank influential features | Explain one prediction | Explain feature contributions |
| Global explanation | Yes, with aggregation | Not directly | Yes, through aggregation |
| Local explanation | Usually no | Yes | Yes |
| Model-agnostic | Depends on method | Yes | Some explainers are model-agnostic |
| Explanation style | Importance scores | Local surrogate model | Additive feature attributions |
| Computational cost | Often low | Moderate | Depends on explainer |
| Common limitation | May not show direction | Local approximation instability | Attribution depends on assumptions |
Which Technique Should You Use?
| Requirement | Recommended Technique |
|---|---|
| Quick model-level feature ranking | Built-in feature importance |
| Measure performance impact of a feature | Permutation importance |
| Explain one prediction with a simple local model | LIME |
| Explain individual feature contributions | SHAP |
| Analyze global feature impact and local predictions | SHAP |
| Understand a simple linear model | Inspect coefficients directly |
No explanation method is universally best. The appropriate choice depends on the model, dataset, computational budget, and explanation objective.
9. Common XAI Mistakes to Avoid
1. Treating Feature Importance as Causation
A feature being important to a model does not mean it causes the outcome.
For example, a model may find a strong relationship between location and loan default risk. This does not establish that location causes a person to default.
2. Ignoring Correlated Features
If two features contain similar information, importance may be distributed between them.
A model may rely on either feature, or both, depending on its training process.
3. Explaining the Wrong Model Output
For classification, explanations may refer to:
- Predicted class.
- Probability of a class.
- Log-odds.
- Another model-specific output.
Always identify which output is being explained.
4. Assuming Explanations Are Always Stable
LIME explanations can vary because of random perturbations.
SHAP explanations can also change when the background dataset or assumptions change.
5. Using Explanations Without Evaluating Model Quality
An explanation does not make a poor model reliable.
Before interpreting a model, evaluate its predictive performance using an appropriate validation strategy.
6. Ignoring Data Leakage
If the model was trained using leaked information, its explanations may describe the leakage rather than meaningful relationships.
Use appropriate cross-validation and preprocessing pipelines before performing XAI analysis.
10. Practical XAI Workflow
A practical explainability workflow can be organized as follows:
Collect and Prepare Data
|
v
Train Machine Learning Model
|
v
Evaluate Model Performance
|
v
Choose Explanation Objective
|
v
+-------------------------------+
| Global Explanation |
| |
| Feature Importance / SHAP |
+-------------------------------+
|
v
+-------------------------------+
| Local Explanation |
| |
| LIME / SHAP |
+-------------------------------+
|
v
Analyze Explanation Stability
|
v
Communicate Results Carefully
For production systems, explanations should also be monitored over time because changes in the input data or model can change the explanations.
11. Real-World Applications of Explainable AI
| Industry | Application | Useful XAI Technique |
|---|---|---|
| Banking | Loan approval explanations | SHAP, LIME |
| Healthcare | Medical risk prediction | SHAP, permutation importance |
| Insurance | Claim risk analysis | SHAP, feature importance |
| E-commerce | Product recommendation analysis | SHAP |
| Manufacturing | Predictive maintenance | Permutation importance, SHAP |
| Cybersecurity | Fraud and anomaly detection | SHAP, LIME |
| Human Resources | Auditing hiring prediction systems | SHAP, careful fairness analysis |
In high-impact applications, explanations should be combined with fairness analysis, data quality checks, domain expertise, and appropriate human oversight.
12. Frequently Asked Questions (FAQs)
Q1. What is Explainable AI?
Explainable AI is a set of techniques that helps people understand how machine learning models produce predictions and which factors influence their outputs.
Q2. What is the difference between interpretable AI and explainable AI?
Interpretable models are designed to be understood directly, such as small decision trees or linear models. Explainable AI also includes post-hoc techniques that explain complex models after training.
Q3. What is SHAP in machine learning?
SHAP is an explainability framework based on Shapley values. It estimates how individual features contribute to a model output relative to a baseline.
Q4. What is LIME?
LIME explains an individual prediction by generating nearby samples and fitting a simple interpretable model to approximate the original model locally.
Q5. Is SHAP better than LIME?
Not always. SHAP has a strong additive attribution framework and supports global and local explanations. LIME can provide simple local explanations with relatively flexible model support. Their suitability depends on the problem.
Q6. What is feature importance?
Feature importance measures how influential a feature is according to a particular definition, such as impurity reduction, permutation-based performance changes, or aggregated SHAP values.
Q7. Can SHAP explain any machine learning model?
SHAP has explainers for many model families, including tree-based models, linear models, and general model-agnostic settings. The computational cost and explanation assumptions vary by explainer.
Q8. Does SHAP prove that a feature causes a prediction?
No. SHAP explains model attribution under a chosen setup. It does not establish causal relationships.
Q9. What is the difference between global and local explainability?
Global explainability describes general model behavior across a dataset. Local explainability describes factors influencing an individual prediction.
Q10. Why is XAI important in production machine learning?
XAI can support debugging, model monitoring, communication, auditing, and investigation of unexpected predictions. It should be used alongside predictive evaluation and other responsible AI practices.
Conclusion
Explainable AI helps make machine learning models easier to understand and analyze.
Feature importance provides a useful overview of influential variables. Permutation importance measures how model performance changes when a feature is disrupted. LIME explains individual predictions through local approximations, while SHAP estimates feature contributions using a game-theoretic framework.
The right technique depends on the question you want to answer.
- Use feature importance to identify influential variables.
- Use permutation importance to measure performance dependence on features.
- Use LIME for simple local explanations.
- Use SHAP for detailed local attributions and aggregated global analysis.
However, explanations should not be mistaken for causal evidence or proof of fairness.
A reliable machine learning system combines strong predictive performance, appropriate validation, careful interpretation, and responsible deployment.
Remember: A model's prediction tells you what it decided. Explainable AI helps you investigate why it made that decision.
Author: Kulbhushan Pukale
Category: AI & Machine Learning