nirs4all.api.predict module

Module-level predict() function for nirs4all.

This module provides a simple interface for making predictions with trained nirs4all models. It wraps PipelineRunner.predict() with ergonomic defaults.

Prediction paths supported by the public API:

  1. Store-based (preferred): nirs4all.predict(chain_id="abc", data=X) replays a stored chain directly from the workspace store.

  2. Model-based: nirs4all.predict(model="model.n4a", data=X) resolves via PredictionResolver / BundleLoader.

  3. Calibrated replayed-array: nirs4all.predict(model=calibrated, data={"y_pred": y, "sample_ids": ids}) applies an existing conformal calibrator to already computed point predictions.

  4. Attached conformal model bundle: nirs4all.predict(model="model.calibrated.n4a", data={"X": X, "sample_ids": ids}, coverage=0.9) replays the model bundle and selects already materialized conformal intervals. all_predictions=True remains fail-closed for conformal sidecars until every returned prediction entry carries calibrated identity mapping.

Example

>>> import nirs4all
>>> result = nirs4all.predict(
...     model="exports/best_model.n4a",
...     data=X_new,
...     verbose=1
... )
>>> print(f"Predictions shape: {result.shape}")
nirs4all.api.predict.predict(model: ModelSpec | None = None, data: DataSpec | None = None, *, chain_id: str | None = None, workspace_path: str | Path | None = None, name: str = 'prediction_dataset', output: str | None = None, all_predictions: bool = False, session: Session | None = None, verbose: int = 0, coverage: float | list[float] | tuple[float, ...] | None = None, save_to_workspace: bool = False, workspace_metadata: Mapping[str, Any] | None = None, workspace_result_metadata: Mapping[str, Any] | None = None, **runner_kwargs: Any) → PredictResult[source]

Make predictions with a trained model on new data.

This function provides a simple interface for running inference with trained nirs4all pipelines.

Main prediction paths are supported:

Store-based (preferred) – pass chain_id together with a raw numpy array for data:

>>> result = nirs4all.predict(chain_id="abc123", data=X_new)

Model-based – pass model together with data:

>>> result = nirs4all.predict(model="exports/model.n4a", data=X_new)

Calibrated replayed-array – pass a calibrated result or conformal result archive together with already computed point predictions:

>>> result = nirs4all.predict(model=calibrated, data={"y_pred": y_pred, "sample_ids": ids}, coverage=0.9)

Attached conformal model bundle – pass a model .n4a carrying a conformal sidecar and explicit prediction sample ids:

>>> result = nirs4all.predict(model="exports/model.calibrated.n4a", data={"X": X_new, "sample_ids": ids}, coverage=0.9)
Parameters:
  • model – Trained model specification. Can be: - Prediction dict from result.best or result.top() - Path to exported bundle: "exports/model.n4a" - Path to pipeline config directory Mutually exclusive with chain_id.

  • data – Data to predict on. Can be: - Path to data folder: "new_data/" - Numpy array: X_new (n_samples, n_features) - Tuple: (X,) or (X, y) for evaluation - Dict: {"X": X, "metadata": meta} - SpectroDataset instance

  • chain_id – Chain identifier in the workspace store. When provided, uses the fast store-based replay path. Mutually exclusive with model.

  • workspace_path – Workspace root directory. Required when using chain_id outside a session. Ignored when a session is provided (the session’s workspace is used instead).

  • name – Name for the prediction dataset (for logging). Default: “prediction_dataset”

  • output – Explicit named output of a multi-output DAG host archive. Omit for ordinary single-output models.

  • all_predictions – If True, return predictions from all folds/entries for non-conformal predictions. With a conformal sidecar and coverage=..., only all_predictions=False is currently supported.

  • coverage – Optional conformal interval coverage selector. This is supported when model is either a calibrated replayed-array result/store/bundle with data={"y_pred": ..., "sample_ids": ...} or a model .n4a bundle carrying an attached conformal sidecar with data={"X": ..., "sample_ids": ...}. The selector must reference already materialized coverages; it never recalibrates or creates a new guarantee. If a model bundle contains a conformal/ sidecar, the sidecar is validated strictly; invalid sidecars fail validation instead of falling back to uncalibrated prediction.

  • save_to_workspace – If True, publish the returned PredictResult through save_workspace_predict_result(...) and add workspace_prediction_id to result.metadata. This publishes prediction/evidence rows only; conformal artifacts remain owned by save_workspace_calibrated_result(...).

  • workspace_metadata – Optional sample-level metadata forwarded to the workspace prediction sidecar when save_to_workspace=True.

  • workspace_result_metadata – Optional result-level metadata merged over result.metadata when publishing the workspace prediction row.

  • session – Optional Session for resource reuse. If provided, uses the session’s runner.

  • verbose – Verbosity level (0=quiet, 1=info, 2=debug). Default: 0

  • **runner_kwargs – Additional PipelineRunner parameters. Common options: plots_visible

Returns:

  • y_pred: Predicted values array (n_samples,)
    • metadata: Additional prediction metadata

    • model_name: Name of the model used

    • preprocessing_steps: List of preprocessing steps applied

Use result.to_dataframe() for pandas DataFrame output.

Return type:

PredictResult containing

Raises:
  • ValueError – If neither model nor chain_id is provided, or if both are provided.

  • FileNotFoundError – If model bundle or data path doesn’t exist.

Examples

Predict from a stored chain (preferred):

>>> import nirs4all
>>> result = nirs4all.predict(chain_id="abc123", data=X_new)

Predict from an exported bundle:

>>> result = nirs4all.predict(
...     model="exports/wheat_model.n4a",
...     data=X_new
... )

Predict using a result from a previous run:

>>> train_result = nirs4all.run(pipeline, train_data)
>>> pred_result = nirs4all.predict(
...     model=train_result.best,
...     data=X_test
... )

See also

  • nirs4all.run(): Train a pipeline

  • nirs4all.explain(): Generate SHAP explanations

  • nirs4all.api.result.PredictResult: Result class