nirs4all.api.retrain module

Module-level retrain() function for nirs4all.

This module provides a simple interface for retraining nirs4all pipelines on new data. Full retrain of a concrete DAG-ML bundle replays its native training contract; the historical PipelineRunner path requires an explicit engine="legacy" selection. A canonical Core .n4a container (or the CanonicalN4aRunResult that produced it) is retrained only with engine="native": Core re-runs cross-validation, selection and refit from the recipe stored in the container on a new IO record.

Example

>>> import nirs4all
>>> # Full retrain on new data
>>> result = nirs4all.retrain(
...     source="exports/model.n4a",
...     data=new_data,
...     mode="full"
... )
>>> print(f"New RMSE: {result.best_rmse:.4f}")
nirs4all.api.retrain.retrain(source: SourceSpec | BundleLoader, data: DataSpec, *, mode: str = 'full', name: str = 'retrain_dataset', new_model: Any | None = None, epochs: int | None = None, session: Session | None = None, verbose: int = 1, save_artifacts: bool = True, **kwargs: Any) → RunResult[source]

Retrain a pipeline on new data.

This function enables retraining trained pipelines with various modes, allowing for full retraining, transfer learning, or fine-tuning.

Parameters:
  • source –

    Pipeline source to retrain from. Can be: - Prediction dict from result.best or result.top() - Path to exported bundle: "exports/model.n4a" - Path to pipeline config directory - Path to a canonical Core .n4a container, or the

    CanonicalN4aRunResult returned by run(..., native_profile="nirs4all.n4a.container.v1") (requires engine="native")

  • data –

    New dataset to train on. Can be: - Path to data folder: "new_data/" - Numpy arrays: (X, y) - Dict: {"X": X, "y": y} - SpectroDataset instance - For a canonical .n4a source: the exact new IO record as a

    path or bytes, or {"record": <path or bytes>}

  • mode – Retrain mode. Options: - “full”: Train everything from scratch (same pipeline structure) - “transfer”: Use existing preprocessing, train new model - “finetune”: Continue training existing model Default: “full”

  • name – Name for the retrain dataset (for logging). Default: “retrain_dataset”

  • new_model – Optional new model for transfer mode. Replaces the original model while keeping preprocessing.

  • epochs – Optional number of epochs for fine-tuning neural networks.

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

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

  • save_artifacts – Whether to save retrained artifacts. Default: True

  • **kwargs –

    Additional retraining parameters and the frozen API-004 controls engine, plugin, and allow_fallback. Transfer through the bounded Python-library adapter requires plugin="nirs4all-python-library" explicitly. Historical rollback execution requires engine="legacy" explicitly. - learning_rate: Learning rate for fine-tuning - freeze_layers: List of layers to freeze during fine-tuning - step_modes: Per-step mode overrides (advanced) - methods_library_path: Methods library for a canonical .n4a

    retrain (the only option that retrain accepts). Other options, new_model, epochs, sessions and non-full modes are refused before any fit.

Returns:

  • predictions: Predictions from the retrained pipeline

  • per_dataset: Per-dataset execution details

  • best: Best prediction entry

  • best_score: Best model’s primary test score

Return type:

RunResult containing

Raises:

Examples

Full retrain on new data:

>>> import nirs4all
>>>
>>> # Retrain the training contract stored in a native bundle
>>> retrained = nirs4all.retrain(
...     source="exports/original_model.n4a",
...     data=new_train_data,
...     mode="full"
... )
>>> print(f"Retrained: {retrained.best_rmse:.4f}")

Transfer learning with new model:

>>> from sklearn.ensemble import RandomForestRegressor
>>>
>>> result = nirs4all.retrain(
...     source="exports/pls_model.n4a",
...     data=new_data,
...     mode="transfer",
...     new_model=RandomForestRegressor(n_estimators=100),
...     plugin="nirs4all-python-library"
... )

Fine-tune a neural network:

>>> result = nirs4all.retrain(
...     source="exports/nn_model.n4a",
...     data=new_data,
...     mode="finetune",
...     epochs=10,
...     learning_rate=0.0001,
...     engine="legacy"
... )

Retrain a canonical Core .n4a on a new IO record (fresh full retrain from the stored recipe; the source container is unchanged):

>>> result = nirs4all.retrain(
...     "exports/canonical.n4a",
...     "new_train_record.json",
...     engine="native",
... )
>>> result.export("exports/canonical_retrained.n4a")

Retrain from an exported bundle:

>>> result = nirs4all.retrain(
...     source="exports/wheat_model.n4a",
...     data="new_wheat_data/",
...     mode="full",
...     verbose=2
... )
>>> result.export("exports/retrained_model.n4a")

See also

  • nirs4all.run(): Train a pipeline from scratch

  • nirs4all.predict(): Make predictions

  • nirs4all.pipeline.RetrainMode: Retrain mode enum

nirs4all.api.retrain.retrain_preflight(mode: str = 'full', *, engine: str | None = None, plugin: str | None = None, allow_fallback: bool = False, session_present: bool = False) → RetrainCapabilityDecision[source]

Return the side-effect-free API-004 decision for retrain.