nirs4all.controllers.models.stacking package

Submodules

Module contents

Stacking subpackage for meta-model training set reconstruction.

This module provides the TrainingSetReconstructor class and supporting utilities for building meta-model training features from out-of-fold predictions.

Phase 2 Classes:

TrainingSetReconstructor: Main class for OOF prediction collection and reconstruction. FoldAlignmentValidator: Validates fold structure consistency across source models. ValidationResult: Container for validation errors and warnings. ReconstructionResult: Container for reconstructed training set data.

Phase 3 Classes (Serialization & Prediction Mode):

SourceModelReference: Reference to a source model with feature mapping. MetaModelArtifact: Complete artifact for meta-model persistence. MetaModelSerializer: Handles serialization/deserialization of meta-model artifacts.

Phase 4 Classes (Branching Integration):

BranchValidator: Validates branch contexts for stacking compatibility. BranchType: Enum for branch type detection. BranchInfo: Information about branch context. BranchValidationResult: Result of branch validation.

Phase 5 Classes (Classification Support):

StackingTaskType: Enum for task types (regression, binary, multiclass). ClassificationInfo: Information about classification task detected from predictions. TaskTypeDetector: Detects task type from prediction metadata. ClassificationFeatureExtractor: Extracts probability features for classification. FeatureNameGenerator: Creates descriptive feature names for meta-features. MetaFeatureInfo: Information about generated meta-features for importance tracking.

Phase 7 Classes (Advanced Features):

MultiLevelValidator: Validates multi-level stacking hierarchies. ModelLevelInfo: Information about a model’s stacking level. LevelValidationResult: Result of multi-level validation. CrossBranchValidator: Validates cross-branch stacking compatibility. CrossBranchValidationResult: Result of cross-branch validation. BranchPredictionInfo: Information about predictions from a branch.

Exception Classes:

MetaModelError: Base exception for meta-model errors. MetaModelPredictionError: Base exception for prediction errors. MissingSourceModelError: Source model binary not found. SourcePredictionError: Source model prediction failed. FeatureOrderMismatchError: Feature columns don’t match expected order. BranchMismatchError: Branch context incompatible. MetaModelSerializationError: Base exception for serialization errors. MissingDependencyError: Dependency not serialized. BranchingError: Base exception for branching errors. IncompatibleBranchTypeError: Branch type not compatible with stacking. CrossPartitionStackingError: Cross-partition stacking attempted. NestedBranchStackingError: Nested branching too deep. FoldMismatchAcrossBranchesError: Folds don’t align across branches. DisjointSampleSetsError: Sample sets don’t overlap. MultiLevelStackingError: Base exception for multi-level stacking errors. CircularDependencyError: Circular dependencies detected in stacking. MaxStackingLevelExceededError: Maximum stacking level exceeded. CrossBranchStackingError: Base exception for cross-branch stacking errors. IncompatibleBranchSamplesError: Branches have incompatible samples. BranchFeatureAlignmentError: Feature alignment failed across branches.

Example

>>> from nirs4all.controllers.models.stacking import TrainingSetReconstructor
>>> from nirs4all.operators.models.meta import StackingConfig
>>>
>>> reconstructor = TrainingSetReconstructor(
...     prediction_store=predictions,
...     source_models=["PLS", "RF"],
...     stacking_config=StackingConfig()
... )
>>> result = reconstructor.reconstruct(dataset, context)
exception nirs4all.controllers.models.stacking.BranchFeatureAlignmentError(expected_features: int, branch_features: Dict[int, int], alignment_issues: List[str] | None = None)[source]

Bases: CrossBranchStackingError

Raised when cross-branch features cannot be aligned.

This occurs when attempting to combine predictions from multiple branches but the feature matrices cannot be properly aligned due to different preprocessing or ordering.

expected_features

Expected number of features.

branch_features

Dict mapping branch_id to feature count.

alignment_issues

List of specific alignment problems.

class nirs4all.controllers.models.stacking.BranchInfo(branch_type: BranchType, branch_id: int | None = None, branch_name: str | None = None, branch_path: List[int] = <factory>, partition_info: Dict[str, ~typing.Any] | None=None, exclusion_info: Dict[str, ~typing.Any] | None=None, sample_indices: List[int] | None = None, n_samples: int | None = None, is_nested: bool = False, nesting_depth: int = 0)[source]

Bases: object

Information about branch context for stacking validation.

branch_id: int | None = None
branch_name: str | None = None
branch_path: List[int]
branch_type: BranchType
exclusion_info: Dict[str, Any] | None = None
is_nested: bool = False
n_samples: int | None = None
nesting_depth: int = 0
partition_info: Dict[str, Any] | None = None
sample_indices: List[int] | None = None
exception nirs4all.controllers.models.stacking.BranchMismatchError(training_branch: Dict[str, Any], prediction_branch: Dict[str, Any], meta_model_id: str)[source]

Bases: MetaModelPredictionError

Raised when prediction branch doesn’t match training branch.

This occurs when attempting to use a meta-model trained in one branch for prediction in a different, incompatible branch context.

training_branch

Branch context during training.

prediction_branch

Branch context during prediction.

meta_model_id

The artifact ID of the meta-model.

class nirs4all.controllers.models.stacking.BranchPredictionInfo(branch_id: int, branch_name: str | None, model_names: List[str], sample_indices: Set[int], n_samples: int, n_folds: int, branch_type: BranchType = BranchType.UNKNOWN)[source]

Bases: object

Information about predictions from a specific branch.

branch_id

Unique branch identifier.

Type:

int

branch_name

Human-readable branch name.

Type:

str | None

model_names

List of model names in this branch.

Type:

List[str]

sample_indices

Set of sample indices with predictions.

Type:

Set[int]

n_samples

Number of samples.

Type:

int

n_folds

Number of folds.

Type:

int

branch_type

Type of branching.

Type:

nirs4all.controllers.models.stacking.branch_validator.BranchType

branch_id: int
branch_name: str | None
branch_type: BranchType = 'unknown'
model_names: List[str]
n_folds: int
n_samples: int
sample_indices: Set[int]
class nirs4all.controllers.models.stacking.BranchType(value)[source]

Bases: Enum

Types of branching in nirs4all pipelines.

GENERATOR = 'generator'
METADATA_PARTITIONER = 'metadata_partitioner'
NESTED = 'nested'
NONE = 'none'
OUTLIER_EXCLUDER = 'outlier_excluder'
PREPROCESSING = 'preprocessing'
SAMPLE_PARTITIONER = 'sample_partitioner'
UNKNOWN = 'unknown'
class nirs4all.controllers.models.stacking.BranchValidationResult(is_valid: bool, compatibility: StackingCompatibility, branch_info: BranchInfo, errors: List[str] = <factory>, warnings: List[str] = <factory>, source_filter_hint: Dict[str, ~typing.Any] | None=None)[source]

Bases: object

Result of branch validation for stacking.

add_error(message: str) None[source]

Add an error message.

add_warning(message: str) None[source]

Add a warning message.

branch_info: BranchInfo
compatibility: StackingCompatibility
errors: List[str]
is_valid: bool
source_filter_hint: Dict[str, Any] | None = None
warnings: List[str]
class nirs4all.controllers.models.stacking.BranchValidator(prediction_store: Predictions, log_warnings: bool = True)[source]

Bases: object

Validates branch contexts for meta-model stacking.

This validator checks that the current branch context is compatible with stacking and provides clear error messages for unsupported cases.

Supported scenarios: - No branching: Fully compatible - Preprocessing branches: Stack within branch - Outlier excluder branches: Stack within branch (all samples have predictions) - Sample partitioner branches: Stack within partition only

Unsupported or limited scenarios: - Cross-partition stacking with sample_partitioner - Deeply nested branching (depth > 2) - Generator syntax with large variant counts

Example

>>> validator = BranchValidator(prediction_store)
>>> result = validator.validate(context, source_model_names)
>>> if not result.is_valid:
...     raise ValueError(result.errors[0])
MAX_GENERATOR_VARIANTS_WARNING = 10
MAX_NESTING_DEPTH = 2
validate(context: ExecutionContext, source_model_names: List[str], dataset: SpectroDataset | None = None) BranchValidationResult[source]

Validate branch context for stacking compatibility.

Parameters:
  • context – Current execution context with branch info.

  • source_model_names – List of source model names to validate.

  • dataset – Optional dataset for sample index validation.

Returns:

BranchValidationResult with validation status and any errors.

validate_sample_alignment(source_model_names: List[str], expected_sample_indices: List[int], context: ExecutionContext) BranchValidationResult[source]

Validate that source models have predictions for expected samples.

This is particularly important for sample_partitioner branches where different partitions have different samples.

Parameters:
  • source_model_names – List of source model names.

  • expected_sample_indices – Expected sample indices (from current partition).

  • context – Execution context.

Returns:

Validation result with any sample alignment issues.

exception nirs4all.controllers.models.stacking.BranchingError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: MetaModelError

Base exception for branching-related errors in meta-model stacking.

exception nirs4all.controllers.models.stacking.CircularDependencyError(source_model: str, meta_model: str, dependency_chain: List[str])[source]

Bases: MultiLevelStackingError

Raised when circular dependencies are detected in multi-level stacking.

This occurs when a meta-model attempts to use itself or a model that depends on it as a source, creating a circular dependency.

source_model

Name of the source model causing the cycle.

meta_model

Name of the current meta-model.

dependency_chain

List of model names forming the cycle.

class nirs4all.controllers.models.stacking.ClassificationFeatureExtractor(classification_info: ClassificationInfo, use_proba: bool = False)[source]

Bases: object

Extracts classification features from predictions.

Handles extraction of probability features for binary and multiclass classification, with proper handling of different array shapes.

extract_features(pred: Dict[str, Any], n_samples: int) ndarray[source]

Extract features from a single prediction entry.

Parameters:
  • pred – Prediction dictionary with y_pred and optionally y_proba.

  • n_samples – Expected number of samples.

Returns:

Feature array of shape (n_samples,) or (n_samples, n_features).

get_n_features() int[source]

Get number of features that will be extracted per model.

Returns:

Number of feature columns per source model.

class nirs4all.controllers.models.stacking.ClassificationInfo(task_type: StackingTaskType, n_classes: int | None = None, class_labels: List[Any] | None = None, has_probabilities: bool = False, proba_shape: Tuple[int, ...] | None = None)[source]

Bases: object

Information about classification task detected from predictions.

task_type

Detected task type (regression/binary/multiclass).

Type:

nirs4all.controllers.models.stacking.classification.StackingTaskType

n_classes

Number of classes if classification, else None.

Type:

int | None

class_labels

Optional class labels if available.

Type:

List[Any] | None

has_probabilities

Whether y_proba is available in predictions.

Type:

bool

proba_shape

Shape of probability arrays if available.

Type:

Tuple[int, …] | None

class_labels: List[Any] | None = None
get_n_features_per_model(use_proba: bool = False) int[source]

Get number of features per source model.

Parameters:

use_proba – Whether probability features are requested.

Returns:

Number of feature columns per source model. - Regression: 1 (y_pred) - Binary + use_proba: 1 (positive class probability) - Multiclass + use_proba: n_classes (all class probabilities) - Classification without use_proba: 1 (y_pred)

has_probabilities: bool = False
property is_binary: bool

Check if this is binary classification.

property is_classification: bool

Check if this is a classification task.

property is_multiclass: bool

Check if this is multiclass classification.

n_classes: int | None = None
proba_shape: Tuple[int, ...] | None = None
task_type: StackingTaskType
class nirs4all.controllers.models.stacking.CrossBranchCompatibility(value)[source]

Bases: Enum

Compatibility level for cross-branch stacking.

COMPATIBLE = 'compatible'
COMPATIBLE_WITH_ALIGNMENT = 'compatible_with_alignment'
INCOMPATIBLE_PARTITIONS = 'incompatible_partitions'
INCOMPATIBLE_SAMPLES = 'incompatible_samples'
NOT_APPLICABLE = 'not_applicable'
exception nirs4all.controllers.models.stacking.CrossBranchStackingError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: BranchingError

Base exception for cross-branch stacking errors.

class nirs4all.controllers.models.stacking.CrossBranchValidationResult(is_compatible: bool = True, compatibility: CrossBranchCompatibility = CrossBranchCompatibility.NOT_APPLICABLE, branches: Dict[int, ~nirs4all.controllers.models.stacking.crossbranch.BranchPredictionInfo]=<factory>, common_samples: Set[int] = <factory>, alignment_issues: List[str] = <factory>, warnings: List[str] = <factory>, errors: List[str] = <factory>)[source]

Bases: object

Result of cross-branch stacking validation.

is_compatible

Whether cross-branch stacking is possible.

Type:

bool

compatibility

Detailed compatibility level.

Type:

nirs4all.controllers.models.stacking.crossbranch.CrossBranchCompatibility

branches

Dict of BranchPredictionInfo by branch_id.

Type:

Dict[int, nirs4all.controllers.models.stacking.crossbranch.BranchPredictionInfo]

common_samples

Set of samples present in all branches.

Type:

Set[int]

alignment_issues

List of alignment problems found.

Type:

List[str]

warnings

List of warning messages.

Type:

List[str]

errors

List of error messages.

Type:

List[str]

add_error(message: str) None[source]

Add an error and mark as incompatible.

add_warning(message: str) None[source]

Add a warning message.

alignment_issues: List[str]
branches: Dict[int, BranchPredictionInfo]
common_samples: Set[int]
compatibility: CrossBranchCompatibility = 'not_applicable'
errors: List[str]
is_compatible: bool = True
property total_models: int

Total number of models across all branches.

warnings: List[str]
class nirs4all.controllers.models.stacking.CrossBranchValidator(prediction_store: Predictions, log_warnings: bool = True)[source]

Bases: object

Validates and supports cross-branch stacking.

This validator checks that stacking across multiple branches is feasible and provides utilities for aligning predictions from different branches.

prediction_store

Predictions storage.

log_warnings

Whether to emit Python warnings.

align_branch_features(branch_features: Dict[int, ndarray], branch_sample_indices: Dict[int, List[int]], target_sample_indices: List[int]) Tuple[ndarray, ndarray][source]

Align features from multiple branches to common sample order.

Combines features from different branches into a single feature matrix, aligning samples to a common order.

Parameters:
  • branch_features – Dict mapping branch_id to feature matrix.

  • branch_sample_indices – Dict mapping branch_id to sample indices.

  • target_sample_indices – Target sample order for output.

Returns:

Tuple of (aligned_features, valid_mask).

Raises:

BranchFeatureAlignmentError – If alignment fails.

get_cross_branch_sources(source_candidates: List[ModelCandidate], context: ExecutionContext) List[ModelCandidate][source]

Get source models from all branches for cross-branch stacking.

Filters and orders candidates for cross-branch stacking, ensuring proper handling of branch-specific models.

Parameters:
  • source_candidates – All candidate source models.

  • context – Execution context.

Returns:

Filtered and ordered list of candidates for cross-branch stacking.

validate_cross_branch_stacking(source_candidates: List[ModelCandidate], context: ExecutionContext, dataset: SpectroDataset | None = None) CrossBranchValidationResult[source]

Validate cross-branch stacking feasibility.

Checks that all branches have compatible samples and predictions can be properly aligned for stacking.

Parameters:
  • source_candidates – List of candidate source models.

  • context – Execution context.

  • dataset – Optional dataset for sample validation.

Returns:

CrossBranchValidationResult with compatibility info.

exception nirs4all.controllers.models.stacking.CrossPartitionStackingError(partition_a: str, partition_b: str, n_samples_a: int, n_samples_b: int)[source]

Bases: BranchingError

Raised when attempting cross-partition stacking with sample_partitioner.

Sample partitioner creates disjoint sample sets, making cross-partition stacking impossible without data leakage or sample misalignment.

partition_a

Name of first partition.

partition_b

Name of second partition.

n_samples_a

Number of samples in partition A.

n_samples_b

Number of samples in partition B.

exception nirs4all.controllers.models.stacking.DisjointSampleSetsError(source_model: str, expected_samples: int, found_samples: int, overlap_ratio: float)[source]

Bases: BranchingError

Raised when source models have disjoint sample sets.

This typically occurs with sample_partitioner where different branches have different samples, making OOF reconstruction impossible.

source_model

Name of the source model with disjoint samples.

expected_samples

Number of expected samples.

found_samples

Number of samples found in predictions.

overlap_ratio

Ratio of overlapping samples.

class nirs4all.controllers.models.stacking.FeatureNameGenerator(classification_info: ClassificationInfo, use_proba: bool = False, pattern: str = '{model_name}_pred')[source]

Bases: object

Generates meaningful feature names for meta-model.

Creates descriptive feature names that include model name and, for classification with probabilities, class information.

generate_names(source_model_names: List[str]) List[str][source]

Generate feature names for all source models.

Parameters:

source_model_names – List of source model names.

Returns:

List of feature column names.

get_feature_importance_mapping(source_model_names: List[str]) Dict[str, List[str]][source]

Get mapping from source models to their feature names.

Useful for feature importance analysis.

Parameters:

source_model_names – List of source model names.

Returns:

Dictionary mapping model name to list of feature names.

exception nirs4all.controllers.models.stacking.FeatureOrderMismatchError(expected_columns: List[str], actual_columns: List[str], meta_model_id: str)[source]

Bases: MetaModelPredictionError

Raised when feature columns don’t match expected order.

This occurs when the predictions from source models don’t align with the feature column order that was used during meta-model training.

expected_columns

Expected feature column names in order.

actual_columns

Actual feature column names found.

meta_model_id

The artifact ID of the meta-model.

class nirs4all.controllers.models.stacking.FoldAlignmentValidator(prediction_store: Predictions, config: ReconstructorConfig | None = None)[source]

Bases: object

Validates fold structure consistency across source models.

Ensures that all source models have compatible fold structures for proper out-of-fold reconstruction.

Checks performed: 1. All models have the same number of folds. 2. Fold indices are sequential (0, 1, 2, …, K-1). 3. No sample appears in multiple validation sets within a model. 4. Sample indices are consistent across folds.

prediction_store

Predictions storage for accessing fold data.

config

Reconstructor configuration.

validate(source_model_names: List[str], context: ExecutionContext, branch_id_override: int | None = -1) ValidationResult[source]

Validate fold alignment across source models.

Parameters:
  • source_model_names – List of source model names to validate.

  • context – Execution context with branch info.

  • branch_id_override – Optional branch_id override. If -1 (default), use context’s branch_id. If None, don’t filter by branch (for ALL_BRANCHES scope).

Returns:

ValidationResult with any errors or warnings.

exception nirs4all.controllers.models.stacking.FoldMismatchAcrossBranchesError(fold_structures: Dict[int, int], affected_models: List[str])[source]

Bases: BranchingError

Raised when source models from different branches have mismatched folds.

For stacking to work correctly, all source models must have compatible fold structures (same number of folds, same sample assignments per fold).

fold_structures

Dict mapping branch_id to fold count.

affected_models

List of affected model names.

exception nirs4all.controllers.models.stacking.GeneratorSyntaxStackingWarning(generator_type: str, n_variants: int)[source]

Bases: BranchingError

Raised as warning for generator syntax with stacking.

Generator syntax creates multiple model variants which may complicate stacking behavior. This is a warning, not a hard error.

generator_type

Type of generator used.

n_variants

Number of variants generated.

exception nirs4all.controllers.models.stacking.IncompatibleBranchSamplesError(branches: Dict[int, int], overlap_matrix: Dict[tuple, float] | None = None)[source]

Bases: CrossBranchStackingError

Raised when branches have incompatible sample sets for cross-branch stacking.

This occurs when attempting ALL_BRANCHES stacking with branches that have different sample indices (e.g., sample_partitioner branches).

branches

Dict mapping branch_id to sample counts.

overlap_matrix

Optional matrix showing sample overlap between branches.

exception nirs4all.controllers.models.stacking.IncompatibleBranchTypeError(branch_type: str, reason: str, suggestions: List[str] | None = None)[source]

Bases: BranchingError

Raised when stacking is attempted with incompatible branch type.

This occurs when the branch context is not suitable for stacking, such as attempting cross-partition stacking with sample_partitioner.

branch_type

Type of branching detected.

reason

Explanation of why stacking is incompatible.

suggestions

List of possible solutions.

exception nirs4all.controllers.models.stacking.InconsistentLevelError(expected_levels: List[int], found_levels: Dict[str, int], problematic_models: List[str])[source]

Bases: MultiLevelStackingError

Raised when source models have inconsistent stacking levels.

This occurs when a meta-model tries to use source models from incompatible levels, which could indicate a pipeline configuration issue.

expected_levels

Expected level(s) for source models.

found_levels

Actual levels found in source models.

problematic_models

Models with unexpected levels.

exception nirs4all.controllers.models.stacking.InvalidMetaModelArtifactError(artifact_id: str, validation_errors: List[str])[source]

Bases: MetaModelSerializationError

Raised when a meta-model artifact is invalid or corrupted.

This occurs when loading a meta-model artifact that doesn’t contain the required fields or has inconsistent data.

artifact_id

The artifact ID being loaded.

validation_errors

List of validation errors found.

class nirs4all.controllers.models.stacking.LevelValidationResult(is_valid: bool = True, detected_level: int = 1, source_levels: Dict[str, int]=<factory>, circular_dependencies: List[List[str]] = <factory>, warnings: List[str] = <factory>, errors: List[str] = <factory>)[source]

Bases: object

Result of multi-level stacking validation.

is_valid

Whether the validation passed.

Type:

bool

detected_level

The detected stacking level for the meta-model.

Type:

int

source_levels

Dict mapping source model names to their levels.

Type:

Dict[str, int]

circular_dependencies

List of detected circular dependencies.

Type:

List[List[str]]

warnings

List of warning messages.

Type:

List[str]

errors

List of error messages.

Type:

List[str]

add_error(message: str) None[source]

Add an error and mark as invalid.

add_warning(message: str) None[source]

Add a warning message.

circular_dependencies: List[List[str]]
detected_level: int = 1
errors: List[str]
is_valid: bool = True
source_levels: Dict[str, int]
warnings: List[str]
exception nirs4all.controllers.models.stacking.MaxStackingLevelExceededError(current_level: int, max_level: int, source_models: List[str] | None = None)[source]

Bases: MultiLevelStackingError

Raised when the maximum stacking level is exceeded.

This occurs when attempting to create more stacking levels than allowed, which could lead to overfitting or excessive computational cost.

current_level

The level that was attempted.

max_level

The maximum allowed level.

source_models

Source models that caused the level increase.

class nirs4all.controllers.models.stacking.MetaFeatureInfo(feature_names: ~typing.List[str], source_models: ~typing.List[str], feature_to_model: ~typing.Dict[str, str], classification_info: ~nirs4all.controllers.models.stacking.classification.ClassificationInfo, n_features_per_model: ~typing.Dict[str, int] = <factory>)[source]

Bases: object

Information about generated meta-features.

Used for tracking feature importance and providing interpretable results.

feature_names

List of all feature column names.

Type:

List[str]

source_models

List of source model names.

Type:

List[str]

feature_to_model

Mapping from feature name to source model.

Type:

Dict[str, str]

classification_info

Classification metadata.

Type:

nirs4all.controllers.models.stacking.classification.ClassificationInfo

n_features_per_model

Number of features from each model.

Type:

Dict[str, int]

aggregate_importance_by_model(feature_importances: Dict[str, float]) Dict[str, float][source]

Aggregate feature importances by source model.

Sums importance scores for all features from the same source model.

Parameters:

feature_importances – Mapping from feature name to importance score.

Returns:

Mapping from model name to aggregated importance.

classification_info: ClassificationInfo
feature_names: List[str]
feature_to_model: Dict[str, str]
get_model_for_feature(feature_name: str) str | None[source]

Get source model name for a feature.

Parameters:

feature_name – Feature column name.

Returns:

Source model name or None if not found.

n_features_per_model: Dict[str, int]
source_models: List[str]
class nirs4all.controllers.models.stacking.MetaModelArtifact(meta_model_type: str, meta_model_name: str, meta_learner_class: str, source_models: ~typing.List[~nirs4all.controllers.models.stacking.serialization.SourceModelReference], feature_columns: ~typing.List[str], stacking_config: ~typing.Dict[str, ~typing.Any], selector_config: ~typing.Dict[str, ~typing.Any] | None = None, branch_context: ~typing.Dict[str, ~typing.Any] | None = None, use_proba: bool = False, n_folds: int = 0, coverage_ratio: float = 1.0, artifact_id: str = '', training_timestamp: str = <factory>, task_type: str = 'regression', n_classes: int | None = None, feature_to_model_mapping: ~typing.Dict[str, str] | None = None)[source]

Bases: object

Complete artifact for meta-model persistence.

Contains all information needed to: - Reload the meta-model and its dependencies - Reconstruct feature columns in the correct order - Validate branch context during prediction - Apply the same stacking configuration

meta_model_type

Type identifier (“MetaModel”).

Type:

str

meta_model_name

Display name of the meta-model.

Type:

str

meta_learner_class

Class name of the meta-learner (e.g., “Ridge”).

Type:

str

source_models

Ordered list of source model references.

Type:

List[nirs4all.controllers.models.stacking.serialization.SourceModelReference]

feature_columns

Feature column names in order.

Type:

List[str]

stacking_config

Serialized stacking configuration.

Type:

Dict[str, Any]

selector_config

Configuration of the model selector used.

Type:

Dict[str, Any] | None

branch_context

Branch context during training.

Type:

Dict[str, Any] | None

use_proba

Whether probability features were used.

Type:

bool

n_folds

Number of cross-validation folds.

Type:

int

coverage_ratio

OOF coverage ratio achieved during training.

Type:

float

artifact_id

The artifact ID for the meta-model itself.

Type:

str

training_timestamp

ISO timestamp of training.

Type:

str

Example

>>> artifact = MetaModelArtifact(
...     meta_model_type="MetaModel",
...     meta_model_name="MetaModel_Ridge",
...     meta_learner_class="Ridge",
...     source_models=[ref1, ref2],
...     feature_columns=["PLS_pred", "RF_pred"],
...     stacking_config=stacking_config_dict,
...     branch_context={"branch_id": None},
...     use_proba=False,
...     n_folds=5,
...     coverage_ratio=1.0,
...     artifact_id="0001:5:all",
...     training_timestamp="2024-12-12T14:30:22Z"
... )
artifact_id: str = ''
branch_context: Dict[str, Any] | None = None
coverage_ratio: float = 1.0
feature_columns: List[str]
feature_to_model_mapping: Dict[str, str] | None = None
classmethod from_dict(data: Dict[str, Any]) MetaModelArtifact[source]

Create from dictionary.

classmethod from_json(json_str: str) MetaModelArtifact[source]

Deserialize from JSON string.

get_source_artifact_ids() List[str][source]

Get ordered list of source model artifact IDs.

Returns:

List of artifact IDs in feature column order.

get_source_by_index(index: int) SourceModelReference | None[source]

Get source model reference by feature index.

Parameters:

index – Feature column index.

Returns:

SourceModelReference or None if index out of range.

meta_learner_class: str
meta_model_name: str
meta_model_type: str
n_classes: int | None = None
n_folds: int = 0
selector_config: Dict[str, Any] | None = None
source_models: List[SourceModelReference]
stacking_config: Dict[str, Any]
task_type: str = 'regression'
to_dict() Dict[str, Any][source]

Convert to dictionary for JSON/YAML serialization.

to_json() str[source]

Serialize to JSON string.

training_timestamp: str
use_proba: bool = False
validate_feature_alignment() bool[source]

Validate that feature columns match source models.

Returns:

True if alignment is valid.

exception nirs4all.controllers.models.stacking.MetaModelError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: Exception

Base exception for meta-model errors.

All meta-model specific exceptions inherit from this class, allowing catch-all handling of meta-model issues.

message

Human-readable error description.

details

Optional dictionary with additional context.

exception nirs4all.controllers.models.stacking.MetaModelPredictionError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: MetaModelError

Base exception for meta-model prediction errors.

Raised when prediction mode fails for a meta-model.

exception nirs4all.controllers.models.stacking.MetaModelSerializationError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: MetaModelError

Base exception for meta-model serialization errors.

Raised when persistence or loading of meta-model artifacts fails.

class nirs4all.controllers.models.stacking.MetaModelSerializer[source]

Bases: object

Handles serialization and deserialization of meta-model artifacts.

Provides methods to: - Build MetaModelArtifact from training context - Convert to/from MetaModelConfig for artifact registry - Validate artifact completeness

Example

>>> serializer = MetaModelSerializer()
>>> artifact = serializer.build_artifact(
...     meta_operator=meta_model_op,
...     source_models=selected_sources,
...     reconstruction_result=result,
...     context=execution_context
... )
>>> config = serializer.to_meta_model_config(artifact)
build_artifact(meta_operator: MetaModel, source_models: List[ModelCandidate], reconstruction_result: ReconstructionResult | None = None, context: ExecutionContext | None = None, artifact_id: str = '') MetaModelArtifact[source]

Build MetaModelArtifact from training context.

Parameters:
  • meta_operator – The MetaModel operator being trained.

  • source_models – List of selected source model candidates.

  • reconstruction_result – Optional result from TrainingSetReconstructor.

  • context – Optional execution context for branch info.

  • artifact_id – The artifact ID for this meta-model.

Returns:

MetaModelArtifact ready for persistence.

to_meta_model_config(artifact: MetaModelArtifact) MetaModelConfig[source]

Convert MetaModelArtifact to MetaModelConfig for registry.

The ArtifactRegistry uses MetaModelConfig to track source model dependencies. This method creates the appropriate config.

Parameters:

artifact – MetaModelArtifact to convert.

Returns:

MetaModelConfig for artifact registry.

validate_artifact(artifact: MetaModelArtifact) List[str][source]

Validate artifact completeness and consistency.

Parameters:

artifact – MetaModelArtifact to validate.

Returns:

List of validation error messages (empty if valid).

exception nirs4all.controllers.models.stacking.MissingDependencyError(dependency_id: str, meta_model_id: str, dependency_name: str | None = None)[source]

Bases: MetaModelSerializationError

Raised when a dependency is not serialized.

This occurs when attempting to serialize a meta-model but one of its source model dependencies hasn’t been persisted yet.

dependency_id

The artifact ID of the missing dependency.

meta_model_id

The artifact ID of the meta-model.

dependency_name

Optional name of the missing dependency.

exception nirs4all.controllers.models.stacking.MissingSourceModelError(source_model_id: str, meta_model_id: str, all_missing: List[str] | None = None)[source]

Bases: MetaModelPredictionError

Raised when a source model binary is not found.

This occurs when trying to load a meta-model for prediction but one or more of its source model dependencies cannot be found in the artifact store.

source_model_id

The artifact ID of the missing source model.

meta_model_id

The artifact ID of the meta-model.

all_missing

List of all missing source model IDs (if multiple).

class nirs4all.controllers.models.stacking.ModelLevelInfo(model_name: str, level: int, is_meta_model: bool, source_models: List[str] = <factory>, step_idx: int = 0)[source]

Bases: object

Information about a model’s stacking level.

model_name

Name of the model.

Type:

str

level

Stacking level (0 for base models, 1+ for meta-models).

Type:

int

is_meta_model

Whether this is a meta-model.

Type:

bool

source_models

List of source model names (for meta-models).

Type:

List[str]

step_idx

Pipeline step index.

Type:

int

is_meta_model: bool
level: int
model_name: str
source_models: List[str]
step_idx: int = 0
exception nirs4all.controllers.models.stacking.MultiLevelStackingError(message: str, details: Dict[str, Any] | None = None)[source]

Bases: MetaModelError

Base exception for multi-level stacking errors.

class nirs4all.controllers.models.stacking.MultiLevelValidator(prediction_store: Predictions, max_level: int = 3, log_warnings: bool = True)[source]

Bases: object

Validates multi-level stacking configurations.

Ensures that stacking hierarchies are valid, detects circular dependencies, and computes appropriate stacking levels for meta-models.

prediction_store

Predictions storage for analyzing model metadata.

max_level

Maximum allowed stacking level.

log_warnings

Whether to emit Python warnings.

META_MODEL_PATTERNS = {'MetaModel', 'StackingClassifier', 'StackingRegressor'}
clear_cache() None[source]

Clear the level info cache.

detect_level(source_candidates: List[ModelCandidate], context: ExecutionContext) int[source]

Detect the appropriate stacking level based on source models.

Parameters:
  • source_candidates – List of candidate source models.

  • context – Execution context.

Returns:

Detected stacking level (1 if no meta-model sources, 2+ otherwise).

filter_by_level(candidates: List[ModelCandidate], context: ExecutionContext, max_source_level: int | None = None, exclude_meta_models: bool = False) List[ModelCandidate][source]

Filter source candidates by stacking level.

Parameters:
  • candidates – List of candidate source models.

  • context – Execution context.

  • max_source_level – Maximum allowed source level (None = no limit).

  • exclude_meta_models – If True, exclude all meta-models from sources.

Returns:

Filtered list of candidates.

get_all_levels(context: ExecutionContext) Dict[str, int][source]

Get levels for all models in the prediction store.

Parameters:

context – Execution context.

Returns:

Dict mapping model names to their stacking levels.

validate_sources(meta_model_name: str, source_candidates: List[ModelCandidate], context: ExecutionContext, allow_meta_sources: bool = True) LevelValidationResult[source]

Validate source models for a meta-model.

Checks for circular dependencies and computes the appropriate stacking level based on source model levels.

Parameters:
  • meta_model_name – Name of the meta-model being validated.

  • source_candidates – List of candidate source models.

  • context – Execution context.

  • allow_meta_sources – Whether to allow other meta-models as sources.

Returns:

LevelValidationResult with validation status and detected level.

exception nirs4all.controllers.models.stacking.NestedBranchStackingError(branch_depth: int, branch_path: List[int], reason: str)[source]

Bases: BranchingError

Raised when stacking is attempted with complex nested branching.

Complex nested branching scenarios may not be fully supported in meta-model stacking due to sample alignment challenges.

branch_depth

Depth of nesting.

branch_path

Full path of branch IDs.

reason

Explanation of the issue.

exception nirs4all.controllers.models.stacking.NoSourcePredictionsError(expected_sources: List[str], meta_model_id: str)[source]

Bases: MetaModelPredictionError

Raised when no source model predictions are available.

This occurs when the prediction store doesn’t contain any predictions from source models, making it impossible to construct meta-features.

expected_sources

List of expected source model names.

meta_model_id

The artifact ID of the meta-model.

class nirs4all.controllers.models.stacking.ReconstructionResult(X_train_meta: ndarray, X_test_meta: ndarray, y_train: ndarray, y_test: ndarray, feature_names: List[str], source_models: List[str], valid_train_mask: ndarray, valid_test_mask: ndarray, validation_result: ValidationResult, n_folds: int, coverage_ratio: float, meta_feature_info: Any | None = None, classification_info: Any | None = None)[source]

Bases: object

Container for reconstructed training set data.

Holds the meta-feature matrices for training and test sets, along with metadata about the reconstruction process.

X_train_meta

Training meta-features (n_train_samples, n_features).

Type:

numpy.ndarray

X_test_meta

Test meta-features (n_test_samples, n_features).

Type:

numpy.ndarray

y_train

Training targets (n_train_samples,).

Type:

numpy.ndarray

y_test

Test targets (n_test_samples,).

Type:

numpy.ndarray

feature_names

List of feature column names.

Type:

List[str]

source_models

List of source model names used.

Type:

List[str]

valid_train_mask

Boolean mask of valid training samples (after coverage handling).

Type:

numpy.ndarray

valid_test_mask

Boolean mask of valid test samples.

Type:

numpy.ndarray

validation_result

Validation result from fold alignment.

Type:

nirs4all.controllers.models.stacking.reconstructor.ValidationResult

n_folds

Number of folds detected.

Type:

int

coverage_ratio

Ratio of samples with complete predictions.

Type:

float

meta_feature_info

Optional MetaFeatureInfo for feature importance tracking.

Type:

Any | None

classification_info

Optional ClassificationInfo for task type metadata.

Type:

Any | None

Example

>>> result = reconstructor.reconstruct(dataset, context)
>>> X_train = result.X_train_meta[result.valid_train_mask]
>>> y_train = result.y_train[result.valid_train_mask]
>>> # For feature importance tracking
>>> if result.meta_feature_info:
...     model_importance = result.meta_feature_info.aggregate_importance_by_model(
...         feature_importances
...     )
X_test_meta: ndarray
X_train_meta: ndarray
classification_info: Any | None = None
coverage_ratio: float
feature_names: List[str]
meta_feature_info: Any | None = None
n_folds: int
source_models: List[str]
valid_test_mask: ndarray
valid_train_mask: ndarray
validation_result: ValidationResult
y_test: ndarray
y_train: ndarray
class nirs4all.controllers.models.stacking.ReconstructorConfig(validate_fold_alignment: bool = True, validate_sample_coverage: bool = True, log_warnings: bool = True, max_missing_fold_ratio: float = 0.0, allow_partial_sources: bool = False, feature_name_pattern: str = '{model_name}_pred', excluded_fold_ids: Set[str] = <factory>)[source]

Bases: object

Configuration for TrainingSetReconstructor.

Controls internal behavior of the reconstruction process, separate from the user-facing StackingConfig.

validate_fold_alignment

Whether to validate fold structure consistency.

Type:

bool

validate_sample_coverage

Whether to validate sample coverage.

Type:

bool

log_warnings

Whether to log warnings during reconstruction.

Type:

bool

max_missing_fold_ratio

Maximum ratio of missing folds before error (0.0-1.0).

Type:

float

allow_partial_sources

Allow reconstruction if some sources have partial data.

Type:

bool

feature_name_pattern

Pattern for generating feature column names. Supports: {model_name}, {fold_id}, {classname}, {step_idx}

Type:

str

excluded_fold_ids

Set of fold_id values to exclude (e.g., {‘avg’, ‘w_avg’}).

Type:

Set[str]

Example

>>> config = ReconstructorConfig(
...     validate_fold_alignment=True,
...     log_warnings=True,
...     feature_name_pattern="{model_name}_pred"
... )
__post_init__()[source]

Validate configuration after initialization.

allow_partial_sources: bool = False
excluded_fold_ids: Set[str]
feature_name_pattern: str = '{model_name}_pred'
log_warnings: bool = True
max_missing_fold_ratio: float = 0.0
validate_fold_alignment: bool = True
validate_sample_coverage: bool = True
class nirs4all.controllers.models.stacking.SourceModelReference(model_name: str, model_classname: str, step_idx: int, artifact_id: str, feature_index: int, fold_id: str | None = None, branch_id: int | None = None, branch_name: str | None = None, branch_path: List[int] | None = None, val_score: float | None = None, metric: str | None = None)[source]

Bases: object

Reference to a source model used in stacking.

Stores all information needed to locate and validate a source model during prediction mode.

model_name

Display name of the model (e.g., “PLSRegression”).

Type:

str

model_classname

Full class name (e.g., “sklearn.cross_decomposition.PLSRegression”).

Type:

str

step_idx

Pipeline step index where the model was trained.

Type:

int

artifact_id

Unique artifact ID for loading the model binary.

Type:

str

feature_index

Column index in meta-features matrix.

Type:

int

fold_id

Optional fold ID if fold-specific reference.

Type:

str | None

branch_id

Branch ID where model was trained.

Type:

int | None

branch_name

Branch name where model was trained.

Type:

str | None

branch_path

Full branch path for nested branches.

Type:

List[int] | None

val_score

Validation score for weighted averaging.

Type:

float | None

metric

Metric used for scoring (e.g., “r2”, “rmse”).

Type:

str | None

Example

>>> ref = SourceModelReference(
...     model_name="PLSRegression",
...     model_classname="sklearn.cross_decomposition.PLSRegression",
...     step_idx=3,
...     artifact_id="0001:3:all",
...     feature_index=0,
...     branch_id=None,
...     val_score=0.92,
...     metric="r2"
... )
artifact_id: str
branch_id: int | None = None
branch_name: str | None = None
branch_path: List[int] | None = None
feature_index: int
fold_id: str | None = None
classmethod from_dict(data: Dict[str, Any]) SourceModelReference[source]

Create from dictionary.

metric: str | None = None
model_classname: str
model_name: str
step_idx: int
to_dict() Dict[str, Any][source]

Convert to dictionary for JSON/YAML serialization.

val_score: float | None = None
exception nirs4all.controllers.models.stacking.SourcePredictionError(source_model_id: str, source_model_name: str, original_error: Exception | None = None)[source]

Bases: MetaModelPredictionError

Raised when a source model fails to produce predictions.

This occurs when a source model is loaded successfully but fails during prediction, preventing the meta-model from constructing its input features.

source_model_id

The artifact ID of the failing source model.

source_model_name

The name of the failing source model.

original_error

The underlying exception that caused the failure.

class nirs4all.controllers.models.stacking.StackingCompatibility(value)[source]

Bases: Enum

Compatibility level for stacking with a branch type.

COMPATIBLE = 'compatible'
COMPATIBLE_WITH_WARNINGS = 'compatible_with_warnings'
NOT_SUPPORTED = 'not_supported'
WITHIN_PARTITION_ONLY = 'within_partition_only'
class nirs4all.controllers.models.stacking.StackingTaskType(value)[source]

Bases: Enum

Task type for stacking.

REGRESSION

Regression task using y_pred as features.

BINARY_CLASSIFICATION

Binary classification (2 classes).

MULTICLASS_CLASSIFICATION

Multi-class classification (>2 classes).

UNKNOWN

Could not determine task type.

BINARY_CLASSIFICATION = 'binary_classification'
MULTICLASS_CLASSIFICATION = 'multiclass_classification'
REGRESSION = 'regression'
UNKNOWN = 'unknown'
property is_classification: bool

Check if this is a classification task type.

property n_classes: int | None

Return expected number of classes or None for regression.

class nirs4all.controllers.models.stacking.TaskTypeDetector(prediction_store: Predictions)[source]

Bases: object

Detects task type from prediction metadata.

Uses prediction store metadata and y_proba presence to determine whether the stacking involves regression or classification.

detect(source_model_names: List[str], context: ExecutionContext) ClassificationInfo[source]

Detect task type from source model predictions.

Examines predictions from source models to determine task type and gather classification metadata.

Parameters:
  • source_model_names – List of source model names to examine.

  • context – Execution context with branch info.

Returns:

ClassificationInfo with detected task type and metadata.

class nirs4all.controllers.models.stacking.TrainingSetReconstructor(prediction_store: Predictions, source_model_names: List[str], stacking_config: StackingConfig | None = None, reconstructor_config: ReconstructorConfig | None = None, source_model_branch_map: Dict[str, int | None] | None = None)[source]

Bases: object

Reconstructs meta-model training set from out-of-fold predictions.

This is the core class for Phase 2 of the meta-model stacking implementation. It handles the critical task of collecting OOF predictions from source models and constructing feature matrices for the meta-learner.

The fundamental invariant is: No sample sees predictions from a model trained on that sample. This prevents data leakage.

prediction_store

Predictions storage for accessing source predictions.

source_model_names

List of source model names to use.

stacking_config

Configuration for coverage and aggregation strategies.

reconstructor_config

Internal configuration for reconstruction.

fold_validator

Validator for fold alignment.

Example

>>> reconstructor = TrainingSetReconstructor(
...     prediction_store=predictions,
...     source_model_names=["PLS", "RF", "XGB"],
...     stacking_config=StackingConfig(
...         coverage_strategy=CoverageStrategy.DROP_INCOMPLETE,
...         test_aggregation=TestAggregation.MEAN
...     )
... )
>>> result = reconstructor.reconstruct(dataset, context)
>>> print(f"Coverage: {result.coverage_ratio:.1%}")
>>> print(f"Features: {result.feature_names}")
reconstruct(dataset: SpectroDataset, context: ExecutionContext, y_train: ndarray | None = None, y_test: ndarray | None = None, use_proba: bool = False) ReconstructionResult[source]

Reconstruct meta-model training and test sets from predictions.

Collects out-of-fold predictions for training samples and aggregated predictions for test samples.

Phase 5 Enhancement: Supports classification tasks with probability features for binary and multiclass classification.

Parameters:
  • dataset – SpectroDataset for sample indices.

  • context – Execution context with partition and branch info.

  • y_train – Optional pre-computed training targets.

  • y_test – Optional pre-computed test targets.

  • use_proba – If True, use probability predictions for classification.

Returns:

ReconstructionResult containing meta-feature matrices and metadata.

Raises:

ValueError – If no source models found or critical validation fails.

validate_branch_compatibility(context: ExecutionContext) ValidationResult[source]

Validate branch compatibility for stacking.

Checks that the current branch context is compatible with stacking based on the configured BranchScope.

Parameters:

context – Execution context with branch info.

Returns:

ValidationResult with any errors or warnings.

class nirs4all.controllers.models.stacking.ValidationResult(errors: List[ValidationError] = <factory>, warnings: List[ValidationWarning] = <factory>)[source]

Bases: object

Container for validation errors and warnings.

Accumulates validation issues during fold alignment and coverage checks.

errors

List of validation errors (critical issues).

Type:

List[nirs4all.controllers.models.stacking.reconstructor.ValidationError]

warnings

List of validation warnings (non-critical issues).

Type:

List[nirs4all.controllers.models.stacking.reconstructor.ValidationWarning]

is_valid

True if no errors (warnings are allowed).

Example

>>> result = ValidationResult()
>>> result.add_error("FOLD_MISMATCH", "Folds don't align")
>>> result.add_warning("PARTIAL_COVERAGE", "80% coverage")
>>> if not result.is_valid:
...     raise ValueError(result.format_errors())
add_error(code: str, message: str, details: Dict[str, Any] | None = None) None[source]

Add a validation error.

add_warning(code: str, message: str, details: Dict[str, Any] | None = None) None[source]

Add a validation warning.

errors: List[ValidationError]
format_errors() str[source]

Format all errors as a human-readable string.

format_warnings() str[source]

Format all warnings as a human-readable string.

property is_valid: bool

Check if validation passed (no errors).

merge(other: ValidationResult) None[source]

Merge another validation result into this one.

warnings: List[ValidationWarning]
nirs4all.controllers.models.stacking.build_meta_feature_info(source_model_names: List[str], classification_info: ClassificationInfo, use_proba: bool = False, name_pattern: str = '{model_name}_pred') MetaFeatureInfo[source]

Build MetaFeatureInfo from source models and classification info.

Parameters:
  • source_model_names – List of source model names.

  • classification_info – Classification metadata.

  • use_proba – Whether probability features are used.

  • name_pattern – Pattern for feature names.

Returns:

MetaFeatureInfo with all mappings populated.

nirs4all.controllers.models.stacking.detect_branch_type(context: ExecutionContext) BranchType[source]

Detect the type of branching from execution context.

Convenience function for quick branch type detection.

Parameters:

context – Execution context with branch info.

Returns:

Detected BranchType enum value.

nirs4all.controllers.models.stacking.detect_stacking_level(prediction_store: Predictions, source_candidates: List[ModelCandidate], context: ExecutionContext) int[source]

Convenience function for detecting stacking level.

Parameters:
  • prediction_store – Predictions storage.

  • source_candidates – List of candidate source models.

  • context – Execution context.

Returns:

Detected stacking level.

nirs4all.controllers.models.stacking.get_disjoint_branch_info(context: ExecutionContext) Dict[str, Any] | None[source]

Get information about the disjoint branch if applicable.

Parameters:

context – Execution context with branch info.

Returns:

Dict with partition info, or None if not a disjoint branch. Keys may include:

  • partition_type: “metadata” or “sample”

  • column: Metadata column name (for metadata partitioner)

  • partition_value: Value(s) for this partition

  • sample_indices: List of sample indices in this partition

  • n_samples: Number of samples in this partition

nirs4all.controllers.models.stacking.is_disjoint_branch(context: ExecutionContext) bool[source]

Check if the current branch context represents disjoint sample branching.

Disjoint branches partition samples into non-overlapping sets, where each sample exists in exactly ONE branch. This is in contrast to copy branches where all branches see all samples.

Disjoint branch types:
  • METADATA_PARTITIONER: Branches by metadata column value

  • SAMPLE_PARTITIONER: Branches by outlier status

Copy branch types:
  • PREPROCESSING: All branches see all samples

  • GENERATOR: All branches see all samples (model variants)

Parameters:

context – Execution context with branch info.

Returns:

True if current context represents a disjoint sample branch.

nirs4all.controllers.models.stacking.is_stacking_compatible(context: ExecutionContext) bool[source]

Quick check if stacking is compatible with current context.

Parameters:

context – Execution context.

Returns:

True if stacking is likely compatible.

nirs4all.controllers.models.stacking.stacking_config_from_dict(data: Dict[str, Any]) StackingConfig[source]

Create StackingConfig from dictionary.

Parameters:

data – Dictionary with config values.

Returns:

StackingConfig instance.

nirs4all.controllers.models.stacking.stacking_config_to_dict(config: StackingConfig) Dict[str, Any][source]

Convert StackingConfig to serializable dictionary.

Parameters:

config – StackingConfig instance.

Returns:

Dictionary with string enum values.

nirs4all.controllers.models.stacking.validate_all_branches_scope(prediction_store: Predictions, source_candidates: List[ModelCandidate], context: ExecutionContext) CrossBranchValidationResult[source]

Convenience function for validating BranchScope.ALL_BRANCHES.

Parameters:
  • prediction_store – Predictions storage.

  • source_candidates – List of candidate source models.

  • context – Execution context.

Returns:

CrossBranchValidationResult with compatibility info.

nirs4all.controllers.models.stacking.validate_multi_level_stacking(prediction_store: Predictions, meta_model_name: str, source_candidates: List[ModelCandidate], context: ExecutionContext, max_level: int = 3, allow_meta_sources: bool = True) LevelValidationResult[source]

Convenience function for validating multi-level stacking.

Parameters:
  • prediction_store – Predictions storage.

  • meta_model_name – Name of the meta-model.

  • source_candidates – List of candidate source models.

  • context – Execution context.

  • max_level – Maximum allowed stacking level.

  • allow_meta_sources – Whether to allow meta-model sources.

Returns:

LevelValidationResult with validation status.