Refit cross-validation¶
A fold plan records which original rows a refit may use and which rows it
must predict. fold_plan constructs reusable random, grouped, or stratified
partitions; cross_validate applies an existing fitting procedure to those
partitions and scores its raw held-out likelihoods. Both need only PyTorch.
The result retains (i) the complete partition and selected folds, (ii) the original rows in each predictive unit, and (iii) optional actual fitted results. This page first specifies partition and scoring semantics, then applies the same runner to QVR source and formula fits.
Partitions and predictive units¶
FoldPlan.assignments contains one zero-based fold per original included row.
fold_plan(n, folds=k, groups=labels) keeps every group in one fold;
strata=labels balances strata across folds. A grouped stratum must be constant
within each indivisible group. Random tie breaking uses a local seeded stream.
Construction takes linear storage and uses a heap to balance groups, avoiding
work proportional to the number of folds for every row.
For leave-one-out prediction, use one fold per row. To leave out the rest of that
row's group as well, set FoldPlan.omission_groups: split.test still names the
one designated row, while split.omitted includes its whole group. Thus the
training set and prediction unit can express different questions.
A refit returns FoldPrediction(log_likelihood=...), with unweighted response
scores of shape (chain, draw, test_row) in exactly split.test order. The
callback owns preprocessing, priors, basis construction, and inference quality.
In particular, fit learned preprocessing on training rows and apply the retained
transformation to held-out rows; splitting after fitting preprocessing may leak
information. An excluded group can leave no training rows, so that callback must
then support a prior fit.
joint="observation" scores each row separately. joint="fold" scores the whole
held-out fold together; joint="group" and explicit groups score each group
within a fold. Multiple responses require an explicit responses selection and
aligned joint posterior draws. The runner sums all selected response and row log
likelihoods within each draw, then computes log-mean-exp across draws. Summing
marginal log predictive densities instead would describe a different prediction.
The brms K-fold reference
distinguishes these observation, fold, and group prediction units. The
loo ELPD reference describes
pointwise log-likelihood arrays with separate iteration, chain, and data axes.
fold_ids evaluates a subset without extrapolating missing folds. result.elpd
sums only evaluated units; result.complete reports whether all folds ran.
result.se is the descriptive square root of the number of units times their
sample variance, rather than a Monte Carlo error estimate or a correction for
overlapping training sets. Zero predictive densities remain -inf; an undefined
SE is NaN. Compare models using the same rows, response selection, partition,
and predictive units. These policies also correspond to the partition, selected
fold, and joint-scoring controls in the
brms K-fold interface.
QVR source refits¶
Each callback fits a fresh binding of the same specification. Held-out scoring
uses ModelFit.log_likelihood, including its checked response semantics and
retained parameters. The small budgets below demonstrate the interface; assess
optimization or MCMC diagnostics before interpreting predictive comparisons.
import torch
from quivers.diagnostics import FoldPrediction, cross_validate, fold_plan
from quivers.modeling import Model, VariationalMethod
source = """object Row : FinSet _
object Out : Real 1
program regression(x : Tensor[Real]([Row]), y : Tensor[Real]([Row])) : Row -> Out
sample b <- Normal(loc=0.0, scale=1.0)
let mu = b * x
observe y : Row <- Normal(loc=mu, scale=1.0)
return b
export regression
"""
specification = Model(source)
data = {"x": torch.tensor([-1., 0., 1., 2.]),
"y": torch.tensor([-0.7, 0.1, 0.9, 1.8])}
plan = fold_plan(4, folds=2, seed=11)
def refit(split):
training = {name: value[list(split.train)] for name, value in data.items()}
testing = {name: value[list(split.test)] for name, value in data.items()}
fitted = specification.fit(
training, method=VariationalMethod(num_steps=2, seed=split.seed),
)
scores = fitted.log_likelihood(testing, num_samples=4, seed=split.seed)
return FoldPrediction(log_likelihood=scores, fit=fitted)
result = cross_validate(plan, refit, save_fits=True)
assert result.complete and result.log_predictive_density.shape == (4,)
assert set(result.fits) == {0, 1}
Prediction reuses the fitted latent layout. Row-specific latent variables whose layout changes with held-out data require an explicit marginal or new-level prediction policy; a refitter must provide those raw scores rather than silently rebinding them to unrelated latent coordinates.
Formula refits¶
The callback changes, while the partition and scorer remain the same. Formula
fits use their existing log_likelihood(new_data=...) path, which retains response
transforms, categories, and declared group prediction policies.
import pandas as pd
from quivers.diagnostics import FoldPrediction, cross_validate, fold_plan
from quivers.formulas import fit
frame = pd.DataFrame({"x": [-1., 0., 1., 2.], "y": [-0.7, 0.1, 0.9, 1.8]})
plan = fold_plan(len(frame), folds=2, seed=11)
def refit_formula(split):
fitted = fit(
"y ~ x", data=frame.iloc[list(split.train)],
method="svi", num_steps=2, seed=split.seed,
)
scores = fitted.log_likelihood(
new_data=frame.iloc[list(split.test)], num_samples=4, seed=split.seed,
)
return FoldPrediction(log_likelihood=scores)
result = cross_validate(plan, refit_formula, joint="fold")
assert result.complete and result.log_predictive_density.shape == (2,)
A new grouping level requires the fitted predictor's explicit new-level policy.
The runner does not infer that policy from fold labels. Fold-specific streams are
stable under fold selection and evaluation order, and participating caller RNG
streams are restored after each callback. Actual fits are retained only when
save_fits=True; otherwise they can be released before the next fold.
cross_validation
¶
Explicit refit partitions and held-out posterior predictive scores.
FoldLabel
¶
A retained group or stratum label; labels are never inferred from outcomes.
FoldSplit
didactic-model
¶
FoldSplit(*, fold: int, train: tuple[int, ...], test: tuple[int, ...], omitted: tuple[int, ...], seed: int)
Bases: ValueModel
Original row identities for one refit and its held-out prediction.
| PARAMETER | DESCRIPTION |
|---|---|
fold
|
Zero-based fold identity in the complete plan.
TYPE:
|
train
|
Original row positions supplied to the refitting procedure.
TYPE:
|
test
|
Original row positions to predict, in their original order.
TYPE:
|
omitted
|
Rows excluded from training, possibly including other group members.
TYPE:
|
seed
|
Fold-specific seed independent of evaluation order or selected folds.
TYPE:
|
FoldPlan
didactic-model
¶
FoldPlan(*, assignments: tuple[int, ...], seed: int = 0, omission_groups: tuple[FoldLabel, ...] = ())
Bases: ValueModel
A reusable complete partition, independent of model and fitting backend.
| PARAMETER | DESCRIPTION |
|---|---|
assignments
|
One zero-based fold per original included row. Every fold must occur.
TYPE:
|
seed
|
Nonnegative seed used to derive independent refit streams.
TYPE:
|
omission_groups
|
Optional grouping identities. A fold also omits every member of a held-out row's group, while predicting only its designated test rows. This expresses leave-one-out prediction with whole-group exclusion.
TYPE:
|
num_folds
property
¶
Return the number of nonempty folds.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Complete partition size. |
split
¶
split(fold: int) -> FoldSplit
Resolve training, omitted, and prediction rows for one fold.
| PARAMETER | DESCRIPTION |
|---|---|
fold
|
Zero-based fold identity.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FoldSplit
|
Original positions; an explicitly omitted whole group can make training empty, in which case the refitter must support prior fits. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the requested fold is outside the complete partition. |
Source code in src/quivers/diagnostics/cross_validation.py
FoldPrediction
didactic-model
¶
FoldPrediction(*, log_likelihood: Mapping[str, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fit: object | None = field(default=None, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
Raw held-out likelihoods returned by a refitting adapter.
| PARAMETER | DESCRIPTION |
|---|---|
log_likelihood
|
Response scores of shape (chain, draw, test row), unweighted and with each response event already reduced. Joint responses share draw axes.
TYPE:
|
fit
|
Optional actual fitted result, retained only when save_fits is true.
TYPE:
|
CrossValidationResult
didactic-model
¶
CrossValidationResult(*, plan: FoldPlan, fold_ids: tuple[int, ...], responses: tuple[str, ...], joint: Literal['observation', 'fold', 'group'], units: tuple[tuple[int, tuple[int, ...]], ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), log_predictive_density: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), fits: Mapping[int, object] = field(default_factory=dict, opaque=True, extras=OPAQUE_BY_IDENTITY))
Bases: ValueModel
Predictive scores from explicit refits on a retained partition.
| PARAMETER | DESCRIPTION |
|---|---|
plan
|
Complete original partition.
TYPE:
|
fold_ids
|
Evaluated folds; a subset is never extrapolated to a full result.
TYPE:
|
responses
|
Selected response names, summed within each joint posterior draw.
TYPE:
|
joint
|
Predictive unit: observation, whole fold, or group within fold.
TYPE:
|
units
|
Fold identity and original response positions for every scored unit.
TYPE:
|
log_predictive_density
|
Float64 log-mean likelihood per unit, preserving zero densities as -inf.
TYPE:
|
fits
|
Optional actual refits keyed by complete-plan fold identity.
TYPE:
|
complete
property
¶
Report whether every fold in the retained partition was evaluated.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
False for a partial fold selection, regardless of score values. |
fold_plan
¶
fold_plan(size: int, *, folds: int = 10, groups: Sequence[FoldLabel] | None = None, strata: Sequence[FoldLabel] | None = None, seed: int = 0) -> FoldPlan
Construct seeded balanced random, grouped, or stratified folds.
| PARAMETER | DESCRIPTION |
|---|---|
size
|
Number of original included response rows.
TYPE:
|
folds
|
Number of nonempty folds, at most the number of independent groups. Setting this to size gives leave-one-out when groups are absent.
TYPE:
|
groups
|
Indivisible units assigned wholly to one fold.
TYPE:
|
strata
|
Labels balanced across folds. Every indivisible group must have one stratum; small strata need not occur in every fold.
TYPE:
|
seed
|
Local random stream; the caller's RNG is preserved.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FoldPlan
|
Original row order and exact assignments for reuse across models. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If counts, labels, or group/stratum combinations are invalid. |
Source code in src/quivers/diagnostics/cross_validation.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | |
cross_validate
¶
cross_validate(plan: FoldPlan, refit: Callable[[FoldSplit], FoldPrediction], *, fold_ids: Sequence[int] | None = None, responses: Sequence[str] | None = None, joint: Literal['observation', 'fold', 'group'] = 'observation', groups: Sequence[FoldLabel] | None = None, save_fits: bool = False) -> CrossValidationResult
Refit selected partitions and score held-out units within joint draws.
| PARAMETER | DESCRIPTION |
|---|---|
plan
|
Explicit reusable partition of original included rows.
TYPE:
|
refit
|
Adapter that fits only split.train and scores exactly split.test. It owns preprocessing, prior/basis policy, inference quality, and raw observation semantics; the runner does not fit another model itself.
TYPE:
|
fold_ids
|
Nonempty unique subset of complete-plan folds, or all folds.
TYPE:
|
responses
|
Explicit joint response selection; required with multiple scored names.
TYPE:
|
joint
|
Sum row/response log likelihoods within a draw before log-mean-exp.
TYPE:
|
groups
|
Original row labels for joint group-within-fold prediction units.
TYPE:
|
save_fits
|
Retain actual callback results and their omitted-row metadata in plan.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
CrossValidationResult
|
Conditional predictive scores from refits, retaining exact row units. Leave-one-out partitions still have the supplied fitter's approximation. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If selections, response shapes, or scores are invalid or inconsistent. |
TypeError
|
If a refitter does not return raw real floating-point likelihoods. |
Source code in src/quivers/diagnostics/cross_validation.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |