nirs4all.api.session module
Session context manager for nirs4all API.
A Session maintains shared resources across multiple nirs4all operations, including a reusable PipelineRunner instance, consistent workspace paths, and shared logging configuration.
Two usage patterns:
- Context manager for shared runner (resource reuse):
>>> with nirs4all.session(verbose=2, save_artifacts=True) as s: ... r1 = nirs4all.run(pipeline1, data1, session=s) ... r2 = nirs4all.run(pipeline2, data2, session=s) ... # Both runs share workspace and configuration
- Stateful session with pipeline (training workflow):
>>> session = nirs4all.Session(pipeline=pipeline, name="MyModel") >>> result = session.run(dataset) >>> predictions = session.predict(new_data) >>> session.save("model.n4a")
- class nirs4all.api.session.Session(pipeline: List[Any] | None = None, name: str = '', **runner_kwargs: Any)[source]
Bases:
objectExecution session for resource reuse and stateful pipeline management.
A session can be used in two modes:
Resource sharing mode (no pipeline): Share a PipelineRunner across multiple nirs4all.run() calls.
Stateful pipeline mode (with pipeline): Manage a single pipeline’s lifecycle: train, predict, save, load.
- name
Session/pipeline name for identification.
- pipeline
Pipeline definition (if in stateful mode).
- status
Current session status (‘initialized’, ‘trained’, ‘error’).
- is_trained
Whether the pipeline has been trained.
- runner
The shared PipelineRunner instance.
- workspace_path
Path to the workspace directory.
- Example (resource sharing):
>>> with nirs4all.session(verbose=1) as s: ... result1 = nirs4all.run(pipeline1, data1, session=s) ... result2 = nirs4all.run(pipeline2, data2, session=s)
- Example (stateful pipeline):
>>> session = nirs4all.Session(pipeline=pipeline, name="MyModel") >>> result = session.run("sample_data/regression") >>> predictions = session.predict(new_data) >>> session.save("exports/my_model.n4a")
- __exit__(exc_type: Any, exc_val: Any, exc_tb: Any) None[source]
Exit the session context and clean up resources.
- close() None[source]
Clean up session resources.
Called automatically when exiting a context manager block.
- predict(dataset: str | Path | Any, **kwargs: Any) PredictResult[source]
Make predictions using the trained pipeline.
- Parameters:
dataset – Data to predict on. Can be: - Path to data folder - Numpy array X - Dict with ‘X’ key
**kwargs – Additional arguments for prediction.
- Returns:
PredictResult with predictions.
- Raises:
ValueError – If session has not been trained.
- retrain(dataset: str | Path | Any, mode: str = 'full', **kwargs: Any) RunResult[source]
Retrain the pipeline on new data.
- Parameters:
dataset – New dataset to train on.
mode – Retrain mode (‘full’, ‘transfer’, ‘finetune’).
**kwargs – Additional arguments for retraining.
- Returns:
RunResult from retraining.
- Raises:
ValueError – If session has not been trained.
- run(dataset: str | Path | Any, *, plots_visible: bool = False, **kwargs: Any) RunResult[source]
Train the session’s pipeline on a dataset.
- Parameters:
dataset – Dataset to train on. Can be: - Path to data folder: “sample_data/regression” - Numpy arrays: (X, y) - Dict: {“X”: X, “y”: y}
plots_visible – Whether to show plots during training.
**kwargs – Additional arguments passed to runner.run().
- Returns:
RunResult with predictions and metrics.
- Raises:
ValueError – If no pipeline was provided to the session.
- property runner: PipelineRunner
Get or create the shared PipelineRunner instance.
The runner is created lazily on first access.
- Returns:
The shared PipelineRunner instance.
- save(path: str | Path) Path[source]
Save the trained session to a bundle file.
- Parameters:
path – Output path for the .n4a bundle file.
- Returns:
Path to the saved bundle file.
- Raises:
ValueError – If session has not been trained.
- nirs4all.api.session.load_session(path: str | Path) Session[source]
Load a session from a saved bundle file.
- Parameters:
path – Path to .n4a bundle file.
- Returns:
Session ready for prediction.
Example
>>> session = nirs4all.load_session("exports/model.n4a") >>> predictions = session.predict(new_data)
- nirs4all.api.session.session(pipeline: List[Any] | None = None, name: str = '', **kwargs: Any) Generator[Session, None, None][source]
Create an execution session context manager.
This is a convenience function that creates a Session and yields it within a context manager block.
- Parameters:
pipeline – Optional pipeline definition for stateful mode.
name – Name for the session/pipeline.
**kwargs – Arguments passed to Session (and ultimately PipelineRunner). Common options: - verbose (int): Verbosity level (0-3). Default: 1 - save_artifacts (bool): Save model artifacts. Default: True - workspace_path (str|Path): Workspace directory. - random_state (int): Random seed for reproducibility.
- Yields:
Session – The active session for use within the block.
- Example (resource sharing):
>>> with nirs4all.session(verbose=2, save_artifacts=True) as s: ... r1 = nirs4all.run(pipeline1, data1, session=s) ... r2 = nirs4all.run(pipeline2, data2, session=s) ... print(f"PLS: {r1.best_score:.4f}, RF: {r2.best_score:.4f}")
- Example (stateful pipeline):
>>> with nirs4all.session(pipeline=my_pipeline, name="Demo") as s: ... result = s.run("sample_data/regression") ... print(f"Best score: {result.best_score:.4f}")