calibrated_explanations.core.validation¶
Validation helpers shared across the core package.
These utilities centralize defensive argument checks while preserving existing behavior, ensuring future refactors can rely on a consistent error vocabulary.
ADR-002 compliance: Validation functions use the exception taxonomy (ValidationError, DataShapeError, NotFittedError, ConfigurationError, etc.) and accept optional details payloads.
- calibrated_explanations.core.validation.normalize_mode(value: Any, *, param: str = 'mode') str[source]¶
Return a canonical explainer mode literal.
- Parameters:
value (Any) – Candidate mode value.
param (str, default="mode") – Parameter name used in the structured error payload.
- Returns:
Lower-case canonical mode (
"classification"or"regression").- Return type:
str
- Raises:
ValidationError – If
valueis not a supported mode string.
- calibrated_explanations.core.validation.validate_bool_parameter(value: Any, *, param: str) bool[source]¶
Require a real boolean instead of truthy/falsy coercion.
- calibrated_explanations.core.validation.validate_explainer_init_kwargs(kwargs: dict[str, Any], *, mode: Any, n_features: int) tuple[str, dict[str, Any]][source]¶
Validate constructor/calibration kwargs at the public boundary.
- calibrated_explanations.core.validation.validate_features_to_ignore(value: Any, *, n_features: int, param: str = 'features_to_ignore') list[int][source]¶
Validate a feature-index ignore list against the calibrated feature count.
- calibrated_explanations.core.validation.validate_low_high_percentiles(value: Any, *, param: str = 'low_high_percentiles') tuple[float, float][source]¶
Validate regression interval percentile bounds.
- calibrated_explanations.core.validation.validate_inputs(x: Any, y: Any | None = None, task: Literal['auto', 'classification', 'regression'] = 'auto', allow_nan: bool = False, require_y: bool = False, n_features: int | None = None, class_labels: Any | None = None, check_finite: bool = True) None[source]¶
Validate input features and target for downstream operations.
This function provides the primary validation entry point per ADR-002, accepting feature matrix x and optional target y with comprehensive shape, dtype, and value checks.
- Parameters:
x (array-like) – Feature matrix of shape (n_samples, n_features). Can be a NumPy array, pandas DataFrame, or similar.
y (array-like, optional) – Target vector of shape (n_samples,). If provided, length must match x. Default is None.
task ({"auto", "classification", "regression"}, default="auto") – Task type. When “auto”, inferred from model capabilities or y dtype.
allow_nan (bool, default=False) – If False, raises ValidationError when x or y contain NaN values.
require_y (bool, default=False) – If True, raises ValidationError when y is None.
n_features (int, optional) – Expected number of features in x. If provided and mismatch occurs, raises DataShapeError.
class_labels (array-like, optional) – Class labels for classification tasks. Stored for later use.
check_finite (bool, default=True) – If True, checks that x and y contain only finite values (except NaN when allow_nan=True).
- Raises:
ValidationError – When y is required but None, or when values contain NaN/inf unexpectedly.
DataShapeError – When x is not 2D, feature count mismatches, or y length mismatches.
Examples
>>> from calibrated_explanations.core.validation import validate_inputs >>> import numpy as np >>> x = np.array([[1.0, 2.0], [3.0, 4.0]]) >>> y = np.array([0, 1]) >>> validate_inputs(x, y, task="classification", require_y=True, n_features=2) # Passes silently if valid
- calibrated_explanations.core.validation.validate_not_none(value: Any, name: str) None[source]¶
Raise
ValidationErrorwhenvalueisNone.
- calibrated_explanations.core.validation.validate_type(value: Any, expected_type: type, name: str) None[source]¶
Ensure that
valueis an instance ofexpected_type.
- calibrated_explanations.core.validation.validate_non_empty(value: Any, name: str) None[source]¶
Ensure that length-aware inputs are not empty.
- calibrated_explanations.core.validation.validate_inputs_matrix(x: Any, y: Any | None = None, *, task: Literal['auto', 'classification', 'regression'] = 'auto', allow_nan: bool = False, require_y: bool = False, n_features: int | None = None, check_finite: bool = True) None[source]¶
Validate a feature/target matrix pair for downstream operations.
Ensure
xis 2D and matches the expected feature count when provided.Confirm that
yhas the same number of samples when supplied.Guard against NaN or infinite values unless explicitly allowed.
Reject empty calibration-style inputs when
require_y=Trueso public boundaries fail with CE exceptions before deeper indexing code runs.
- calibrated_explanations.core.validation.validate_model(model: Any) None[source]¶
Validate minimal model protocol requirements.
- calibrated_explanations.core.validation.validate_sample_percentiles(value: Any, *, param: str = 'sample_percentiles') list[float][source]¶
Validate percentile checkpoints used by explanation summaries.
- calibrated_explanations.core.validation.validate_seed_parameter(value: Any, *, param: str = 'seed') int[source]¶
Require an integer random seed.
- calibrated_explanations.core.validation.validate_fast_tuning_parameters(*, noise_type: Any, scale_factor: Any, severity: Any) tuple[str, int, float][source]¶
Validate FAST perturbation controls before plugin construction.
- calibrated_explanations.core.validation.validate_fit_state(obj: Any, *, require: bool = True) None[source]¶
Validate fit state flags before executing stateful operations.
- calibrated_explanations.core.validation.infer_task(x: Any = None, y: Any = None, model: Any = None) Literal['classification', 'regression'][source]¶
Infer the task type using model capabilities or target dtype.
Priority is given to model capabilities (
predict_probaimplies classification). When a model is unavailable, heuristics based on the target dtype are used. Regression is the safe fallback.
- calibrated_explanations.core.validation.validate(condition: bool, exc_cls: Type[CalibratedError], message: str, *, details: dict[str, Any] | None = None) None[source]¶
Conditional validation helper for common patterns.
Raises an exception when a condition is False, enabling concise guard clauses.
- Parameters:
condition (bool) – Condition to check. If False, raises exc_cls.
exc_cls (Type[CalibratedError]) – Exception class to raise when condition is False.
message (str) – Error message.
details (dict, optional) – Structured error details to attach to the exception.
- Raises:
exc_cls – If condition is False.
Examples
>>> from calibrated_explanations.core.validation import validate >>> from calibrated_explanations.utils.exceptions import ValidationError >>> validate(len(x) > 0, ValidationError, "x must not be empty", details={"param": "x"})