/gpcam:uncertainty-calibrationfrom gpcam
Validates gpCAM posterior uncertainty calibration using scoring rules (NLPD, CRPS, MSLL), calibration/coverage curves, PICP, and interval width. Detects over/under-confidence before publishing or autonomous loop use.
Ships in gpcam. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Verified against gpCAM 8.7.0 / fvgp 4.11.1 — last checked 2026-10-28 (gpCAM a21385a).
A GP's headline product is not the prediction — it is the uncertainty on the
prediction. An autonomous loop acts on that uncertainty at every step: "variance"
goes where the model claims ignorance, "ucb" and "expected improvement" weigh
mean against spread, and any convergence rule that stops when variance falls below a
threshold is trusting the error bar completely. An overconfident GP will stop
early, under-sample the interesting region, and report a wrong error bar with
conviction.
This skill is about checking that the error bars are honest. Run it after training and before believing any result.
import numpy as np
# Hold out data the GP has never seen. Random split, not the tail of the loop —
# adaptively-acquired points are not i.i.d. and will flatter the model.
print(f"RMSE {gpo.rmse(x_test, y_test):.4f}") # accuracy only
print(f"NLPD {gpo.nlpd(x_test, y_test):.4f}") # accuracy + calibration (lower better)
print(f"PICP {gpo.picp(x_test, y_test, interval=0.95):.3f} (target 0.95)")
print(f"MPIW {gpo.mpiw(x_test, interval=0.95):.4f}") # average width of that interval
If PICP ≈ 0.95 and NLPD is small, the posterior is roughly trustworthy. If
PICP is far from 0.95, stop and read the rest of this skill — nothing downstream
is reliable.
Shapes must match posterior_mean(x_test)["m(x)"].shape (gp_optimizer.py:615). rmse, nlpd, and crps assert posterior_mean(x_test)["m(x)"].shape == y_test.shape: for a single-task GP, y_test must be 1-D (V,) (not (V, 1)); for a multi-task GP (including multi_task_mode="cartesian"), x_test is (V, D) and y_test must be (V, No) across all No = len(x_out) tasks.
| Method | What it measures | Reading it |
|---|---|---|
rmse(x_test, y_test) | Accuracy of the mean only | Lower better. Blind to uncertainty — a model with absurd error bars can have excellent RMSE. |
nrmse(x_test, y_test) | RMSE / range(y) | Dimensionless; use to compare across datasets. |
mae / mape | Mean absolute / percentage error | Robust to outliers; mape breaks near y = 0. |
r2(x_test, y_test) | Fraction of variance explained | 1 is perfect, 0 is no better than predicting the mean. |
nlpd(x_test, y_test) | Negative log predictive density | The primary scoring rule. Penalizes both wrong means and wrong spreads. Lower is better; can be negative. Use this to choose between models. |
crps(x_test, y_test) | Continuous ranked probability score | Returns a tuple (mean, std) — unpack it. Lower better, in the units of y, and less brutal than NLPD toward badly-underestimated variances. |
msll(x_test, y_test) | Mean standardized log loss | NLPD relative to a trivial Gaussian baseline fitted to the training data. Negative means you beat the baseline; ≈ 0 means the GP learned nothing useful. |
picp(x_test, y_test, interval=q) | Prediction Interval Coverage Probability — fraction of test points inside the q credible interval | Compare against q itself. This is the calibration workhorse. |
mpiw(x_test, interval=q) | Mean Prediction Interval Width | Only meaningful alongside picp: an interval can always reach its coverage by growing uselessly wide. |
interval_score(x_test, y_test, interval=q) | Coverage and width in one number | Lower better. Penalizes both misses and excessive width — the right single metric when tuning for interval quality. |
coverage_curve(x_test, y_test, intervals=None) | picp across many levels | The full calibration picture. See below. |
crps returning two values is a common trip-up:
crps_mean, crps_std = gpo.crps(x_test, y_test) # NOT a single float
A single PICP@95 compresses the whole calibration story into one number. The
coverage curve evaluates picp across many levels at once and shows you how the
model is wrong, not just that it is:
cc = gpo.coverage_curve(x_test, y_test) # default: 19 levels from 0.05 to 0.95
target = np.array(cc["target_coverage"])
measured = np.array(cc["measured_coverage"])
for t, m in zip(target, measured):
print(f" target {t:.2f} -> measured {m:.3f} {'over-confident' if m < t else 'under-confident'}")
# Single-number summary: mean absolute calibration error
print(f"Calibration error: {np.mean(np.abs(measured - target)):.4f}")
Plot measured against target:
import matplotlib.pyplot as plt
plt.plot(target, measured, "o-", label="model")
plt.plot([0, 1], [0, 1], "k--", label="perfect calibration")
plt.xlabel("target coverage"); plt.ylabel("measured coverage"); plt.legend()
| Curve shape | Meaning | Consequence in an autonomous loop |
|---|---|---|
| On the diagonal | Well calibrated | Error bars mean what they say |
| Below the diagonal | Over-confident — intervals too narrow | Loop stops early, under-explores, publishes error bars that are too small. The dangerous failure. |
| Above the diagonal | Under-confident — intervals too wide | Loop over-explores and wastes measurements; conclusions are safe but inefficient |
| S-shaped / crossing | Mis-specified shape, not just scale | Usually a wrong noise model or a non-Gaussian likelihood — a transformed optimizer may be the fix |
A worked example of what over-confidence looks like: understating the noise variance
by 100× on an otherwise identical model moved PICP@95 from 0.95 to 0.88 and NLPD
from 0.23 to 4.21. RMSE barely moved. This is exactly why RMSE cannot be your only
check.
Most common, most dangerous. In rough order of likelihood:
Understated observation noise. You passed noise_variances that are too small,
or your noise function's hyperparameter hit its lower bound. Check:
print(gpo.get_data()["measurement variances"][:5])
print(gpo.hyperparameters) # is a noise hp pinned at its bound?
Fix: raise the noise, or switch from fixed noise_variances to a learnable
noise_function so the data can speak. See the noise-functions skill.
Length scale too short. The GP fits every wiggle, treats the residual as signal, and leaves no uncertainty between points. Check whether a length scale is sitting at its lower bound; raise that bound.
Wrong noise structure. Heteroscedastic data fitted with constant noise is
over-confident in the noisy region and under-confident in the quiet one — this
produces the S-shaped curve. Fix with a position-dependent noise_function.
Test set is not independent. Points chosen by ask() cluster where the model
was uncertain, so scoring on them is not a fair test. Hold out a random subset
before the loop starts.
Less harmful but wasteful:
noise_variances, or lower the noise hyperparameter's
upper bound.r2; if it is poor and the model is under-confident, it is
underfitting.hps[0] inflates every interval.Use mpiw on subsets to localize it, or plot residuals against predicted std:
mean = gpo.posterior_mean(x_test)["m(x)"]
std = np.sqrt(gpo.posterior_covariance(x_test, variance_only=True)["v(x)"])
z = (y_test - mean) / std # should be ~ N(0, 1) if well calibrated
print(f"z mean {z.mean():+.3f} (want 0) z std {z.std():.3f} (want 1)")
plt.hist(z, bins=30, density=True)
z.std() > 1 means over-confident, < 1 means under-confident, and a non-zero
z.mean() means the prior mean is biased — see the prior-mean-functions skill.
This standardized-residual histogram is the analogue of a PIT histogram for a
Gaussian posterior, and it localizes problems that a single scalar hides.
If y is strictly positive or bounded, a plain GP is often structurally
mis-calibrated near the boundary: it puts probability mass on impossible values, so
lower credible bounds go negative and coverage is wrong exactly where the data is
most interesting.
Check calibration on the original scale using evaluate_posterior, not the
latent-space metrics:
post = gpo.evaluate_posterior(x_test, level=0.95)
covered = (y_test >= post["lower"]) & (y_test <= post["upper"])
print(f"original-scale PICP@95: {covered.mean():.3f}")
The inherited picp / nlpd / coverage_curve operate in the GP's latent space,
which is the correct check for the latent model but not the number you report to a
collaborator. If latent calibration is good but original-scale coverage is poor, the
transform is the problem. See the transformed-optimizers-advanced skill.
Track calibration as data accumulates — it will drift, especially early:
holdout_x, holdout_y = ... # reserved BEFORE the loop, never told to the GP
history = []
for i in range(N_ITERATIONS):
... # ask / measure / tell
if (i + 1) % RETRAIN_EVERY == 0:
gpo.train(hyperparameter_bounds=hp_bounds, method="local", n_restarts=1)
history.append({
"n": len(gpo.y_data),
"rmse": gpo.rmse(holdout_x, holdout_y),
"nlpd": gpo.nlpd(holdout_x, holdout_y),
"picp95": gpo.picp(holdout_x, holdout_y, interval=0.95),
})
print(history[-1])
Expect rmse and nlpd to fall and picp95 to settle near 0.95. If picp95 drifts
steadily down as points accumulate, the hyperparameters are overfitting the growing
dataset — re-run multi-restart local training (n_restarts=5, the train() default) or method="mcmc", or tighten the length-scale lower
bound.
Never score against points the GP has been told; rmse on training data measures
interpolation, not prediction, and will look excellent regardless.
gpo.plot_observed_vs_predicted(x_test, y_test) # needs matplotlib
Points should fall on the diagonal with scatter consistent with the error bars.
nlpd and picp at minimum.crps as a scalar. It returns (mean, std).picp without mpiw. Coverage is trivially achievable with absurdly wide intervals; always report both, or use interval_score, which combines them.y_test must match posterior_mean(x_test)["m(x)"].shape — (V,) for a single-task GP (not (V, 1)) and (V, No) for a multi-task GP.evaluate_posterior.gpcam.GPOptimizer inherits all of these from fvgp.GP — see the fvGP source for exact formulasexperiment-designer skill — where to put these checks in a generated scriptnoise-functions skill — the noise model is usually what calibration is really testingtransformed-optimizers-advanced skill — for constrained observationsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub lbl-camera/gpcam --plugin gpcam11 skills in this plugin
/acquisition-functionsUse when choosing or writing an acquisition function for gpCAM — selecting a built-in criterion for exploration, optimization, batch, or multi-task runs, or implementing a custom callable for UCB/LCB, minimization EI, constraints, radical gradient, or threshold finding./cost-functionsUse when modeling the real expense of moving between gpCAM measurement points — motor travel time, settling, directional costs, sample damage, beam time, or zone-based penalties./experiment-designerUse for end-to-end autonomous experiment design with gpCAM. Translates a scientist's description of their measurement into a complete, runnable gpCAM script — useful for replacing raster scans with adaptive sampling, peak-finding, or parameter optimization./gp2scale-advancedUse for large-scale gpCAM experiments (>10k points up to millions) using sparse compactly-supported kernels and Dask distributed computing for exact GP computation at scale./kernel-designerUse when designing or composing custom kernel (covariance) functions for gpCAM — smoothness, periodicity, symmetry, anisotropy, non-stationary amplitude/length-scale kernels (`non_stat_kernel`, Gibbs), non-Euclidean inputs, or neural-network-warped deep kernels (`Network`)./multi-task-advancedUse for multi-output, vector-valued, or function-valued gpCAM experiments using GPOptimizer with several output columns and multi_task_mode (or migrating legacy fvGPOptimizer code) — useful when a single measurement returns multiple correlated quantities (e.g., spectra, multi-channel detectors).Other plugins' skills for the same job