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:
Store-based (preferred):
nirs4all.predict(chain_id="abc", data=X)replays a stored chain directly from the workspace store.Model-based:
nirs4all.predict(model="model.n4a", data=X)resolves via PredictionResolver / BundleLoader.Calibrated replayed-array:
nirs4all.predict(model=calibrated, data={"y_pred": y, "sample_ids": ids})applies an existing conformal calibrator to already computed point predictions.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=Trueremains 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_idtogether with a raw numpy array fordata:>>> result = nirs4all.predict(chain_id="abc123", data=X_new)
Model-based – pass
modeltogether withdata:>>> 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
.n4acarrying 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.bestorresult.top()- Path to exported bundle:"exports/model.n4a"- Path to pipeline config directory Mutually exclusive withchain_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 instancechain_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_idoutside a session. Ignored when asessionis 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=..., onlyall_predictions=Falseis currently supported.coverage – Optional conformal interval coverage selector. This is supported when
modelis either a calibrated replayed-array result/store/bundle withdata={"y_pred": ..., "sample_ids": ...}or a model.n4abundle carrying an attached conformal sidecar withdata={"X": ..., "sample_ids": ...}. The selector must reference already materialized coverages; it never recalibrates or creates a new guarantee. If a model bundle contains aconformal/sidecar, the sidecar is validated strictly; invalid sidecars fail validation instead of falling back to uncalibrated prediction.save_to_workspace – If
True, publish the returnedPredictResultthroughsave_workspace_predict_result(...)and addworkspace_prediction_idtoresult.metadata. This publishes prediction/evidence rows only; conformal artifacts remain owned bysave_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.metadatawhen 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
modelnorchain_idis 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 pipelinenirs4all.explain(): Generate SHAP explanationsnirs4all.api.result.PredictResult: Result class