Module contents
Lesson 1 of 39Review 70 min

Review and map: how models fail and what it means to trust them

Review epistemic and aleatoric uncertainty and calibration as foundations of trustworthiness. Organize ML system failure modes and introduce threat models, lifecycle attack surfaces, and evaluation protocols for each dimension of trust.

After this lesson you can

  • Recall the predictive variance decomposition into epistemic and aleatoric components and calculate it for an ensemble.
  • Classify real incidents as statistical, adversarial, systemic, or specification failures.
  • Formulate a complete threat model, including objective, knowledge, capability, and budget, for an ML system.
  • Locate each attack studied in the module at its lifecycle point.
  • Connect each trustworthiness dimension with its evaluation protocol.

Before you start

One number is not a guarantee

A 99% test accuracy can hide a shortcut in the images, a different device at the receiving hospital, an attacker controlling part of the inputs, or an agent confusing instructions with document content. Each claim depends on the population, metric, and protocol. The failure taxonomy separates four useful questions, although an incident can fit several:

  • Statistical: sampling, shortcuts, changing data, or poorly estimated uncertainty.
  • Adversarial: someone chooses actions to affect integrity, availability, or confidentiality.
  • Systemic: the model interacts unexpectedly with tools, people, processes, or infrastructure.
  • Specification: the objective or training variable does not represent the desired human goal.

Evidence matters. In a skin lesion study, marking benign nevi with ink changed a network’s melanoma score; this is an artifact sensitivity experiment, not an estimate of population harm. An external validation of a sepsis model examined alerts and missed cases in a hospital: discrimination alone is insufficient when the clinical workflow must manage alerts. Obermeyer and colleagues documented racial disparities caused by using healthcare spending as a proxy for need in a health management application. Greshake and colleagues demonstrated in real systems and experimental applications that instructions in retrieved content can divert an LLM application. Each study has its own scope; none establishes that all systems fail in the same way.

Uncertainty and calibration

For an ensemble of MM models, if member mm predicts mean μm\mu_m and conditional variance vmv_m, the total variance decomposition is

Var⁡(Y∣x)≈1M∑mvm+1M∑m(μm−μˉ)2,μˉ=1M∑mμm.\Var(Y\mid x)\approx\frac1M\sum_m v_m+\frac1M\sum_m(\mu_m-\bar\mu)^2,\qquad \bar\mu=\frac1M\sum_m\mu_m.

The first term represents conditional noise in each member and the second disagreement among means. A finite ensemble is not necessarily a posterior sample and its heads may be misspecified: the curves are estimates. In classification, the difference between mixture entropy and mean conditional entropy measures disagreement under that mixture; total entropy also includes noise.

InteractiveTwo kinds of uncertainty
  • Mean aleatoric variance
  • Dispersion of means
Data in center
Noise at x > 0
Mean disagreement in center0.072
Predicted noise in right region0.033
Five networks trained on resampled synthetic data. Change data in the gap or noise on the right to compare predicted variances and dispersion of means; both can respond to training.

The generating signal is sin⁡(2x)\sin(2x) over [−2,2][-2,2]; noise has standard deviation 0.15, or 0.5 in the positive region when high noise is enabled. Each network uses two hidden layers of 32 units, a Gaussian head, and 500 training steps on a resample. Changing data and noise can also change disagreement: these are not perfect measures of separate causes.

A prediction is calibrated when, among examples assigned a given confidence, the accuracy frequency matches that confidence under the population and definition considered. ECE approximates the discrepancy by binning predictions; it depends on interval number, shape, and occupancy. A predictor that always returns the base rate can be calibrated yet discriminate poorly. Temperature scaling fits a positive parameter on validation data; it changes neither binary logit order nor guarantees calibration outside that distribution.

InteractiveCalibration under corruption
  • Ideal
  • Observed groups
Corruption
Temperature
ECE0.025
Accuracy0.930
NLL0.183
Gradient boosting fitted on Wisconsin Breast Cancer, temperature selected on clean validation data, and held-out test. Synthetic Gaussian noise is added to features of the same test; temperature remains fixed.

What to measure for trust

The dimensions of trustworthiness cannot be reduced to one another. NIST AI RMF 1.0 proposes managing risk throughout the lifecycle. It is a voluntary framework, not a certificate of no harm. Turn each dimension into a concrete protocol:

DimensionExample protocol
Accuracy and calibrationHeld-out test, NLL, diagram, and ECE with intervals and subgroups.
Shift and unknown dataTemporal or cross-site validation; OOD detection with defined alternatives.
Robustness and securityCorruptions and attacks under explicit capabilities and budgets.
PrivacyMembership auditing or a formal guarantee under differential privacy assumptions.
FairnessCompare errors and decisions across groups with context and sample limits.
Explainability and agencyInterventions and fidelity tests; permission and failure-recovery tests.

Defining the adversary

A threat model specifies objective, knowledge, capabilities, and budget. Integrity targets decisions; availability targets the service; confidentiality targets protected information. White, gray, and black box describe degrees of access, not absolute power. Specify what the adversary can modify, whether they see labels or scores, query count, constraints, and measurable success. Hiding architecture can change attack cost, but does not replace that evaluation.

The attack surface includes collection, labeling, training, artifacts, API, and agent tools. The catalogs MITRE ATLAS y OWASP GenAI help enumerate hypotheses; they do not turn each capability into a proven attack.

InteractiveCapabilities and lifecycle
DataLabelingTrainingArtifactAPIAgent + documents
Enable a capability to explore the surface.
Active hypotheses0
Grant capabilities and follow links to the corresponding lessons. Highlighted cases are test hypotheses, not simulated incidents or guaranteed successes.

The module progresses from uncertainty, conformal prediction, and shift detection to interpretability and circuits; then covers evasion, adversarial training, poisoning, extraction, privacy, fairness, and agent security. Each part adds a protocol, and a real system may require several at once.

Lab: a quick audit

The Wisconsin Breast Cancer dataset is included in scikit-learn. Reserve 20% for temperature validation and 20% for testing, with stratification; training, validation, and test are disjoint. The first feature selects a test subset without consulting labels: it changes the input marginal and does not cover the full support. Subsequent Gaussian corruption is another synthetic shift and may also change the conditional distribution; it is not assumed to be pure covariate shift. The true-class confidence gap is an exploratory overfitting signal, not proof or a measurement of membership-inference success. Equal-mass groups split ties in stable order, so they may differ from other binning criteria. Download audit.py to run it separately.

[ ]Tabular audit and temperatureBrowser
"""Auditoría didáctica: Wisconsin Breast Cancer (sklearn), shift simulado."""
import numpy as np
from scipy.optimize import minimize_scalar
from scipy.special import expit,logit
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,log_loss

def ece(probs,labels,n_bins=10,strategy='width'):
    p=np.asarray(probs);y=np.asarray(labels);conf=np.maximum(p,1-p);correct=(p>=.5)==y
    if strategy=='width':groups=[np.where((conf>=lo)&((conf<hi) if i<n_bins-1 else (conf<=hi)))[0] for i,(lo,hi) in enumerate(zip(np.linspace(0,1,n_bins+1)[:-1],np.linspace(0,1,n_bins+1)[1:]))]
    elif strategy=='mass':groups=np.array_split(np.argsort(conf,kind='stable'),n_bins)
    else:raise ValueError('strategy debe ser width o mass')
    rows=[]
    for idx in groups:
        if len(idx):rows.append((len(idx),float(conf[idx].mean()),float(correct[idx].mean())))
    return sum(n/len(p)*abs(acc-c) for n,c,acc in rows),rows

def run():
    ds=load_breast_cancer();X=ds.data;y=ds.target
    Xtr,Xhold,ytr,yhold=train_test_split(X,y,test_size=.4,stratify=y,random_state=30)
    Xval,Xte,yval,yte=train_test_split(Xhold,yhold,test_size=.5,stratify=yhold,random_state=31)
    model=GradientBoostingClassifier(n_estimators=70,max_depth=2,random_state=30).fit(Xtr,ytr)
    def logits(data):return logit(np.clip(model.predict_proba(data)[:,1],1e-7,1-1e-7))
    zval=logits(Xval)
    def nll(logT):return log_loss(yval,expit(zval/np.exp(logT)),labels=[0,1])
    T=float(np.exp(minimize_scalar(nll,bounds=(-2,2),method='bounded').x))
    train_p=expit(logits(Xtr)/T);base_z=logits(Xte);base_p=expit(base_z/T)
    rng=np.random.default_rng(30);noise=rng.normal(size=Xte.shape)*Xtr.std(axis=0)
    print('Wisconsin Breast Cancer',len(Xtr),len(Xval),len(Xte),'T validación',T)
    for intensity in (0.,.25,.5,1.,2.):
        p=expit(logits(Xte+intensity*noise)/T);err,rows=ece(p,yte)
        print('corrupción',intensity,'accuracy',accuracy_score(yte,p>=.5),'NLL',log_loss(yte,p,labels=[0,1]),'ECE anchura',err)
    true_train=np.where(ytr,train_p,1-train_p);true_test=np.where(yte,base_p,1-base_p)
    print('confianza clase verdadera train/test',true_train.mean(),true_test.mean(),'brecha',true_train.mean()-true_test.mean())
    # Selección por x: el conjunto cambia su marginal; condicionada en x,
    # la regla de selección no consulta la etiqueta. Sin soporte completo.
    mask=Xte[:,0]>=np.median(Xtr[:,0])
    print('selección por primera variable n',int(mask.sum()),'accuracy',accuracy_score(yte[mask],base_p[mask]>=.5),'ECE',ece(base_p[mask],yte[mask])[0])
    print('ECE masa test',ece(base_p,yte,strategy='mass')[0])
    return model,(Xtr,ytr,Xval,yval,Xte,yte),T,noise

if __name__=='__main__':run()

To complete a worksheet, consider a hypothetical API returning probabilities to external users: confidentiality objective, black-box access to scores, 1000 queries per account, and known candidates. The next action is to measure a membership attack on independent members and nonmembers, report TPR at low FPR and uncertainty, and compare with a baseline. The lab gap alone does not answer that question.

Exercises

QuizA shortcut
A study finds that a mark on lesion images changes a network score. Which type of failure does this primarily illustrate?
QuizManipulated training
Someone introduces mislabeled emails into a filter’s training data. How would you classify this capability?
QuizEmail agent
A retrieved document induces an agent to use a tool outside the user’s intent. What kind of risk arises?
QuizA proxy variable
Healthcare spending is predicted to allocate care, but the goal is clinical need. What risk should be reviewed?
QuizNew site
A system moves to a different hospital with different devices. Which hypothesis should be investigated?
QuizMembership
An attacker queries an API to determine whether a person was in training. What is the objective?
QuizAPI threat model
A public API returns probabilities but not weights. What access and objective are plausible for an extraction audit?
QuizOn-device model
An attacker physically controls a device with the model installed. What must be specified?
QuizAgent with tools
The attacker can modify a retrieved email, but not the system prompt. What capability would you describe?
NumericEnsemble variance
Five means are 1, 2, 3, 4, and 5; each member predicts conditional variance 1. Using weights 1/5, what is total predictive variance?
CodeMaximum-confidence ECE
Implement ece(probs, labels, n_bins, strategy) for binary class-1 probabilities. Confidence is max(p,1−p), correctness is (p≥0.5)==label. width uses equal-width bins in [0,1] with the final bin closed; mass stably sorts by confidence and splits into n_bins groups of sizes as equal as possible. Ignore empty groups and weight by frequency.
def ece(probs, labels, n_bins, strategy):
  pass
Shift+Enter to run

Summary

Key idea
Trust requires linking a measurable claim to its population, threat, budget, and consequences, and reviewing the entire system.
  • Uncertainty and calibration describe different aspects of prediction; they change with the model and data.
  • Statistical, adversarial, systemic, and specification failures can coexist.
  • Adversary capability determines relevant tests; a hypothesis does not establish success.