Explainable AI for Beginners: SHAP, LIME and Feature Importance in Machine Learning

A student builds a machine-learning model to estimate what a house sold for in a historical dataset. The computer announces a predicted price of $270,000. The student is pleased—but then asks a harder question: why did the model give that figure? Did living area matter? Was overall construction quality important? Would a different explanation method tell the same story? Could a convincing explanation still be misleading? The $270,000 example is fictional classroom arithmetic, not a prediction from an Ames property.

This is the central problem of Explainable AI (XAI). In this guide you will distinguish transparent and difficult-to-interpret models, investigate global and local behaviour, compute permutation feature importance, understand SHAP contributions and LIME surrogate explanations, and learn why no explanation automatically establishes correctness or causation. The complete Python experiment is designed around a six-feature Random Forest regressor for the historical Ames Housing dataset. It continues Topic 90: Feature Engineering, which taught how to design model inputs; this lesson teaches how to investigate the predictions that follow.

Reproducibility disclosure (25 November 2026): The actual OpenML Ames Housing dataset (ID 42165) could not be retrieved within this authoring environment, and the LIME package could not be installed because of network restrictions. Therefore no Ames predictions, real Ames permutation rankings, Ames SHAP plots or executed LIME outputs are claimed below. The SHAP method and numerical additivity were actually tested on 450 separately generated fictional housing-like records, using Scikit-learn 1.8.0 and SHAP 0.50.0; their sample graphics are clearly marked synthetic and are not Ames evidence. The full real-data script and notebook are provided to generate authentic results where OpenML and LIME are accessible.

What is Explainable AI?

Explainable AI refers to techniques and practices intended to make selected aspects of an AI system’s behaviour or output more understandable to humans. A model can produce a numerical prediction or class label without communicating the relationships that led to it. An explanation method supplies additional information: perhaps which inputs the fitted model uses, which inputs change one prediction relative to a reference, or how a simpler model approximates complex behaviour near one case.

The word “explain” has limits. An explanation is not a magic transcript of the model’s private intentions, and many models have no single short human-language reason for a prediction. The usefulness of an explanation depends on its audience, the question, the model, the data, and assumptions about how missing or altered features are represented. Good XAI is an investigation process, not a certificate of safety.

Why investigate machine-learning predictions?

People need explanations to detect errors, challenge unexpected results, communicate limitations, inspect unusual cases and decide what further evidence is required. If a historical house-price model is heavily influenced by an impossible building-age value, an explanation may point investigators toward a data-quality problem. If a student-score model appears to depend on an identifier or future exam result, examining feature effects can reveal potential leakage.

Understanding the model is particularly important when outputs could affect opportunities or resources. Yet an understandable explanation cannot compensate for inaccurate predictions, unrepresentative training records, unfair error patterns, insecure deployment or lack of oversight. Assess performance and data quality before interpreting attributions as useful insight.

Transparency, interpretability and explainability

Transparency can refer to whether system design, features, algorithms, code and operating rules are accessible to scrutiny. Interpretability is the extent to which a human can make sense of a model or relationship under an intended task. Explainability is the practice of generating and evaluating accounts of model outputs or behaviour. These terms overlap in the literature and are not universally defined by a single authority.

A small decision tree may be easy to inspect directly, while a forest containing hundreds of trees can be difficult to summarize, even if every line of code is available. Calling it a “black box” does not mean the code is necessarily secret; rather, its detailed mapping from input combinations to outputs is difficult to comprehend as a few ordinary rules.

Interpretable models and post-hoc methods

A modest linear regression has a learned coefficient for each numeric feature, although the interpretation of that coefficient depends on transformations, other variables and modelling assumptions. A short decision tree can show a sequence of split rules. A constrained additive model may also be intelligible in a carefully specified context. These are often called inherently interpretable model types.

SHAP, LIME and permutation importance generally investigate an already fitted model and are commonly called post-hoc approaches. A method that produces a readable chart does not necessarily produce a faithful summary of the model or any causal explanation of the world. Even a simple model can mislead if its inputs are poorly measured or its assumptions are wrong.

Local versus global explanations

A global explanation investigates model behaviour across many records or a selected population: which variables change predictions most on average, or which changes reduce evaluation performance when a feature is disrupted? A local explanation focuses on a particular observation: which features moved the model’s output up or down relative to a chosen baseline, or which simple rule approximates it near this house?

A variable might have high global importance yet contribute little to a particular case. Conversely, an unusual house characteristic could dominate the explanation for one prediction while scarcely mattering across the dataset. A report should identify whether its conclusions refer to one house, fifty explained cases, a test partition or a broader intended population.

QuestionGlobal explanationLocal explanation
ScopeMany evaluation observationsOne selected observation
ExampleAverage SHAP magnitudeOne SHAP waterfall
Other examplePermutation importanceLIME local surrogate
InterpretationPopulation-dependent model patternCase-dependent model account
Main cautionAggregate hides subgroupsOne case may not generalize

Three different meanings of feature importance

The term feature importance is not a single universal statistic. A Random Forest may report normalized impurity reduction accumulated during tree fitting. Permutation importance measures how a model’s evaluation score changes when one column is shuffled. Mean absolute SHAP summarizes the magnitude of model-output attribution across explained observations. Local LIME weights come from a nearby weighted surrogate approximation.

These numbers have different units and meanings. An impurity score may sum to one; a regression permutation score based on negative MAE is measured in price-error units; SHAP regression attributions are in model-output units; and LIME coefficients describe a particular local approximation. It is wrong to convert all four into seemingly comparable percentages and assert that one method has measured “true importance.”

Random Forest impurity-based importance

In Scikit-learn, a fitted RandomForestRegressor exposes feature_importances_, a normalized measure of accumulated decrease in the criterion used to choose splits. It is inexpensive to inspect and can help identify variables actively used by the trees. In a six-feature numerical model, it returns one value per feature in the fitted order.

But this is based on the tree structure trained on the development observations, not an independent test of predictive necessity. Certain feature characteristics can attract more splits, and correlated predictors can divide apparent credit in unstable ways. A feature with a large impurity importance is not proven to cause house prices to change; a low score does not always establish irrelevance.

Permutation importance: test the fitted model’s reliance

Permutation importance keeps the fitted model fixed, measures its score on a chosen evaluation dataset, randomly shuffles one input column, and measures the score again. Repeating the shuffle produces a distribution of score changes. If disrupting living area causes markedly worse predictions, the fitted model may depend heavily on information supplied by that column under the stated evaluation scheme.

With scoring='neg_mean_absolute_error', a larger score is better because it represents the negative of error. Scikit-learn computes baseline score minus the post-shuffle score. If ordinary MAE rises from a hypothetical $20,000 to $24,000, negative MAE falls from −20,000 to −24,000, and importance becomes (−20,000)−(−24,000)=+$4,000. This is verified classroom arithmetic, not the actual Ames model’s outcome.

Fictional exampleBefore shuffle MAEAfter shuffle MAEImportance
Living area$20,000$24,000+$4,000
Another feature$20,000$20,500+$500

Why permutation importance can mislead

Suppose above-ground living area and another engineered size measure contain similar information. Shuffling one may not greatly hurt the model, because the other retains related information. Conversely, shuffling a feature independently can create implausible combinations that were absent from the real population. A small result might reflect redundancy, evaluation noise, weak model performance or an unsuitable score rather than physical irrelevance.

Always name the metric and dataset, repeat shuffles with a fixed seed, and report variability instead of treating a single number as exact. Negative permutation importance can occur when shuffling accidentally improves the score; it should not be silently clipped to zero. If test observations are used for post-hoc inspection, do not then repeatedly redesign the model using those test findings and still call its test accuracy independently estimated.

What is SHAP?

SHAP stands for SHapley Additive exPlanations. It draws on the idea of Shapley values from cooperative game theory: when participants jointly produce a result, one can assign credit by considering marginal contributions across possible coalitions. For model explanations, the “players” are input features, and the allocated contributions depend on a mathematical setup for how feature information is included, excluded or replaced.

The classroom analogy is useful but imperfect. A house feature is not a student who independently chooses effort, and the “game” must define how unknown features are handled. Some SHAP algorithms exploit tree structures or approximations rather than enumerating all possible subsets directly. SHAP is a family of explanation approaches; its output should always be interpreted under the chosen method and reference assumptions.

SHAP baseline, output scale and additive values

For a suitable single-output regression explanation, the model prediction can be represented as f(x) = baseline + φ₁ + φ₂ + … + φₙ, where each φ is a feature attribution under the chosen explainer. For our Random Forest regression, values are on the predicted sale-price scale. A positive attribution moves the prediction above the chosen reference; a negative attribution moves it below. Neither sign tells us that the feature is socially desirable or undesirable.

The baseline is not the particular house’s actual price. It reflects a reference model output defined by the background data and explanation convention. A different background set can change the baseline and divide credit differently. In classification, the relevant output may instead be raw scores, probabilities or log-odds; do not automatically apply regression interpretations to multidimensional class probabilities.

A fully checked $270,000 SHAP arithmetic example

Imagine an explanation with a fictional baseline price of $200,000. Living area contributes +$40,000; overall quality contributes +$25,000; construction year contributes −$10,000; basement area contributes +$5,000; garage capacity contributes −$5,000; full bathrooms contribute +$15,000. The contributions sum to +$70,000, and the reconstructed model output equals $270,000.

This example demonstrates additivity in price units. None of those six values comes from Ames, a real trained model or an actual dwelling. Such fictional mathematics helps students understand a SHAP waterfall, but must remain explicitly separate from charts generated by computation.

Fictional explanation componentContribution
Reference / baseline$200,000
Living area+$40,000
Overall quality+$25,000
Construction year−$10,000
Basement area+$5,000
Garage capacity−$5,000
Full bathrooms+$15,000
Reconstructed prediction$270,000

What SHAP waterfall plots show

Actual computed SHAP waterfall for FICTIONAL synthetic housing-like records—not an Ames Housing result.
Actual computed SHAP waterfall for FICTIONAL synthetic housing-like records—not an Ames Housing result.

A waterfall plot starts from a reference prediction, displays each contribution for a chosen observation, and arrives at the fitted model’s output. Positive and negative horizontal movements show how the accounting adds up. Students should read the baseline, the displayed feature values, the sign and magnitude of each attribution, and the final model prediction. The plot explains the model’s output, not the actual physical forces that produced the house’s sale price.

A genuine waterfall plot should be generated from the fitted estimator and a corresponding explanation object, not manually assembled from arbitrary attractive numbers. Before publication, verify that baseline plus SHAP contributions reproduces the estimator’s output within documented numerical tolerance. Be wary of overlapping labels or wrong currency units.

What SHAP beeswarm plots show

Actual computed SHAP beeswarm for 20 FICTIONAL synthetic housing-like records—not an Ames Housing result.
Actual computed SHAP beeswarm for 20 FICTIONAL synthetic housing-like records—not an Ames Housing result.

A beeswarm summarizes many observations rather than only one. Each dot is an attribution for a particular feature and observation; its horizontal position describes the direction and magnitude of the feature’s model-output contribution. Colour can encode that feature’s original or transformed value, depending on the plotting setup. A wide distribution of dots suggests the attribution varies considerably among explained records.

Our intended project explains fifty held-out observations. That is a sample, not a census of all historical Ames houses or all contemporary homes. Features can interact, and correlated inputs can shift how responsibility is allocated. A visually convincing slope in a beeswarm is not proof that physically altering a property characteristic would have the predicted causal effect.

Calculate global SHAP importance carefully

A common global summary takes the arithmetic mean of each feature’s absolute attribution over a defined group of observations. For fictional values +10, −5, +15 and −10, the absolute values are 10, 5, 15 and 10, whose mean is (10+5+15+10)/4 = 10. Unlike an average signed value, this does not cancel positive and negative effects. In a regression model, the resulting magnitude uses model-output units.

The rank depends on which observations are included, the fitted model and the SHAP explanation convention. A high mean absolute attribution indicates a large typical allocation in that explanation setup; it is not the same as the change in MAE caused by permutation. Report the sample count and baseline assumptions whenever sharing the number.

Background data, correlation and SHAP assumptions

TreeExplainer can use a sample of training records as background data for interventional explanations. The background helps define a distribution of reference values when feature information is considered unavailable. In our reproducible script, a random-seed-91 sample of up to one hundred training rows is specified, and the forest’s raw regression output is explained. This setup avoids incorporating held-out test targets into the reference construction.

Changing reference data can alter the attribution baseline and feature values. Moreover, interventional feature-marginalization assumptions may generate combinations that are statistically uncommon or physically implausible, especially when feature measurements are strongly correlated. SHAP can be useful and mathematically consistent while still depending on contested assumptions about what counts as feature removal.

SHAP stability and explanation uncertainty

Feature attributions can change when a model is retrained, background composition changes, correlated features are added or numerical settings change. This does not imply SHAP is intrinsically random or worthless; rather, it means a particular explanation needs a documented context. Students can sample two different training-background subsets, explain the same test row, compare baselines and rankings, and discuss whether interpretations are stable enough for their intended communication.

If a single feature repeatedly dominates under reasonable reference choices, that can be an informative empirical observation. If rankings change materially, communicate the sensitivity instead of cherry-picking the most persuasive chart. Consistency with the model prediction is a necessary numerical check for additive attribution, but not a guarantee of causal correctness, fairness or future validity.

What is LIME?

LIME stands for Local Interpretable Model-agnostic Explanations. LIME explains a particular prediction by sampling perturbed input records around that observation, asking the original model for predictions, weighting the neighbours by proximity and fitting a simpler local surrogate model. The result is an approximate picture of how the complex model behaves near the chosen observation under that sampling scheme.

In the house-price example, the original Random Forest might contain many interacting tree splits. LIME may use a weighted linear surrogate in a transformed local neighbourhood. The surrogate is not another copy of the forest; its coefficients describe a nearby approximation. That approximate relationship should not be treated as a globally valid regression equation.

How LIME generates an explanation

First select a held-out house to explain and prepare its six numerical features with the already fitted training imputer. Second generate simulated neighbour records under the chosen perturbation strategy. Third obtain the forest’s price predictions for those neighbours. Fourth assign proximity weights and fit the surrogate. Finally inspect the features, directions and weights the surrogate returns, along with its local fit diagnostic.

For continuous features, the tabular implementation may discretize values into ranges; the generated explanation terms can therefore describe intervals rather than coefficients for an unbinned continuous measurement. Neighbouring records need not be physically realistic houses, and highly correlated variables create additional problems. Keep feature order consistent between the reference data, chosen record and prediction function.

LIME local fidelity and what its score means

The local surrogate’s score is a fit diagnostic for how closely the simpler model approximates the black-box model over the generated, weighted neighbourhood. It is not the Random Forest’s final test R², its market-price accuracy or a proof that the explanation reveals real causes. A low fit suggests that this local linear summary may poorly approximate the forest in the sampled region.

Fidelity depends on neighbourhood generation, kernel width, chosen features, discretization and number of perturbations. Students should inspect those choices rather than treating a polished six-bar plot as automatically reliable. When LIME and SHAP disagree, consider their different mathematical objectives before declaring either one incorrect.

Test LIME stability with repeated sampling

Because LIME uses generated perturbations, repeated runs may produce somewhat different weights or selected terms. To assess this empirically, hold the fitted model and house observation fixed while repeating the explanation with seeds 91, 92 and 93. Record the top features, weight signs, surrogate fit scores and any substantial ranking changes. A single repeatable result under one fixed seed is not evidence of universal stability.

Our downloadable script includes this repeated-seed procedure, but LIME was not installed in this environment and no results from those runs are claimed. The activity must be executed on a computer with an available LIME installation and real or clearly marked synthetic data.

CriterionSHAPLIME
Central approachShapley-based attribution under chosen setupLocally weighted surrogate approximation
Local explanationYesYes
Global summaryCan aggregate many local attributionsRequires aggregation of local accounts
Model supportModel-specific and model-agnostic variantsDesigned as model-agnostic
Reference dependenceBackground distribution and feature assumptionsPerturbation distribution and locality weights
Numerical outputAdditive contributions on defined model scaleApproximate surrogate weights
Main cautionDependence/correlation and causal misreadingFidelity and stability of surrogate

SHAP versus LIME: how to compare responsibly

A strong classroom comparison uses the same model and same house for both tools. Record the actual target price, model prediction, absolute error, SHAP baseline, the highest-magnitude SHAP contributions, LIME features and weight signs, and LIME’s local fidelity. Discuss any agreement or disagreement without forcing the ranks to match. Both methods may respond to a large living area, for example, while allocating relative weight differently.

Do not compare a local LIME coefficient directly with a SHAP attribution as though their numerical units and semantics were interchangeable. LIME describes a surrogate under its sampling design; SHAP allocates model-output differences under an attribution convention. An explainability report should identify what each method measures and should not claim that one is always better in every context.

Compare impurity, permutation and SHAP summaries

Tree impurity importance is inexpensive and reflects splitting structure. Permutation importance measures the performance effect of disrupting a column on a chosen evaluation set. Mean absolute SHAP magnitude measures typical attributed model-output differences on explained observations. Each can be valuable if its definition matches the question, but raw values should not be directly compared as a shared percentage of true causation.

Correlated inputs particularly complicate comparisons. A feature may be repeatedly used in tree splits, yet shuffling it may have a small effect because another predictor retains similar information. SHAP may distribute attribution based on the reference assumptions and chosen grouping. Describe the discrepancy and inspect the dataset rather than forcing one ranking to be the definitive ground truth.

Complete model project: historical Ames Housing

The intended real-data benchmark is OpenML house_prices, ID 42165, comprising 1,460 historical Ames, Iowa sales and 79 explanatory variables in the commonly used version. We intentionally select six documented numerical inputs: GrLivArea, OverallQual, YearBuilt, TotalBsmtSF, GarageCars and FullBath. Their meanings are above-ground living area, quality rating, construction year, basement area, garage-car capacity and full bathrooms.

Our question is retrospective: how does the fitted forest predict historical sale prices, and how do different post-hoc tools describe its behaviour? The six-variable restriction makes charts readable and computation manageable but leaves out many determinants of actual transaction prices. The experiment must not be advertised as a present-day valuation product or generalized to housing markets worldwide.

Protect training, validation and final test partitions

The reproducible script calls fetch_openml(data_id=42165, as_frame=True), verifies required columns, converts the six inputs to numerical types and ensures sale prices are valid. It then reserves an 80/20 random train/test split using seed 91. With the expected complete dataset, this means 1,168 development and 292 final test observations. Within development, a shuffled five-fold KFold measures training-only cross-validation MAE.

The regression Pipeline contains SimpleImputer(strategy='median') and RandomForestRegressor(n_estimators=120, min_samples_leaf=2, random_state=91, n_jobs=-1). Median imputation is learned only from the relevant fitting observations. The baseline uses a DummyRegressor(strategy='median') fitted on development targets. Test labels are used only for independent evaluation and, if disclosed, subsequent fixed-model diagnostics—not to keep choosing new model settings.

What genuine model evaluation must report

After fitting the pre-specified model to all development data, predict the untouched test records and calculate positive Mean Absolute Error (MAE) plus R². MAE reports the average absolute currency error; R² assesses reduction in squared error relative to a constant mean reference on the evaluated set. Compare the forest with the training-median baseline and provide the five individual cross-validation MAE values.

The Ames download did not run here, so the article does not contain a fabricated test MAE, R², feature ranking or model prediction. The source files generate those results in JSON and CSV after successful execution. The manuscript explicitly reserves the right to find that the forest performs poorly; explanations do not rescue invalid or unhelpful predictions.

from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.impute import SimpleImputer
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline

features = ["GrLivArea","OverallQual","YearBuilt",
            "TotalBsmtSF","GarageCars","FullBath"]
ames = fetch_openml(data_id=42165, as_frame=True)
X = ames.frame[features].apply(pd.to_numeric, errors="coerce")
y = pd.to_numeric(ames.frame["SalePrice"], errors="raise")
X_train,X_test,y_train,y_test = train_test_split(
    X,y,test_size=0.2,random_state=91
)
pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("model", RandomForestRegressor(
        n_estimators=120,min_samples_leaf=2,
        random_state=91,n_jobs=-1
    ))
])
cv = KFold(n_splits=5,shuffle=True,random_state=91)
fold_mae = -cross_val_score(
    pipeline,X_train,y_train,cv=cv,
    scoring="neg_mean_absolute_error"
)
pipeline.fit(X_train,y_train)
# Run the companion source file for verification and XAI plots.

Generate actual permutation importance in Python

After final evaluation, use sklearn.inspection.permutation_importance on a documented evaluation dataset with scoring='neg_mean_absolute_error', n_repeats=10 and random_state=91. Create a Pandas table containing feature names, mean changes and standard deviations across shuffles. Keep the input order consistent with the model Pipeline. Inspect features that become less or more harmful when shuffled.

The fixed trained model should not be refitted after seeing test-set permutations if you intend the same test numbers to remain an untouched evaluation. For iterative feature redesign, compute importance on validation data and reserve a further independent final assessment.

Prepare the exact representation used by SHAP and LIME

The fitted Pipeline includes an imputer. Extract that already trained imputer and transform both training and test input frames without refitting it. Construct new DataFrames preserving feature names, row indices and the same column order. Then pass the fitted forest and this prepared numeric representation to SHAP and LIME. Explaining a differently scaled or imputed matrix from the one used for prediction can produce nonsensical interpretations.

For example, train_ready = pd.DataFrame(imputer.transform(X_train), columns=features). The value of this step is consistency, not convenience alone. Check resulting shapes and missing values before explaining; an apparent explanation for the wrong feature order is a dangerous silent error.

Generate SHAP TreeExplainer values and verify additivity

The full script creates a random sample of up to one hundred training rows as background, explains fifty test examples using shap.TreeExplainer(forest, data=background, feature_perturbation='interventional', model_output='raw'), and checks the shape of the resulting single-output regression attributions. It reconstructs each forest prediction as the reference value plus the sum of six attributions, comparing the result with forest.predict using numerical tolerance.

A locally executed, clearly marked synthetic experiment used Scikit-learn 1.8.0 and SHAP 0.50.0, with maximum absolute reconstruction difference about 0.00233 on synthetic prediction magnitudes. That is genuine execution evidence for the method on fictional generated data, not an Ames result. The same consistency check is built into the real-data script and must be repeated after real model fitting.

import shap
imputer = pipeline.named_steps["imputer"]
forest = pipeline.named_steps["model"]
train_ready = pd.DataFrame(imputer.transform(X_train),columns=features)
test_ready = pd.DataFrame(imputer.transform(X_test),columns=features)
background = train_ready.sample(n=min(100,len(train_ready)),random_state=91)
explained = test_ready.iloc[:50].copy()
explainer = shap.TreeExplainer(
    forest,data=background,
    feature_perturbation="interventional",model_output="raw"
)
values = explainer(explained)
reconstructed = np.asarray(values.base_values)+values.values.sum(axis=1)
assert np.allclose(reconstructed,forest.predict(explained),rtol=1e-4,atol=1.0)
shap.plots.waterfall(values[0],show=False)
plt.savefig("ames-shap-waterfall.png",dpi=200,bbox_inches="tight")

Create genuine visual explanations, not decorative scores

A SHAP waterfall explains the first selected house, while a SHAP beeswarm summarizes the fifty explained test observations. The report should annotate the data source, feature list, model, background sample, explanation sample size and output units. A table of np.abs(values.values).mean(axis=0) gives global mean absolute SHAP importance for those explained records. Create all plots from actual explanation objects, not hand-painted bars.

This article intentionally does not insert the local synthetic SHAP charts as if they belong to Ames. The ZIP includes those files with filenames beginning synthetic- for method-verification and visual study. When the real experiment runs, its graphics should replace any placeholder visual and be described as results for the documented test examples.

Generate the same observation’s LIME explanation

The complete script sets up LimeTabularExplainer(training_data=train_ready.to_numpy(), feature_names=features, mode='regression', discretize_continuous=True, random_state=91). The first explained test record is passed to explain_instance with predict_fn=forest.predict, six displayed features and 3,000 generated samples. It prints the feature-weight explanation, local surrogate fit and saves the associated figure.

The built-in LIME-generated neighbourhood is a simplification of the six-dimensional housing space; it can contain uncommon combinations. Consequently, its fitted local surrogate is an approximation of the forest, not a direct price equation and not a causal calculation. The routine is supplied for real execution once lime can be installed; no invented local weights or fidelity values are included.

from lime.lime_tabular import LimeTabularExplainer
lime_explainer = LimeTabularExplainer(
    training_data=train_ready.to_numpy(),
    feature_names=features, mode="regression",
    discretize_continuous=True, random_state=91
)
explanation = lime_explainer.explain_instance(
    data_row=test_ready.iloc[0].to_numpy(),
    predict_fn=forest.predict,num_features=6,num_samples=3000
)
print(explanation.as_list())
print("Local surrogate fit:", explanation.score)
fig = explanation.as_pyplot_figure()
fig.savefig("ames-lime-explanation.png",dpi=200,bbox_inches="tight")

A three-part explanation-stability experiment

Experiment A—LIME: repeat the same record’s explanation with seeds 91, 92 and 93, keeping the forest fixed. Compare weight signs, feature ranking and local R². Experiment B—SHAP: change the training-background sample with a documented procedure, and compare the baseline and attributions for the same record. Experiment C—Permutation: repeat evaluation shuffles and examine the distribution of score changes.

These investigations address different kinds of sensitivity. A method that produces identical results in one deterministic setup may still vary under sensible changes to input representation, background or model fitting. Report both stability and uncertainty rather than exaggerating a single demonstration.

Why accuracy and explainability are different requirements

A model may predict very accurately but be difficult for a human to summarize. Another may produce simple charts yet make large errors. A post-hoc tool may faithfully describe an unfair model; an unfair model does not become fair because the explanation looks professional. Reliable use requires predictive evaluation, source quality checks, privacy controls, fairness analysis, security, shift monitoring and domain competence beyond XAI plots.

For this educational exercise, a median-only baseline and a separately evaluated Random Forest establish whether modelling the numerical features is worthwhile. Explanation quality then becomes an additional question. The final report should place validation results and explanation findings in distinct sections so that readers do not confuse an attractive waterfall with evidence of accurate prices.

Attribution is not causation

Predictive attribution describes how a fitted model output is allocated to input features under a stated explanation method. Causal effect concerns what would happen under an intervention, requiring appropriate assumptions and evidence about real-world mechanisms. A positive quality-rating SHAP value does not prove that increasing a home’s rating by one point will raise its actual transaction price by that number of dollars.

Observational housing records contain correlated features, different buyer preferences, historical market conditions and omitted variables. Some imaginable interventions are not even physically coherent: changing a home’s recorded construction year without changing its materials does not cause the past to change. Avoid calling feature attributions causal estimates, even when their direction seems intuitive.

Correlated features and unrealistic perturbations

Living area, basement area, garage capacity, bathrooms and overall quality can be associated with shared aspects of a property. Independent shuffling or reference substitution may combine a very large house with an improbable set of other attributes. Such synthetic combinations can be useful for algorithmic diagnostics, but they may not represent attainable real houses. This is an interpretability limitation, not evidence that the method is fraudulent.

Correlations can also split or hide apparent importance: one of two related predictors may substitute for the other when shuffled; an attribution method can allocate shared information differently depending on conventions. A careful investigator checks feature distributions and relationships before treating a rank order as a stable universal conclusion.

Explainability, fairness and historical bias

House-price records can reflect historical inequalities in neighbourhood development, financing and other social circumstances. A high importance for a location-like input could reflect proxy relationships rather than inherent qualities of residents or communities. Our six-feature introductory dataset intentionally avoids many of the wider dataset’s categorical fields, but that does not automatically prove the model unbiased.

Model explanations can flag features or patterns to investigate. Fairness assessment still needs appropriate objectives, legally and ethically permitted subgroup analysis, error-rate comparisons and broader social context. Explanations are not a substitute for a justified decision policy, appeal mechanism or human oversight.

Privacy and the risks of explanation disclosure

An explanation may reveal input values, model behaviour, or combinations of attributes that are sensitive in context. Do not publish identifiable students’ education or health records, private addresses or individual financial decisions in a public tutorial. Even a small set of attributes can sometimes identify a person when combined with external information. Use licensed datasets and data-minimization practices appropriate to the task.

The Ames project is historical and educational; the output should avoid unnecessary identifying details and should respect dataset licence and attribution requirements. A model or explanation trained on nonpublic data should not be uploaded or shared without authorization.

Classification explanation: an optional extension

For Iris classification in Topic 87, a Random Forest predicts one of three species and may also output class probabilities. Explainability tools must specify the output class and whether attributions are on raw scores, probabilities or another scale. Multiclass SHAP objects may include an extra dimension for classes, so the regression formula code cannot simply be reused unchanged.

For LIME’s classification mode, the prediction function should supply appropriate class probabilities, not a single regression scalar. Classification examples should be validated with accuracy, macro F1, calibration or other suitable criteria. A convincing local explanation for a wrong class prediction is still a wrong prediction.

Why student performance explanations need special caution

Predictive explanations about students risk encouraging labels such as “weak”, “intelligent” or “destined to fail”, especially when input records contain historical bias, unequal resources or misleading proxies. A model could associate attendance or access to technology with grades without capturing the full learning environment. Its feature attribution cannot justify stigmatizing an identifiable learner or withholding support.

Use education-related models only for authorized, validated, supportive learning research, with privacy protections and meaningful human review. This tutorial does not create a public tool that ranks individual students’ ability. Similar caution applies to medical, employment, lending and public-service systems, where explanations alone do not establish safety or regulatory compliance.

Explainability has a computational budget

Impurity-based tree importance is usually inexpensive to retrieve after fitting. Permutation importance performs repeated scoring and therefore takes additional prediction time. SHAP cost depends heavily on model type, explainer and background sample size. LIME must generate and evaluate perturbed observations, and its cost depends on neighbourhood size and the complexity of the prediction function.

The beginner project limits itself to six numeric features, a moderate 120-tree ensemble, up to 100 background records, fifty explained test observations, and 3,000 LIME perturbations. Do not treat these settings as universally optimal. Actual runtimes depend on the computing environment and were not measured for the unavailable real Ames/LIME run.

Forty common explainability mistakes and their corrections

Foundations (1–10): (1) confusing interpretation with accuracy—evaluate predictions separately; (2) treating black-box as secret software—distinguish accessibility from comprehensibility; (3) calling attributions causal—state assumptions; (4) assuming one true importance measure—name the definition; (5) mixing local and global conclusions—declare scope; (6) including the target as an input—exclude it; (7) explaining leaked models—repair splitting first; (8) overlooking poor baseline performance—report it; (9) treating impurity scores as unbiased—compare independent diagnostics; (10) ignoring correlated inputs—inspect feature relationships.

Permutation and SHAP (11–20): (11) calling permutations causal interventions—describe them as perturbations; (12) shuffling time-dependent records carelessly—respect structure; (13) forgetting the scoring sign—verify negative-MAE conventions; (14) setting negative permutation scores to zero—report them; (15) inventing rankings—execute code; (16) confusing baseline with actual sale price—label reference output; (17) calling positive SHAP good and negative bad—explain direction only; (18) comparing different importance units directly—use method-specific interpretation; (19) using the wrong output scale—state model output; (20) omitting SHAP background—document reference data.

Implementation and LIME (21–30): (21) reusing regression array shapes for multiclass explanations—check dimensions; (22) assuming background changes cannot matter—test sensitivity; (23) reading waterfall bars as market causes—avoid causal claims; (24) attributing every feature effect independently of others—consider dependence; (25) trusting LIME without local fit—inspect surrogate R²; (26) forgetting perturbation assumptions—describe the generated neighbourhood; (27) changing seeds without reporting them—document randomness; (28) interpreting LIME coefficients as SHAP values—keep their meanings separate; (29) explaining differently preprocessed data—use the fitted transformation; (30) publishing outputs from broken imports—test execution.

Research practice (31–40): (31) repeating test-driven redesign—use validation; (32) ignoring small evaluation sample sizes—report n; (33) omitting confidence or instability discussion—evaluate repeatability; (34) ignoring fairness—perform separate assessment; (35) exposing private records—minimize disclosure; (36) claiming historical Ames prices generalize globally—state scope; (37) ignoring source licence—verify permissions; (38) claiming a SHAP consistency check proves accuracy—interpret it narrowly; (39) reporting fabricated LIME fidelity—run or leave pending; (40) publishing simulated diagrams as genuine Ames outputs—label synthetic material explicitly.

Ten-task capstone: investigate a historical housing model

Task 1: obtain the documented Ames Housing dataset and verify row count, source and selected features. Task 2: separate target from inputs and reserve test observations with seed 91. Task 3: implement median imputation and the specified Random Forest inside a Pipeline. Task 4: evaluate a median baseline and five-fold development MAE. Task 5: fit the forest on development data and report independent test MAE and R².

Task 6: calculate impurity-based and ten-repeat permutation importance with units. Task 7: create a documented training-reference SHAP explainer and verify additivity. Task 8: save a real waterfall and beeswarm and compute mean absolute SHAP values. Task 9: use LIME on the same house, inspect local fidelity and compare three random seeds. Task 10: write a transparent report including method definitions, data provenance, model results, explanation disagreements, sensitivity, privacy, fairness, licence and causal limitations.

Successful work must report measured numbers rather than copying the fictional $270,000 example. Include the actual and predicted price for the chosen test record, explain any unexpectedly large error, and make it clear that post-hoc interpretation did not drive further optimization of the final test set.

Thirty original practice questions with worked solutions

Question 1: What is Explainable AI?

Worked solution: Methods and practices for making aspects of AI behaviour or output understandable to people.

Question 2: Why might a Random Forest be called a black box?

Worked solution: Its many interacting trees can be difficult to summarize as a few human-readable rules, even when code is available.

Question 3: What is a global explanation?

Worked solution: An investigation of model behaviour over many observations.

Question 4: What is a local explanation?

Worked solution: An account focused on one selected model prediction.

Question 5: Name an inherently interpretable model.

Worked solution: A suitably small decision tree or simple linear model, with appropriate assumptions.

Question 6: What is post-hoc explainability?

Worked solution: Explaining a model after it is fitted rather than relying solely on inherently interpretable structure.

Question 7: What does feature_importances_ measure in a forest?

Worked solution: Normalized reductions in the splitting impurity criterion under the trained trees.

Question 8: What does permutation importance assess?

Worked solution: Change in model evaluation score when one feature is disrupted.

Question 9: What does SHAP stand for?

Worked solution: SHapley Additive exPlanations.

Question 10: What does LIME stand for?

Worked solution: Local Interpretable Model-agnostic Explanations.

Question 11: Find importance when MAE rises $20,000 to $24,000 after permutation.

Worked solution: Importance under negative-MAE scoring is +$4,000.

Question 12: Find importance when MAE rises $20,000 to $20,500.

Worked solution: Importance is +$500.

Question 13: Calculate the sum of fictional SHAP contributions +40k,+25k,−10k,+5k,−5k,+15k.

Worked solution: $70,000.

Question 14: Reconstruct the fictional prediction from a $200,000 baseline and +$70,000 sum.

Worked solution: $270,000.

Question 15: Find mean absolute attribution of +10,−5,+15,−10.

Worked solution: (10+5+15+10)/4=10.

Question 16: Do positive SHAP attributions mean a feature is morally good?

Worked solution: No. They shift the model output above a reference, not moral status.

Question 17: Can permutation importance be negative?

Worked solution: Yes. Shuffling can randomly improve an evaluated score.

Question 18: Does SHAP additivity prove a model is accurate?

Worked solution: No. It checks consistency of attribution with the model output, not correctness against targets.

Question 19: What does a LIME local fit score measure?

Worked solution: How well its weighted local surrogate approximates original model predictions in the sampled neighbourhood.

Question 20: Why compare LIME outputs from seeds 91,92 and 93?

Worked solution: To assess sensitivity to perturbation sampling and randomness.

Question 21: What issue arises with correlated living area and basement area?

Worked solution: The feature attributions or shuffling effects can depend on redundancy and explanation assumptions.

Question 22: What does the SHAP baseline depend on?

Worked solution: The chosen background/reference distribution and explanation configuration.

Question 23: Why must the fitted imputer be reused for explanation?

Worked solution: The explained features must match the numerical representation actually used by the forest.

Question 24: Why should test-set-driven feature redesign be avoided?

Worked solution: It contaminates independent evaluation and may produce optimistic performance estimates.

Question 25: Does a high local surrogate R² prove a causal effect?

Worked solution: No. It indicates approximation quality over the local synthetic neighbourhood.

Question 26: What is the difference between permutation and mean absolute SHAP importance?

Worked solution: Permutation measures metric change on disruption; SHAP measures average magnitude of model-output attribution.

Question 27: How many real observations are intended in the Ames source?

Worked solution: 1,460 in the specified OpenML house_prices version; verify after download.

Question 28: How many historical input features are used in the beginner model?

Worked solution: Six numerical features, chosen for an interpretable comparison.

Question 29: How can an explanation reveal privacy-sensitive information?

Worked solution: It may disclose individual input values or distinctive feature combinations.

Question 30: Outline a defensible SHAP/LIME study.

Worked solution: Verify data; establish split and baseline; evaluate forest; use training-only preprocessing; explain same held-out record; check additivity and LIME fidelity; report sensitivity and limits.

Eight interactive decisions: which explanation would you trust?

Scenario 1: A waterfall looks clear, but test predictions have huge errors.

Reasoning: Explainability is not performance; assess the model first and state error limitations.

Scenario 2: Two size features are highly correlated and permutation rankings are low.

Reasoning: Investigate redundancy and correlated-feature dependence before declaring either irrelevant.

Scenario 3: A LIME chart has low local surrogate R².

Reasoning: Describe low local fidelity; do not treat the displayed weights as a faithful local summary.

Scenario 4: A SHAP value changes when training-background sample changes.

Reasoning: Report the reference dependence and conduct a documented sensitivity comparison.

Scenario 5: A researcher uses SHAP dollars to claim renovation causes identical price gains.

Reasoning: Reject the causal claim: model attribution and intervention effects are different.

Scenario 6: An explanation reveals a student’s private grades and identifier.

Reasoning: Do not publish identifiable education records without authorization; minimize disclosure.

Scenario 7: A coder changes the model after inspecting held-out test importance.

Reasoning: Use a separate validation workflow and new independent assessment; the old test is no longer untouched.

Scenario 8: A plot claims to be Ames evidence but uses randomly generated houses.

Reasoning: Correct the caption and provenance; synthetic diagnostic data are not real source observations.

Four-week practical learning plan

Week 1—Foundations: revise prediction, regression, model accuracy and local/global interpretation; calculate permutation arithmetic and fictional additive attributions by hand. Week 2—Model audit: run the actual Ames dataset when available, verify the six numerical inputs, compare baseline and forest performance, and inspect impurity and permutation importance.

Week 3—Attributions: compute background-dependent SHAP values, check additive reconstruction, save waterfall and beeswarm figures, and explain how mean absolute SHAP importance differs from shuffling. Week 4—Critical explanations: install and run LIME, repeat local explanations, compare features, document fidelity, test background sensitivity and write the ten-task capstone research report.

Frequently asked questions

What is Explainable AI for beginners?

A collection of methods for investigating parts of how models behave and why they output particular values under specific explanation rules.

Is SHAP better than LIME?

Neither is universally better; their objectives, assumptions, output meanings and computational costs differ.

What does a positive SHAP value mean?

It moves the chosen model output above the reference baseline under the applicable attribution setup.

What does a negative SHAP value mean?

It moves the chosen model output below the reference baseline, not that a feature is bad.

Does SHAP prove causation?

No. Feature contributions are not automatically real-world intervention effects.

Why can LIME change between runs?

Perturbation sampling, proximity weighting, discretization and other modelling choices can influence the local surrogate.

How do I know if LIME is reliable locally?

Check surrogate fidelity, repeat sampling and assess whether generated neighbours are meaningful.

Can permutation importance be used for any model?

Many fitted predictors can be assessed with it if an appropriate scoring function and evaluation dataset are available.

Why can correlated features give confusing rankings?

They share predictive information and may be disrupted or allocated differently by different methods.

What is a SHAP waterfall plot?

A visualization accounting for a single model output as a reference plus feature attributions.

What is a SHAP beeswarm plot?

A summary of attribution values over a documented set of explained observations.

Can I reuse regression explanation code for multiclass classification?

Not without checking output dimensions, classes and model-output scales.

Are the Ames model’s SHAP figures verified in this article?

No. OpenML retrieval was blocked. The companion code generates real figures when executed with the correct data and dependencies.

Were the SHAP smoke-test charts actually computed?

Yes, using 450 explicitly fictional housing-like records and a fitted Random Forest; they are not Ames results.

Were LIME weights generated in the authoring environment?

No. The dependency could not be installed, and no LIME outputs are claimed.

Can an explanation certify that a model is fair?

No. Fairness requires additional evidence, contextual evaluation and governance.

Research sources and related Notes for SHS lessons

For implementation details consult the SHAP TreeExplainer documentation, SHAP waterfall documentation, SHAP beeswarm documentation, LIME tabular documentation, and Scikit-learn permutation importance. Primary research: Lundberg and Lee (2017), A Unified Approach to Interpreting Model Predictions, and Ribeiro, Singh and Guestrin (2016), “Why Should I Trust You?”

The educational series builds on Topic 90: Feature Engineering, Topic 89: Hyperparameter Tuning, Topic 62: AI Bias and Topic 61: Decision Trees. These links are contextual rather than a duplicate generic related-post block.

Conclusion: useful explanations require evidence and humility

Feature importance, SHAP and LIME open different windows onto a fitted model. Tree impurity importance summarizes training splits; permutation importance tests dependence of a score on disrupted inputs; SHAP allocates output differences under a reference convention; and LIME approximates complex behaviour near one observation. Learning their distinctions is more important than memorizing a chart colour or declaring one method universally superior.

A trustworthy XAI report establishes predictive performance, protects test data, uses exactly the features the fitted model saw, verifies any numerical decomposition, measures local fidelity, tests stability and names the limits of its background and perturbation assumptions. It also avoids causal exaggeration, respects privacy and asks whether the model is appropriate for its context. The real Ames investigation remains executable through the accompanying source code, while all numbers in this article are clearly identified as classroom arithmetic or synthetic method checks unless an authentic dataset run is specifically documented.

Companion download: The Topic 91 ZIP package contains a complete OpenML Ames Housing script, a Jupyter notebook, SHAP/LIME implementation notes, verified synthetic SHAP waterfall and beeswarm plots, the synthetic verification JSON and a concise formula sheet. The synthetic figures are not Ames data. No real Ames prediction results or executed LIME figures were available when this article was prepared.