spectrochempy.cross_validate

cross_validate(estimator, X, y, *, cv=5, groups=None, sample_dim='y', metrics=('rmsecv', 'r2'), return_estimators=False)[source]

Evaluate a fixed supervised regression configuration by cross-validation.

Each fold receives a fresh unfitted estimator. Pipeline preprocessing is learned only from that fold’s calibration observations, and predictions are assembled once in the original target order and geometry. The supplied estimator, datasets, groups, and explicit splitter remain unchanged.

Parameters:
  • estimator (PLSRegression or Pipeline) – Unfitted or fitted template to clone for each fold. A Pipeline must end in PLSRegression.

  • X (NDDataset) – Two-dimensional predictor dataset.

  • y (NDDataset) – One- or two-dimensional target dataset aligned with X along sample_dim.

  • cv (int, KFold, GroupKFold, or LeaveOneOut, optional, default: 5) – Cross-validation design. An integer creates unshuffled KFold when groups is absent and GroupKFold otherwise. Integers must be at least 2; booleans and floating-point values are rejected.

  • groups (array-like or NDDataset, optional) – One group identity per observation. Required by GroupKFold and forbidden for splitters that do not use groups.

  • sample_dim (str, optional, default: β€œy”) – Dimension identifying observations independently in X and y.

  • metrics (ordered iterable of str, optional) – Global metrics selected from "rmsecv", "r2", "bias", and "mae". Names must be unique and the order is preserved. "rmse" is not a public selector; fold records use that generic internal name. An empty selection is rejected.

  • return_estimators (bool, optional, default: False) – Retain independent fitted estimators for every fold. Enabling this may substantially increase memory use.

Returns:

CrossValidationResult – Structured OOF predictions, residuals, global and fold metrics, validated positions, configuration snapshots, and optional estimators. Dataset members are isolated copies but remain mutable.

Raises:

SpectroChemPyError – If the estimator, splitter, groups, geometry, masks, values, metrics, or complete unique OOF coverage violate the bounded v1 contract.

See also

CrossValidationResult

Structured result returned by this function.

Notes

This function evaluates one fixed estimator configuration. It performs no hyperparameter search, nested cross-validation, final full-data fit, persistence, replay, or automatic provenance capture.

Examples

>>> values = np.arange(24.0).reshape(8, 3)
>>> X = scp.NDDataset(values, dims=["y", "x"])
>>> y = scp.NDDataset((1.0 + values[:, 0])[:, None], dims=["y", "t"])
>>> model = scp.PLSRegression(n_components=1, scale=False)
>>> result = scp.cross_validate(model, X, y, cv=4)
>>> result.oof_predictions.shape
(8, 1)
>>> result.metric("rmsecv").values.shape
(1,)

Examples using spectrochempy.cross_validate

Cross-validation of corn moisture models

Cross-validation of corn moisture models