"Attribution tells me which millisecond mattered. A prototype tells me what I was reminded of. Only one of those survives a conversation with a technician."
A Case-Based AI Agent
The Big Picture
Saliency and attribution (Sections 67.1 and 67.2) answer where a model looked. They rarely answer what the model thinks it saw. A vibration classifier that fires on an early bearing fault does not reason in raw samples; it reasons in patterns: a rising sideband, a spectral hump, a windowed shape it has met before. Concept- and prototype-based methods make that vocabulary explicit. A prototype is a learned reference example ("this new window looks like that known fault"); a concept is a human-named direction in feature space ("how much impact-transient energy is present"). Both replace a heatmap over 512 timesteps with a sentence a domain expert can accept or reject. This section builds the two families, connects them, shows where each is faithful, and where each quietly lies.
This section assumes you are comfortable with learned embeddings for sensor windows (Chapter 13), with contrastive representation learning that shapes those embedding spaces (Chapter 17), and with the shapelet and feature ideas from Chapter 8. Prototypes are, in effect, learnable shapelets living in embedding space.
Prototype networks: reasoning by resemblance
The prototype recipe adapts the vision idea of "this looks like that" (ProtoPNet, Chen et al. 2019) to sequences. An encoder \(f\) maps a window \(x\) to an embedding \(z = f(x) \in \mathbb{R}^d\). A prototype layer holds \(K\) learnable vectors \(p_1,\dots,p_K\), each tied to a class. The network scores a window by its similarity to every prototype, then classifies from those similarities alone:
$$ s_k(x) = \exp\!\left(-\,\lVert f(x) - p_k \rVert_2^2 \,/\, \tau\right), \qquad \hat{y} = \operatorname{softmax}\!\big(W\, [\,s_1,\dots,s_K\,]\big). $$Because the final decision is a sparse weighted sum over similarities, every prediction decomposes into "activated 0.81 on prototype #12, which is the outer-race defect from bearing B-207, logged 2024-03." The crucial trick, from ProSeNet (Ming et al. 2019) and its descendants, is a projection step: after training, each prototype vector is snapped onto the embedding of a real training window nearest to it. That guarantees the explanation is an actual measured signal you can plot, not a synthetic point in latent space that corresponds to nothing physical.
Three loss terms make the prototypes usable. A clustering term pulls every training embedding close to some prototype of its class; a separation term pushes embeddings away from other classes' prototypes; and a diversity term penalizes prototypes that collapse onto each other, so you get distinct failure archetypes rather than twelve copies of one. Getting the similarity metric right matters: Euclidean distance in a poorly aligned embedding treats two identical shapes offset by three samples as different. Encoders trained with temporal augmentation, or a soft dynamic-time-warping distance, restore the shift invariance that raw \(\ell_2\) throws away.
Key Insight
A prototype explanation is faithful by construction in a way a post-hoc saliency map is not. The similarity scores \(s_k\) are the literal inputs to the classifier head, so "it resembled prototype #12" is not a guess about the model, it is the arithmetic the model actually ran. The remaining question is not faithfulness but meaningfulness: does prototype #12 correspond to a coherent physical phenomenon a human recognizes, or to a spurious cluster the encoder invented? Projection onto real examples exposes that immediately, because you can look at the plotted signal and say "that is just sensor dropout, not a fault."
Concept-based explanations: naming the axes
Prototypes explain by example; concepts explain by attribute. Testing with Concept Activation Vectors (TCAV, Kim et al. 2018) asks a different question: how sensitive is the model's fault prediction to a human concept such as "high-frequency ringing"? You assemble a small set of windows that exhibit the concept and a set that does not, train a linear probe in an intermediate activation layer to separate them, and take the probe's normal vector \(v_C\) as the concept direction. The concept's influence on class \(c\) is the fraction of examples whose directional derivative along \(v_C\) is positive:
$$ \mathrm{TCAV}_{c,C} = \frac{1}{|X_c|}\sum_{x \in X_c} \mathbb{1}\!\left[\, \nabla h_c\big(f_\ell(x)\big) \cdot v_C \;>\; 0 \,\right]. $$A score near 1 means the concept consistently pushes the model toward class \(c\); near 0.5 means it is irrelevant. This is powerful for auditing: you can test whether a sleep-stage model relies on "delta-wave power" (a clinically valid concept) or on "electrode pop artifacts" (a leakage concept it should ignore). Concept Bottleneck Models (Koh et al. 2020) go further and force the architecture through a named concept layer: the network first predicts interpretable concepts, then predicts the label only from those concepts. That makes the model steerable, because a technician who corrects a wrong concept value gets a corrected downstream prediction, but it costs accuracy whenever the pre-declared concepts miss something the raw signal contained.
Practical Example: the gearbox that flagged the wrong tooth
A wind-farm operator ran a prototype-based condition monitor on accelerometer streams from turbine gearboxes (the anomaly-scoring backbone comes from Chapter 37). An alert fired on turbine T-14 with 0.88 activation on a prototype the dashboard labeled "gear-mesh sideband growth." The reliability engineer pulled up the projected prototype window: a real vibration snippet from a turbine that had later lost a gear tooth. Side by side with T-14's window, the resemblance was obvious, and the crew scheduled a borescope that found early pitting. Months later a second alert fired on the same prototype, but the projected example this time looked nothing like T-14; a TCAV audit revealed the encoder had begun leaning on a "cold-morning DC-offset" concept correlated with a recalibrated sensor. The prototype view caught a real fault; the concept audit caught the model drifting onto a spurious cue. Neither a bare saliency map nor a bare accuracy number would have surfaced either story.
Building a prototype layer on sensor embeddings
The code below defines a minimal prototype head over any frozen or trainable encoder, and shows the two operations that make it interpretable: scoring by similarity, and the post-training projection of each prototype onto its nearest real embedding. It is deliberately small so the mechanism is visible; production trees add the clustering, separation, and diversity losses discussed above.
import torch
import torch.nn as nn
import torch.nn.functional as F
class PrototypeHead(nn.Module):
def __init__(self, dim, n_prototypes, n_classes, tau=1.0):
super().__init__()
self.prototypes = nn.Parameter(torch.randn(n_prototypes, dim))
self.classifier = nn.Linear(n_prototypes, n_classes, bias=False)
self.tau = tau
def similarities(self, z): # z: (B, dim) embeddings
d2 = torch.cdist(z, self.prototypes) ** 2 # squared L2 to each prototype
return torch.exp(-d2 / self.tau) # (B, n_prototypes), in (0, 1]
def forward(self, z):
s = self.similarities(z)
return self.classifier(s), s # logits AND the explanation vector
@torch.no_grad()
def project_to_data(self, bank_z): # bank_z: (N, dim) real windows
d2 = torch.cdist(self.prototypes, bank_z) ** 2
nearest = d2.argmin(dim=1) # index of closest real window
self.prototypes.copy_(bank_z[nearest]) # snap prototypes onto real data
return nearest # rows to plot as the "that"
# usage: each prediction carries s, and nearest[k] names the plottable exemplar
head = PrototypeHead(dim=128, n_prototypes=20, n_classes=4)
z = torch.randn(8, 128) # encoder output for 8 windows
logits, s = head(z)
top_proto = s.argmax(dim=1) # which archetype each window matched
similarities returns the exact vector fed to the linear classifier, so it doubles as the explanation; project_to_data replaces each learned prototype with the nearest real training window so every "this looks like that" points at a signal you can plot and hand to an expert.Notice that forward returns s alongside the logits: the explanation is not computed by a separate tool afterward, it falls out of the forward pass. That is the structural advantage of self-explaining models over the post-hoc attribution of Section 67.1.
Library Shortcut
Hand-rolling the full ProSeNet training loop (encoder, projection scheduling, and the clustering, separation, and diversity losses) runs to roughly 250 lines. Concept auditing with captum.concept.TCAV replaces about 120 lines of probe-fitting and directional-derivative bookkeeping with a dozen: you supply concept and random example batches, and Captum fits the CAVs, computes the sign-count statistics, and returns per-layer significance with a two-sided test built in. Reach for the library for the CAV machinery and the projection scheduler; keep the prototype layer itself hand-written, since it is ten lines and you want full control over the distance metric.
When each family earns its keep
Prototypes shine when the operator's mental model is case-based: technicians already reason "this sounds like the pump we replaced last spring," so a nearest-archetype explanation lands without training. They degrade when classes have no compact archetype (diffuse, high-variance faults need dozens of prototypes and the explanation stops being concise). Concepts shine when you have a pre-existing vocabulary to audit against, especially for detecting spurious cues and satisfying a reviewer who asks "does it use anything it should not?" They degrade when the true discriminative feature has no name yet, because a concept bottleneck can only reason with concepts you thought to declare. In predictive-maintenance workflows (Chapter 36) the two compose well: prototypes for the front-line alert, TCAV as a periodic audit that the prototype library has not drifted onto sensor artifacts. Always fix prototypes and concept sets on the training split only, using the leakage-safe partitions of Chapter 65; a prototype projected onto a test window has quietly memorized the test set.
Research Frontier
Current work pushes both families toward temporal faithfulness. ProSeNet (Ming et al., KDD 2019) established sequence prototypes with projection; P2ExNet and subsequent "this looks like that for time series" variants add subsequence-level prototypes so the explanation localizes which part of the window matched, not just the whole window. On the concept side, Concept Bottleneck Models (Koh et al., ICML 2020) are being extended with concept-discovery methods that learn candidate concepts and only then ask a human to name them, addressing the "you can only audit concepts you declared" limitation. The open problem for sensors specifically is metric choice: prototypes under Euclidean distance are not shift-invariant, and soft-DTW prototype layers are still expensive to train at fleet scale. Expect faithfulness benchmarks (Section 67.7, XTSC-Bench) to start scoring prototype meaningfulness, not just prediction accuracy.
Exercise
Take a human-activity-recognition encoder (walking, running, cycling, stairs) trained on wrist-IMU windows and attach the PrototypeHead above with 5 prototypes per class. After training, call project_to_data and plot every projected prototype. (1) Identify at least one prototype that is not a clean activity exemplar (for example, a transition or a device-removal artifact) and explain why the diversity loss failed to prevent it. (2) Build a small "arm-swing periodicity" concept set and a random set, run TCAV against the "walking" class, and report whether the model relies on the concept you expect. (3) Swap the Euclidean distance for a soft-DTW distance and report how the projected prototypes change.
Self-Check
- Why is a prototype similarity score \(s_k\) faithful "by construction" while an Integrated-Gradients heatmap is only an approximation of the model's reasoning?
- A colleague projects prototypes onto the combined train-plus-test set to "get the best-looking exemplars." What evaluation error has this introduced, and what would the reported accuracy no longer mean?
- Give one fault scenario where a concept-bottleneck model would systematically miss the true cause, and explain why a plain prototype network might still catch it.
What's Next
In Section 67.5, we move from "what does this window resemble" to "what caused it": root-cause graphs turn a fired alert into a directed structure over sensors, subsystems, and events, so an explanation stops being a single archetype and becomes a traceable chain through the physical system.