Skip to main content

Explainable AI (XAI): SHAP and LIME on Real Data

Explainable AI (XAI) explained: SHAP and LIME worked through on real credit data, NIST principles, the limits for LLMs, and the law from the EU AI Act to GDPR.

FHFinn Hillebrandt
Last updated:
Technology
Explainable AI (XAI): SHAP and LIME on Real Data

Explainable AI (XAI) refers to methods that make it understandable to humans why an AI system reaches a particular result. They do not open the "black box" completely, but they give checkable hints about which inputs carried a decision.

Compare it with a doctor who does not just say "surgery needed" but points to the findings the judgment rests on. For a rejected loan this means, for example, that the long term and the high credit amount tipped the decision. The applicant can follow that, and the bank can check whether the model decided for good reasons.

Two terms often get mixed up. Interpretability usually means a model is understandable by itself, like a small decision tree. Explainability refers to techniques that describe an opaque model after the fact. The literature does not use the words consistently, so it pays to check what is meant in each case. The abbreviation can be confusing too. XAI with a capital X stands for explainable AI. xAI with a lowercase x was the original name of the AI company Elon Musk founded. It develops the Grok chatbot and now operates under a different name.

What we calculated ourselves: for a credit model on real data, the SHAP contributions add up exactly to the prediction, while LIME wobbles with a nonlinear model and a small sample (section 3). For language models, stated reasons are not an explanation (section 4), and the AI Act and GDPR apply, including CJEU rulings (section 5).

1. Why explainable AI is needed

When a model only delivers results, three questions stay open. Is the decision correct, does the model decide for the right reasons, and can an affected person challenge it? Three typical fields show this.

  • Credit: A model rejects. Without a reason, nobody can check whether an improper proxy for origin or gender played a part.
  • Medicine: An image model detects a tumor. Doctors must see whether it looks at the lesion or at a confounder such as a stamp in the image.
  • Recruiting: A model ranks applications. Without an explanation it stays unclear whether it scores résumés by fit or by patterns from old, biased data.

In "Stop explaining black box machine learning models for high stakes decisions", Cynthia Rudin argues that for consequential decisions you should use an interpretable model from the start instead of explaining an opaque one afterwards. That is a good counter-question for any project. Do you really need the complex model?

What makes a good explanation was put into four principles by the US agency NIST in 2021 (NIST IR 8312).

  • Explanation: The system delivers or contains evidence or reasons for its outputs or processes.
  • Meaningful: The explanation is understandable to the people it is meant for.
  • Explanation accuracy: The explanation correctly reflects the reason for the output or the system's actual process.
  • Knowledge limits: The system only operates under the conditions it was designed for and when it reaches sufficient confidence in its output.

The third principle matters most. NIST explicitly separates explanation accuracy from decision accuracy. A model can decide correctly and still give a wrong reason, and the other way around. According to NIST, reliable metrics for explanation accuracy were still being developed.

2. The methods ordered by axes

Methods can be placed on three axes. Intrinsic means the model is readable by design, post-hoc means the explanation comes afterwards. Local explains a single decision, global the overall behavior. Model-agnostic means the technique works with any model that is only queried as a black box.

Here is one example per axis. A decision tree is intrinsically readable. An explanation for this one rejected loan is local, while the average importance of the loan term across all applications is global. The table places the common techniques.

Decision tree, linear regression
Type
intrinsic
Scope
global and local
Model access
the model itself
Delivers
Rules or weights, directly readable
LIME
Type
post-hoc
Scope
local
Model access
model-agnostic
Delivers
A simple surrogate model around one case
SHAP
Type
post-hoc
Scope
local, aggregable to global
Model access
model-agnostic, TreeSHAP for tree models
Delivers
Each feature's contribution to the prediction
Counterfactual explanations
Type
post-hoc
Scope
local
Model access
model-agnostic
Delivers
The smallest change that flips the result
Permutation importance, partial dependence
Type
post-hoc
Scope
global
Model access
model-agnostic
Delivers
Average importance and effect of a feature
Integrated gradients, Grad-CAM
Type
post-hoc
Scope
local
Model access
needs gradients of the neural network
Delivers
Heatmap of which pixels or tokens count
Concept activation vectors (TCAV)
Type
post-hoc
Scope
global
Model access
needs internal activations
Delivers
Influence of human concepts such as "striped"

3. SHAP and LIME on a real credit model

SHAP is based on Shapley values from game theory. The idea is to measure a feature's contribution as its average added value over all orders in which you reveal the features to the model one by one. With 8 features there are 256 subsets of features, which can be computed exactly, without approximation. That is what we did.

3.1 The model and the application

This is gradually.ai's own calculation from 9 November 2026. It rests on the Statlog (German Credit Data) set with 1,000 credit applications from Germany, 30% of which defaulted. Hans Hofmann of the University of Hamburg compiled it in 1994, the UCI Machine Learning Repository provides it under CC BY 4.0, and the amounts are in Deutsche Mark. We trained a logistic regression on 8 features (700 cases) and tested it on 300 further cases. It is right in 76.7% of the test cases. Always answering “no default” gets 70%. The AUC is 0.80. This is a teaching model, not a scoring model.

The example application comes from the test cases. Its features: term 48 months, credit amount 9,960 DM, age 26 years, employed under 1 year, installment rate level 1 of 4, checking account in credit, savings below 100 DM. The model estimates a 65.0% default probability and rejects (threshold 50%). The loan did in fact default.

3.2 SHAP: the contribution of each feature

The base value is the average prediction over the training data, 30.0%. Each bar shows by how many percentage points a feature shifts this application's default probability relative to that average.

0%20%40%60%80%Base value (training data average)30Duration 48 months+17Credit amount 9,960 DM+9.9No checking account no, has an account+8.8Installment rate (share of income) level 1 of 4−8.1Employment duration under 1 year+4.3Checking account overdrawn no−3.6Age 26 years+3.4Savings below 100 DM yes+3.3Prediction for this application65%
raises the default probabilitylowers itValues in percentage points
SHAP waterfall: Base value (training data average) 30, Duration plus 17, Credit amount plus 9.9, No checking account plus 8.8, Installment rate (share of income) minus 8.1, Employment duration plus 4.3, Checking account overdrawn minus 3.6, Age plus 3.4, Savings below 100 DM plus 3.3, Prediction for this application 65
FeatureValue for the applicationSHAP contribution (percentage points)
Base value (training data average)30
Duration48 months+17
Credit amount9,960 DM+9.9
No checking accountno, has an account+8.8
Installment rate (share of income)level 1 of 4−8.1
Employment durationunder 1 year+4.3
Checking account overdrawnno−3.6
Age26 years+3.4
Savings below 100 DMyes+3.3
Prediction for this application65
Own calculation, German Credit data
gradually.ai

The base value plus all contributions gives 65.0%, exactly the model's prediction. The sum check holds with a deviation below 0.01 points. The biggest driver is duration with 17.0 points, followed by credit amount with 9.9. Installment rate (share of income) lowers the estimated risk by 8.1 points.

Read every contribution relative to the training data average. The feature “No checking account” is “no” for this applicant, so they have an account, and it still contributes 8.8 points. That does not mean an account raises the risk. In the training data many applicants have no checking account, and the model rates that group as less likely to default. Compared with that average, the applicant looks worse.

The caveat matters. SHAP describes what the model relies on, not what works causally in the world. A shorter term would not automatically lower this applicant's actual default risk by the term's contribution. But the bank can say which features led the model to reject.

3.3 LIME: the same question, a different route

LIME changes the input of a single applicant slightly many times, asks the model for its prediction each time, and fits a simple weighted substitute model to the results. That model's weights are the explanation for exactly this case. LIME only needs queries to the model. Because it perturbs at random, the weights can vary between two runs. We rebuilt LIME for the same application (we did not use the “lime” package) and ran ten seeds per setup.

For the linear model, LIME is stable. The contributions vary between runs by at most 0.15 percentage points, the ranking of the features is the same in all ten runs, and the values differ from the exact SHAP values by at most 1.1 points. LIME becomes unstable only with a nonlinear model and a small sample. We repeated the experiment with a gradient boosting model (accuracy 79.0%). With 5,000 samples the contributions vary by up to 0.60 points, with only 300 by up to 2.36 points.

Logistic regression, 5,000 samples
Largest spread (percentage points)
0.15
Most important feature across 10 runs
Duration 10
Features with rank changes
0 of 8
Sign changes
none
Gradient boosting, 5,000 samples
Largest spread (percentage points)
0.60
Most important feature across 10 runs
Duration 10
Features with rank changes
4 of 8
Sign changes
none
Gradient boosting, 300 samples
Largest spread (percentage points)
2.36
Most important feature across 10 runs
Duration 5, Credit amount 5
Features with rank changes
8 of 8
Sign changes
Installment rate (share of income)
Own calculation, German Credit data
gradually.ai

The limits of this calculation: one data set of 1,000 cases from the 1990s, one application, two models. The features are coarsely recoded, for example checking account and savings as yes-no features. SHAP treats the features as independent of each other (interventional variant), and our LIME is a rebuild in which kernel width and sampling can shift the weights. No general statement about the two methods follows from it.

4. Explainability for LLMs

The classic techniques are of limited use for large language models. There is no small table of features, only billions of weights and text as input. Three routes lead to answers, and each has hard limits.

4.1 A model's own justification is not an explanation

The obvious move is to ask the model for its reasoning, for example through chain-of-thought. But the reasoning is again generated text. Turpin et al. showed in 2023 that such rationales can omit factors that influenced the answer, and accuracy dropped by up to 36% in their tests with biasing hints. Anthropic found in 2025 that Claude 3.7 Sonnet mentioned a hint it used in its chain of thought 25% of the time on average, DeepSeek R1 39% of the time.

A visible chain of thought is therefore useful for reading and checking, but it is no proof of how the model actually arrived at the result.

4.2 Mechanistic interpretability

This research field tries to understand the model's inside directly. In 2024 Anthropic used dictionary learning to extract millions of interpretable features from Claude 3 Sonnet, including one for the Golden Gate Bridge. Intervening on such features measurably changes the model's behavior.

The authors name the limits themselves. The features are only a small share of the learned concepts, a full extraction would be too expensive with this method, and knowing a feature does not yet explain how the model uses it. The benefit for safety is also not yet shown. For everyday work in companies this is research today, not a tool.

4.3 Practical substitutes

  • Cite sources: With RAG you show which documents an answer comes from. That explains provenance, not the computation.
  • Test instead of interpret: Fixed test cases and spot checks show where the model is reliable and where it is not.
  • Separate the decision from the model: For consequential decisions an explainable model makes the decision and the LLM only words the text.

5. What the law requires

There is no general duty for "explainable AI". But there are rules that force explanations in practice. How the AI Act is built overall I explain in the article on the EU AI Act.

AI Act, Art. 13
What it requires
High-risk systems must be transparent enough for deployers to interpret the output and use it appropriately. That includes instructions for use with performance limits and aids for interpretation.
Affects
Providers of high-risk systems
AI Act, Art. 14
What it requires
Human oversight must be possible. The people overseeing should interpret outputs correctly, stay aware of over-reliance (automation bias), and be able to disregard outputs.
Affects
Providers, in use the deployers
AI Act, Art. 50
What it requires
Transparency toward people, such as the disclosure for chatbots and the labeling of AI-generated content and deepfakes. This is about disclosing that AI is involved, not about the computation.
Affects
Providers and deployers of certain systems
AI Act, Art. 86
What it requires
People affected by a decision based on an Annex III high-risk system with significant effects can ask the deployer for a clear explanation of the system's role and the main elements of the decision.
Affects
Deployers of high-risk systems
GDPR, Art. 22
What it requires
The right not to be subject to a solely automated decision with legal or similarly significant effects. Exceptions need safeguards such as human intervention and the ability to contest the decision.
Affects
Controllers that decide automatically
GDPR, Art. 15(1)(h)
What it requires
Information about the logic involved and the significance and consequences of an automated decision.
Affects
Controllers

The AI Act applies in stages. Article 50 has applied since August 2, 2026, with providers of generative systems already on the market having until December 2, 2026 for the technical marking. For Annex III high-risk systems, which include systems for credit scoring and for selecting applicants, the AI Omnibus moved the obligations to December 2, 2027, and for systems embedded in regulated products to August 2, 2028.

The GDPR already applies. In the SCHUFA ruling (December 2023) the CJEU held that a score on which a decision relies heavily can itself be an automated decision under Art. 22. In Dun & Bradstreet Austria (February 2025) it clarified that affected people can demand a comprehensible explanation of the procedure and principles applied. You do not have to disclose the algorithm itself, but a bare formula or a reference to trade secrets is not enough.

The law explains why you have to explain. The next section shows the tools for it.

6. XAI frameworks at a glance

The most important libraries are open source. The table shows which kinds of explanation, data types, and licenses they cover.

11 frameworks

LIME

Ribeiro, Singh & Guestrin

Model-Agnostic

LIME (Local Interpretable Model-agnostic Explanations) generates local explanations by approximating with interpretable surrogate models. Works with any model.

TabularTextImage
Local:Yes
Global:No
Year:2016
License:BSD-2-Clause
Best For: Fast local explanations for individual predictions without model assumptions

ELI5

TeamHG-Memex

Model-Specific

ELI5 (“Explain Like I'm 5”) provides simple explanations for Scikit-learn, XGBoost, LightGBM, and other ML libraries. Focus on understandability.

TabularText
Local:Yes
Global:No
Year:2016
License:MIT
Best For: Quick, simple explanations for classical ML models

SHAP

Lundberg & Lee / Microsoft

Model-Agnostic

SHAP (SHapley Additive exPlanations) uses Shapley values from game theory to quantify each feature's contribution to predictions. Provides both local and global explanations.

TabularTextImage
Local:Yes
Global:Yes
Year:2017
License:MIT
Best For: Theoretically grounded feature attribution for tabular data and tree models

What-If Tool

Google PAIR

Dashboard

The What-If Tool enables interactive exploration and analysis of ML models without coding. Integrated into TensorBoard and Jupyter Notebooks.

Tabular
Local:Yes
Global:Yes
Year:2018
License:Apache-2.0
Best For: Interactive fairness analysis and model comparisons without coding

DALEX

MI² DataLab

Model-Agnostic

DALEX (Descriptive mAchine Learning EXplanations) provides model-agnostic explanations focused on Partial Dependence Plots, Feature Importance, and Model Performance.

Tabular
Local:Yes
Global:Yes
Year:2018
License:GPL-3.0
Best For: Model comparisons and performance diagnostics with elegant visualizations

InterpretML

Microsoft Research

Hybrid

InterpretML is a unified toolkit for glass-box models (like EBM) and black-box explanations. Provides interactive visualizations and what-if analysis.

Tabular
Local:Yes
Global:Yes
Year:2019
License:MIT
Best For: Inherently interpretable models (EBM) with performance close to black-box models

Captum

Meta / PyTorch

Deep Learning

Captum is an interpretability library for PyTorch models. Offers various attribution methods like Integrated Gradients, DeepLIFT, and Layer-wise Relevance Propagation.

ImageTextTime Series
Local:Yes
Global:No
Year:2019
License:BSD-3-Clause
Best For: Deep learning models in PyTorch, especially for computer vision and NLP

AIX360

IBM Research

Comprehensive

AI Explainability 360 (AIX360) is a comprehensive open-source toolkit with diverse algorithms for various explanation requirements, including Contrastive Explanations.

TabularTextImage
Local:Yes
Global:Yes
Year:2019
License:Apache-2.0
Best For: Enterprise applications with fairness and compliance requirements

Alibi

Seldon

Comprehensive

Alibi is a comprehensive Python library for black-box explanations including Counterfactuals, Anchors, Contrastive Explanations, and Drift Detection.

TabularTextImage
Local:Yes
Global:Yes
Year:2019
License:Apache-2.0
Best For: Counterfactual explanations and Anchors for rule-based explanations

Shapash

MAIF

Dashboard

Shapash is a web dashboard for model interpretability combining SHAP and LIME in a user-friendly interface. Ideal for data scientists and business stakeholders.

Tabular
Local:Yes
Global:Yes
Year:2020
License:Apache-2.0
Best For: Interactive exploration and communicating model results to non-technical stakeholders

OmniXAI

Salesforce Research

Comprehensive

OmniXAI unifies all common XAI methods in one library and supports various data types (tabular, text, image, time series) as well as NLP-specific explanations.

TabularTextImageTime Series
Local:Yes
Global:Yes
Year:2021
License:BSD-3-Clause
Best For: Multi-data-type projects requiring a unified XAI solution
Source: framework project pages

7. The history of explainable AI

The timeline runs from early decision trees through the DARPA program and the first standard tools to the current debates around LLMs and the AI Act.

8 milestones

The tools produce explanations. Whether those explanations are any good is another question.

8. Pitfalls and misconceptions

Heatmaps
MythA heatmap shows what the model really attends to.
FactSome saliency methods barely depend on the model weights (Adebayo et al. 2018). Test every method with sanity checks.
Manipulation
MythLIME and SHAP cannot be manipulated.
FactSlack et al. showed in 2020 that both can be fooled so that a biased model looks harmless.
Causality
MythSHAP shows causes in the real world.
FactSHAP describes the model's dependence on features, not causal effects. Strongly correlated features share contributions.
Explanation quality
MythAn explanation is automatically a good explanation.
FactIt has to fit the audience. A data scientist needs something different from a customer.
LLM justification
MythIf the LLM justifies its answer, we know how it decided.
FactThe justification is generated text and can leave out influencing factors.

9. What this means for you

  1. Ask first whether a simple, interpretable model is enough. For credit, hiring, and medicine it is often the strongest solution.
  2. If you need a complex model, plan SHAP or a comparable method from the start and check the explanations with sanity tests.
  3. With LLMs, treat justifications as a reading aid. Rely on tests, source citations, and human review.
  4. Check whether your system falls under Art. 22 GDPR or the AI Act's high-risk rules, and document how affected people get an explanation. The larger frame is in AI governance.

Frequently Asked Questions

A credit model rejects an application and shows which features tipped the decision, such as the long term and the high credit amount. Methods like SHAP calculate these contributions for each individual decision. Another example is a heatmap that marks the areas of an X-ray a diagnosis rests on.

Yes, and because of the law, more than before. The EU AI Act requires transparency and human oversight for high-risk systems, and the GDPR gives affected people rights around automated decisions. For large language models, explainability remains an open research problem.

No, not in the XAI sense. ChatGPT can give a justification when asked, but that is generated text again and not a look at the actual computation. Studies show such justifications can leave out influencing factors. The weights themselves are not readable by humans.

SHAP distributes the prediction across the features using game theory, and the contributions add up exactly to the prediction. LIME fits a simple substitute model around a single case but because it samples at random, the weights are not identical on every run. For a linear model they barely move, for a nonlinear model with a small sample they move a lot (section 3). Both are model-agnostic, and both can be fooled.

Not as a method, but as an outcome. Providers of high-risk systems must build them transparently enough that deployers can interpret the output (Art. 13) and must enable human oversight (Art. 14). For certain decisions, affected people can request an explanation of the role the AI system played (Art. 86).

Not under that name. Article 22 protects against purely automated decisions with significant effects, and Article 15 gives access to the logic involved. The Court of Justice clarified in 2025 that affected people can demand a comprehensible explanation of the procedure. You do not have to disclose the algorithm itself.

It makes decisions checkable. Experts can spot errors and unfair patterns, affected people can question decisions, and companies meet legal requirements. This matters most for credit, medicine, and hiring.

Sources and References
FH

Finn Hillebrandt

AI Expert & Blogger

Finn Hillebrandt is the founder of Gradually AI, an SEO and AI expert. He helps online entrepreneurs simplify and automate their processes and marketing with AI. Finn shares his knowledge here on the blog in 50+ articles as well as through the AI Business Club.

Learn more about Finn and the team, follow Finn on LinkedIn, join his Facebook group for ChatGPT, OpenAI & AI Tools or do like 17,500+ others and subscribe to his AI Newsletter with tips, news and offers about AI tools and online business. Also visit his other blog, Blogmojo, which is about WordPress, blogging and SEO.