Lecture 13 · AI4ST

eXplainable AI

Not just what a model predicts, but why: interpretable models, model-agnostic methods (LIME, counterfactuals), neural-network interpretation (GradCAM), self-explaining prototype networks, how to evaluate explanations, and XAI for sensor time series in Ambient Intelligence.

⏱ ~60 min 📚 6 sections ✅ 15 MCQ + 2 open-ended ⭐ Includes sim Q3 · Q21 — GradCAM & counterfactual
1

Intro to eXplainable AI

ML models drive crucial decisions in AmI (healthcare diagnosis, smart-city management, energy choices, helping data scientists improve a model). In some domains it is not only important to know what is predicted, but also why.

  • Knowing the "why" helps in learning more about the problem, the data, and the reason a model might fail.
  • XAI techniques unveil the reasoning behind the predictions and decisions of ML models — big in Computer Vision and NLP, but also crucial for time-series sensor data in AmI.

A typical explanation framework

An XAI system takes the current task and makes a recommendation, decision or action; an explanation interface provides an explanation that justifies it; the user then makes a decision based on the explanation. The shift "today → tomorrow": from "Why did you do that? When do you fail? Can I trust you?" to "I understand why; I know when you'll fail; I know when to trust you."

XAI emphasis — it's not only ML
XAI is not only about ML models: Human-Computer Interaction plays a major role (explanations must be effectively delivered to target users), and there is a strong "psychological" component when designing how to deliver explanations.

The target of explanations

Sibling set — who reads the explanation
Based on the target, explanations may differ a lot.
TargetSlide definition
Non-expert end-usersTake advantage of AI models in daily life without knowledge about ML (e.g., smart-city operators, clinicians, monitored subjects)
TechniciansData scientists / ML experts: monitor the model to understand if the sensing setup needs refinement, if more labeled data are needed, if the model must be improved
2

Global vs Local · Accuracy vs Interpretability

Global vs Local explanations

Global explainability

  • How does the trained model make predictions? Which features are important in general and how do they interact?
  • Usually prohibitive to understand the whole model, but sometimes a portion can be explained (e.g., specific weights)

Local explainability

  • Why did the model make a certain prediction for an instance? Locally, the prediction might depend only on some features
  • Most widely adopted since it is more accurate than making global explanations

Accuracy vs Interpretability

There is a well-known trade-off: the most accurate models tend to be the least interpretable. From low to high interpretability (and high to low accuracy): Deep Learning → Ensembles (RF, BRT) → SVM → k-NN → Decision/Regression Trees → Lasso/Ridge → Linear Regression.

The three categories of XAI approaches

🔍

Interpretable Models

Classic ML algorithms that are inherently explainable (§3).

📦

Model Agnostic

Decouple the explanation from the model, treating it as a black box (§4).

🧠

Deep Explanation

Neural networks designed with interpretability in mind (§5).

3

Interpretable Models

Some classic ML algorithms are inherently explainable: once trained, their parameters can deliver explanations (global or local, depending on the model). Pro: very simple approach. Con: for certain tasks classic ML models are too simple compared to deep learning ones.

Linear Regression

  • Prediction = a weighted sum of the feature inputs (y = β₀ + β₁x₁ + … + βₚxₚ + ε).
  • The weights β₁…βₚ indicate feature importance → used as a global explanation (high weight = most important feature).
  • Pros: simple weight estimation, easy to interpret. Cons: linearity can't capture feature interactions; low predictive performance.

Decision Trees

  • Capture complex relationships among features; give both global and local explanations:
  • Global: feature importance, by measuring at each node how much it reduced the variance compared to the parent node.
  • Local: tracking the path of the data point from root to leaf — the combination of traversed conditions is the local explanation.

Rules Induction

  • Learning IF-THEN rules from data; each rule covers a portion of the dataset.
  • The set of rules used for a prediction is the local explanation; all the rules together are the global explanation.
  • Approaches: Sequential Covering, Bayesian Rules Lists (also iterative approaches, pattern mining).
4

Model-Agnostic Approaches

Interpretable models are sometimes too simple for complex domains (CV, NLP, time series). Model-agnostic XAI decouples the explanation from the ML model, so it can be applied to any model treated as a black box.

  • Model flexibility: the interpretation method works with any model (random forests, deep nets).
  • Explanation flexibility: you can choose the best interpretation model based on the goal.

LIME — Local Interpretable Model-agnostic Explanations

LIME analyzes how the model's output changes by varying the input (goal: which parts of the input are important for classification). Given a sample to explain:

Generate perturbed versions + black-box predictions Train an interpretable model (e.g., linear regression) Weight each perturbed sample by similarity to the original

The resulting explanation should accurately approximate the local prediction (local fidelity).

Counterfactual Explanations

Definition — sim Q21 lives here
Describing a causal situation: "If X had not occurred, Y would not have occurred" (X = cause, Y = event) — imagining a hypothetical reality that contradicts the observed facts (e.g., "If I hadn't taken a sip of this hot coffee, I wouldn't have burned my tongue").
  • Idea: change feature values (realistically), analyze how the prediction changes, observe when it changes relevantly (e.g., the predicted class flips).
  • The counterfactual explanation is the feature vector with the smallest change that modifies the prediction (e.g., loan: "if he had been 2.5 years older and requested $210 less for two months shorter, he would have been eligible").
  • Pros: clear, easy to implement. Cons: for each instance there may be multiple, possibly contradictory counterfactuals — choosing the best is challenging.
Problems of model-agnostic approaches
Explanations do not always mimic the actual calculations made by the original model — the explanation may include different features than the ones really used by the black box. This motivates methods that explain complex (deep) models directly.
5

Neural Network Interpretation & Deep Explanation

Interpreting Neural Networks

Methods to visualize features/concepts learned by a network, to explain individual predictions (local). A single deep prediction can involve millions of operations — impossible for humans to follow the exact mapping. Idea: networks learn features in their hidden layers, and the gradient can implement interpretation methods — more computationally efficient than model-agnostic methods looking at the model "from the outside".

GradCAM — Gradient-weighted Class Activation Map

Where sim Q3 lives
A method for CNNs (born in Computer Vision, adaptable to time series). Goal: understand which parts of an input a convolutional layer "looks" at. Idea: consider the gradients (backprop) on the LAST convolutional layer (the one before the dense layers), analyze which regions are activated in the feature maps, and generate a heatmap of the most relevant input parts.
  • Algorithm: forward-propagate the input; get the raw score for the class of interest (last neuron before softmax); set other class activations to zero; back-propagate the gradient to the last conv layer; weight each feature-map "pixel" by the gradient for the class.
  • Heatmap: ReLU(Σₖ αₖᶜ Aᵏ) where the weights αₖᶜ are a global average pooling of the gradients δyᶜ/δAᵏ; ReLU keeps only positive values.

Deep Explanation: prototype-based networks

Posthoc methods (chosen architecture first, then interpret it) have problems: explanations change a lot based on the model used to generate them and may not make sense to humans. Deep explanation instead designs networks interpretable by design.

  • Prototype-based = case-based reasoning: explain predictions by similarity to prototypical cases. A prototype is a data point close/identical to a training observation; a limited set should represent the whole dataset.
  • A self-explaining model that learns prototypes has three components: an autoencoder (latent space), a prototype layer (learns m prototypes), and fully-connected + softmax layers for classification. It learns in parallel the latent space, the classification task, and the prototypes.
  • Distance to each prototype = squared L² distance in latent space; explanation = the k closest prototypes. Two regularization terms: each prototype close to ≥1 training example, and every training example close to ≥1 prototype. To visualize latent prototypes, use the Decoder to reconstruct them.
6

Evaluating Explanations & XAI for Time Series

How to evaluate explanations

It's tempting to think convincing explanations are also effective — but convincing explanations may be associated with model mistakes. A key challenge is over-reliance: the user trusts the system too much just because it provides explanations.

Sibling set — measures of explanation effectiveness
Four measures the exam can turn into a list MCQ.
MeasureWhat it assesses
User SatisfactionClarity / utility of the explanation — usually via questionnaires
Mental ModelHow well a user understands the underlying model — by asking users to describe the explanation process
Trust AssessmentTrust is the cognitive factor influencing perception (can be positive or negative) — questionnaires before/after using the model
CorrectabilityWhether XAI can identify errors (leading to correction and continuous training) — usually assessed with automatic methods

XAI for time series

Explanation typeHow it explains
Time-points basedAssign a relevance score to every time point (how much each sample contributes). Attribution methods (external, e.g., LIME, GradCAM) vs Attention methods (internal focus of the network)
Subsequence basedIdentify sub-parts of the series responsible for the outcome — by extracting motifs (repeating patterns) and training interpretable models on them
Instance basedUse the whole temporal window: feature-based, prototype-based, or counterfactual-based (minimal change flipping the outcome; minimality uses a distance between time series)

AmI use case 1 — DeXAR (explainable smart-home HAR)

Raw sensor measurements are hard to explain to non-expert users, so DeXAR works on semantic states (high-level info describing what happened in a time interval — e.g., a pressure mat ON→OFF becomes using_kitchen_chair [t1,t2]). Pipeline:

Extract semantic states Segmentation → semantic image Explainable DL classifier + XAI (heatmap) Semantic Explanation Generator → natural language
  • A semantic image includes the semantic states observed in the segment + the most recent K past activities; any CV XAI method (LIME, GradCAM, prototypes) can be applied.
  • The heatmap is useful for data scientists; since each pixel has a semantic, a natural-language explanation is built (threshold the relevant features → sentence via heuristics or an LLM).

Explanation Score

A metric to automatically evaluate the consistency of an explanation with common-sense knowledge about the HAR domain (e.g., washing dishes happens in the kitchen, after eating). Common-sense knowledge is encoded in a semantic model defining which features partially explain each activity; a feature counts positively if it partially explains the activity, negatively otherwise.

AmI use case 2 — X-CHAR (counterfactuals for nurse care)

When nurses only wear an inertial device, complex activities are recognized as sequences of simpler low-level activities ("concepts"). X-CHAR learns to recognize concepts and then complex activities end-to-end, and produces a counterfactual explanation: it stores all concept sequences from training, and for a test sequence c finds the nearest one cex with minimum distance but a different class (e.g., "it would be 'Cleaning the Patient' had the sequence been Measure Blood Glucose → Oral care → Cleaning Genital Area").

ThinkA smart-home model labels a window as "Eating". One tool highlights which sensor pixels mattered ("dining-room chair, cooker"); another says "it would have been 'Cooking' had the cooker activated after — not before — sitting at the table". Which XAI families are these, and which is a counterfactual?
Answer: The first is an attribution / feature-importance explanation — a heatmap of which input parts drove the prediction (DeXAR-style, via LIME/GradCAM/prototypes), translated to natural language. The second is a counterfactual explanation: it describes a hypothetical reality contradicting the observed facts ("if the order had been different, the class would have flipped to Cooking") — the smallest change that modifies the output, exactly the X-CHAR concept-reordering idea and the definition behind sim Q21. Attribution answers "what mattered?"; counterfactual answers "what minimal change flips the decision?".

Final Quiz — Exam Style

15 MCQs + 2 open-ended. Two are the actual simulation questions (Q3, Q21) reproduced verbatim; the rest follow the professor's recipe — sibling distractors, one-word swaps, and a FALSE question hiding an absolutizer.

1
What is the main purpose of eXplainable AI?
AImproving the predictive accuracy of a black-box model on unseen data
BUnveiling the reasoning behind the predictions and decisions of ML models
CCompressing a deep model so it runs on resource-constrained devices
DDistributing the training of a model across many participating clients
B — XAI techniques reveal the why behind predictions, not only the what, helping understand the problem, the data and why a model might fail. A confuses accuracy with explainability, C is model compression (L7b), D is federated learning (L12).
2
Who are the "technicians" among the targets of explanations?
AMonitored subjects who use AI in daily life without ML knowledge
BSmart-city operators who act on the system's recommendations
CClinicians supported by the model during healthcare diagnosis
DData scientists / ML experts who monitor and improve the model and sensing setup
D — technicians are data scientists / ML experts who check if the sensing setup needs refinement, if more labeled data are needed, or if the model must be improved. A, B, C are all non-expert end-users (the other target category). Based on the target, explanations differ a lot.
3
What does local explainability address?
AWhy the model made a certain prediction for a specific instance
BHow the trained model makes predictions in general, and which features matter overall
CHow to compress the whole model into a smaller interpretable surrogate
DWhich clients contributed the most to the global federated model
A — local explainability asks why this instance got this prediction (it may depend only on some features); it's the most widely adopted because it's more accurate than global explanations. B is global explainability; C/D are unrelated. Global = the whole model; local = one prediction.
4
According to the accuracy–interpretability trade-off, which model is the most accurate but least interpretable?
ALinear regression
BDecision / regression trees
CDeep learning
DLasso / ridge regression
C — the slide's curve puts deep learning at high accuracy / low interpretability, with linear regression at the opposite end. The order: Deep Learning → Ensembles → SVM → k-NN → Trees → Lasso/Ridge → Linear Regression. A, B, D are all more interpretable but less accurate.
5
Which describes the model-agnostic category of XAI?
AClassic ML algorithms whose own parameters deliver the explanation
BMethods that decouple the explanation from the model, treating it as a black box
CNeural networks designed from the start to be interpretable
DMethods that reduce the numerical precision of the model's weights
B — model-agnostic XAI decouples the explanation from the model, applicable to any black box (model + explanation flexibility). A is interpretable models, C is deep explanation — the other two categories; D is quantization. The three categories: interpretable / model-agnostic / deep explanation.
6
In a linear regression model, what serves as a global explanation?
AThe weights, which indicate the importance of each feature
BThe path of the data point from the root to a leaf
CThe set of IF-THEN rules that fired for the prediction
DThe k prototypes closest to the input in the latent space
A — a linear model predicts a weighted sum of features, and the weights β₁…βₚ are the feature importance → a global explanation (cons: can't capture interactions). B is a decision tree local explanation, C is rules induction, D is the prototype approach.
7
How does a decision tree provide a local explanation for a prediction?
ABy measuring at each node how much the variance was reduced versus the parent
BBy weighting perturbed versions of the input by their similarity to the original
CBy tracking the path from root to leaf — the traversed conditions are the explanation
DBy computing the gradient on the last convolutional layer of the network
C — locally, the combination of conditions traversed on the root-to-leaf path explains the prediction. A is the tree's global feature-importance (variance reduction per node); B is LIME; D is GradCAM. Trees give both global and local explanations.
8
How does LIME build a local explanation?
ABy extracting motifs (repeating patterns) and training a model on them
BBy learning prototypes jointly with an autoencoder and a classifier
CBy computing feature importance from the weights of the trained black box
DBy generating perturbed inputs, predicting them with the black box, and fitting a weighted interpretable model
D — LIME perturbs the input, gets black-box predictions, and trains an interpretable surrogate (e.g., linear regression) with each perturbed sample weighted by similarity to the original, achieving local fidelity. A is subsequence-based time-series XAI, B is the prototype network, C assumes access to weights (LIME treats the model as a black box).
9
Simulation exam · Q21
Which of the following is a "counterfactual explanation"?
AThe AI model would have classified the activity as 'using treadmill' instead of 'jogging', if it had been carried out in a gym instead of a park.
BThe AI model classified the activity as 'jogging' because it associated a high weight to the feature related to the semantic location "park".
CThe AI model classified the activity as 'jogging' mainly because the subject was at the park. Indeed, when masking the feature about the semantic location "park", the classifier is no confident anymore on 'jogging'.
DThe AI model classified the activity as 'jogging' because the feature vector is similar to a sample in the training set that was labeled as 'jogging'.
A — a counterfactual is "if X had not occurred, Y would not have occurred" — a hypothetical reality contradicting the observed facts (gym instead of park → treadmill instead of jogging). B is a feature-importance / weight explanation, C is an attribution / ablation explanation (masking a feature), D is a prototype / instance-based explanation. Only A imagines a changed input flipping the class.
10
In rules induction, what constitutes the global explanation?
AThe single IF-THEN rule that fired for the current prediction
BAll the rules together, each covering a portion of the dataset
CThe weights associated with each input feature
DThe smallest change to the input that flips the predicted class
B — the set of rules used for a prediction is the local explanation, while all the rules together form the global one (approaches: Sequential Covering, Bayesian Rules Lists). A is the local case, C is linear regression, D is a counterfactual.
11
Why is interpreting a neural network via its gradients attractive?
ABecause a human can easily follow the exact mapping from input to prediction
BBecause it avoids having to train the network with backpropagation
CBecause it is more computationally efficient than model-agnostic methods looking from the outside
DBecause gradients guarantee the explanation always matches human intuition
C — a single deep prediction has millions of operations (humans can't follow it — so A is false); networks learn features in hidden layers and the gradient can implement interpretation methods more efficiently than external model-agnostic methods. B is nonsensical, D is an absolutized overclaim.
12
Simulation exam · Q3
Which information of the neural network does GradCAM use to generate a heatmap highlighting the regions of the input considered important for classification?
AThe gradient on the softmax layer
BThe gradient on the final dense layer
CThe gradient on the final convolutional layer
DThe gradient on each convolutional layer
C — GradCAM back-propagates the class score's gradient to the last convolutional layer (the one before the dense layers) and weights the feature maps by it. A (softmax) and B (dense) are the wrong layers — GradCAM needs the spatial feature maps of the conv layer; D ("each" conv layer) over-generalizes — it's specifically the last one.
13
In the self-explaining network that learns prototypes, which three components are trained in parallel?
AA domain classifier, a discrepancy loss, and a classification loss
BAn autoencoder for the latent space, a prototype layer, and the classification task
CA scheduler thread, an updater thread, and a staleness weighting
DA perturbation generator, a similarity weighting, and a linear surrogate
B — the model jointly learns the latent space (autoencoder), the prototypes (prototype layer), and the classification task (FC + softmax), using squared L² distance to prototypes and two regularization terms. A is UDA (L11), C is FedAsync (L12), D is LIME. To visualize latent prototypes you use the decoder.
14
In DeXAR, why are sensor data first turned into semantic states?
ABecause raw sensor measurements are hard to explain to non-expert users
BBecause semantic states reduce the numerical precision of the model's weights
CBecause they allow training the classifier without any labeled data
DBecause they remove the need for any computer-vision XAI method
A — XAI only makes sense if the explanation's semantics are understandable, but raw measurements aren't; DeXAR derives semantic states (e.g., pressure mat ON→OFF → using_kitchen_chair[t1,t2]), builds a semantic image, applies a CV XAI method (LIME/GradCAM/prototypes), then generates natural language. B/C/D are false: it still needs labels, still uses CV XAI, and isn't about quantization.
15
Which of these sentences on model-agnostic approaches is FALSE?
AThey can be applied to any model treated as a black box
BThe explanation may include different features than the ones actually used by the model
CThey offer model flexibility and explanation flexibility
DTheir explanations always reproduce exactly the calculations made by the original model
D is FALSE — the slide states explanations "do not always mimic the actual calculations" of the original model and may use different features. "always reproduce exactly" is the absolutizer tell. A, B, C are true. In a FALSE question, hunt always / exactly / never / only.
16
Open-ended · XAI foundations
a) What is XAI and why does it matter in AmI? Distinguish global vs local explainability and the accuracy–interpretability trade-off, and name the three categories of XAI approaches.
b) Describe the interpretable models (linear regression, decision trees, rules induction) and how each delivers global and/or local explanations.
Model answer

a) XAI techniques unveil the reasoning behind ML predictions — important because in many AmI domains (healthcare, smart cities, energy) it matters not only what is predicted but why, helping understand the problem/data and why a model may fail; HCI and psychology matter too, since explanations must be effectively delivered to the target (non-expert end-users vs technicians). Global explainability asks how the trained model predicts in general and which features matter overall (usually prohibitive for the whole model); local explainability asks why a specific instance got its prediction (most adopted, more accurate than global). Accuracy–interpretability trade-off: the most accurate models are the least interpretable — Deep Learning (high accuracy, low interpretability) → Ensembles → SVM → k-NN → Trees → Lasso/Ridge → Linear Regression. Three categories: Interpretable Models, Model-Agnostic, Deep Explanation.

b) Linear regression: prediction = weighted sum of features; the weights = feature importance → a global explanation (simple, but can't capture interactions and has low accuracy). Decision trees: capture complex feature relationships; global = feature importance from how much each node reduces variance vs its parent; local = the conditions on the root-to-leaf path of the data point. Rules induction: learn IF-THEN rules, each covering a portion of the data; the rules firing for a prediction are the local explanation, all rules together the global one (e.g., Sequential Covering, Bayesian Rules Lists). Pro: very simple; con: classic models are sometimes too simple versus deep learning.

17
Open-ended · From model-agnostic to deep explanation, and time series
a) Explain model-agnostic XAI (LIME and counterfactual explanations) and its problems, then GradCAM and the prototype-based deep-explanation network.
b) How are explanations evaluated (over-reliance + the four measures), and how is XAI applied to time series in AmI (DeXAR, Explanation Score, X-CHAR counterfactuals)?
Model answer

a) Model-agnostic XAI decouples the explanation from the model (any black box). LIME: generate perturbed versions of the input, predict them with the black box, and fit an interpretable surrogate (e.g., linear regression) with samples weighted by similarity to the original, achieving local fidelity. Counterfactual: "if X had not occurred, Y would not have occurred" — the smallest realistic change to the input that flips the prediction (pros: clear, easy; cons: multiple, possibly contradictory counterfactuals). Problem of model-agnostic: explanations don't always mimic the model's real calculations and may use different features → motivates explaining deep models directly. GradCAM: for CNNs, back-propagate the class score's gradient to the last convolutional layer, global-average-pool the gradients as weights, ReLU(Σ αₖᶜAᵏ) → a heatmap of relevant input regions. Prototype-based deep explanation: case-based reasoning; a network learns in parallel a latent space (autoencoder), a prototype layer (m prototypes), and the classifier; explanation = the k closest prototypes (squared L² distance), visualized via the decoder; two regularizers tie prototypes and training examples together.

b) Evaluation: convincing ≠ effective — a key risk is over-reliance (trusting the system just because it explains). Measures: User Satisfaction (clarity/utility, questionnaires), Mental Model (does the user understand the model — describe the process), Trust Assessment (cognitive, positive or negative, questionnaires before/after), Correctability (can XAI identify errors → correction & continuous training, automatic methods). Time series: time-points based (relevance per sample — attributions like LIME/GradCAM vs internal attention), subsequence based (motifs), instance based (feature/prototype/counterfactual). DeXAR: extract semantic states → semantic image → explainable DL classifier + CV XAI heatmap → natural-language explanation. Explanation Score: automatically measures consistency with common-sense knowledge (which features partially explain an activity). X-CHAR: recognizes complex nurse activities as sequences of concepts and gives a counterfactual = the nearest training concept-sequence with minimum distance but a different class.

0/15
MCQ score 0/15