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 models, if member predicts mean and conditional variance , the total variance decomposition is
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.
The generating signal is over ; 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.
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:
| Dimension | Example protocol |
|---|---|
| Accuracy and calibration | Held-out test, NLL, diagram, and ECE with intervals and subgroups. |
| Shift and unknown data | Temporal or cross-site validation; OOD detection with defined alternatives. |
| Robustness and security | Corruptions and attacks under explicit capabilities and budgets. |
| Privacy | Membership auditing or a formal guarantee under differential privacy assumptions. |
| Fairness | Compare errors and decisions across groups with context and sample limits. |
| Explainability and agency | Interventions 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.
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.
"""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
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):
passSummary
- 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.