Skip to content

Preprocessing and model-selection API

CapacityNormalizer

Min-max transformer with optional cost-criterion reversal. It is scikit-learn compatible and preserves feature names through get_feature_names_out().

CapacityNormalizer

CapacityNormalizer(
    feature_range: tuple[float, float] = (0.0, 1.0),
    cost_features: Sequence[int | str] | None = None,
    clip: bool = True,
)

Bases: TransformerMixin, BaseEstimator

Scale commensurable capacity inputs and orient cost features.

Each feature is independently min-max scaled. Selected cost criteria are then reversed so that larger transformed values consistently represent more desirable outcomes, as required by monotone Choquet models.

Parameters

feature_range : tuple of float, default=(0.0, 1.0) Desired lower and upper bounds of transformed features. cost_features : sequence of int or str, optional Indices or DataFrame column names whose direction must be reversed. clip : bool, default=True Whether values outside the fitted range are clipped during transform.

Attributes

data_min_ : ndarray of shape (n_features,) Per-feature minima observed during fitting. data_max_ : ndarray of shape (n_features,) Per-feature maxima observed during fitting. scale_ : ndarray of shape (n_features,) Multiplicative scaling factors. cost_features_ : ndarray of int Resolved indices of reversed features. n_features_in_ : int Number of features seen during :meth:fit. feature_names_in_ : ndarray of str Feature names seen during fitting when X provides string columns.

Source code in src/capacities_ml_fin/ml/preprocessing/normalization.py
def __init__(
    self,
    feature_range: tuple[float, float] = (0.0, 1.0),
    cost_features: Sequence[int | str] | None = None,
    clip: bool = True,
) -> None:
    self.feature_range = feature_range
    self.cost_features = cost_features
    self.clip = clip

fit

fit(X: ArrayLike, y: Any = None) -> 'CapacityNormalizer'

Learn feature ranges and resolve cost-feature names.

Source code in src/capacities_ml_fin/ml/preprocessing/normalization.py
def fit(self, X: ArrayLike, y: Any = None) -> "CapacityNormalizer":
    """Learn feature ranges and resolve cost-feature names."""
    matrix = check_array(X, dtype=float, ensure_2d=True, ensure_min_samples=1)
    lower, upper = self._validate_feature_range()
    if not isinstance(self.clip, (bool, np.bool_)):
        raise TypeError("clip must be a boolean.")

    self.n_features_in_ = matrix.shape[1]
    columns = getattr(X, "columns", None)
    if columns is not None and all(isinstance(column, str) for column in columns):
        self.feature_names_in_ = np.asarray(columns, dtype=object)
    self.cost_features_ = self._resolve_cost_features(columns)
    self.data_min_ = np.min(matrix, axis=0)
    self.data_max_ = np.max(matrix, axis=0)
    self.data_range_ = self.data_max_ - self.data_min_
    safe_range = np.where(self.data_range_ == 0.0, 1.0, self.data_range_)
    self.scale_ = (upper - lower) / safe_range
    self.min_ = lower - self.data_min_ * self.scale_
    self.feature_range_ = (lower, upper)
    return self

transform

transform(X: ArrayLike) -> ndarray

Transform features into the configured capacity range.

Source code in src/capacities_ml_fin/ml/preprocessing/normalization.py
def transform(self, X: ArrayLike) -> np.ndarray:
    """Transform features into the configured capacity range."""
    check_is_fitted(self, ["data_min_", "scale_", "cost_features_"])
    matrix = self._validate_input(X)
    lower, upper = self.feature_range_
    transformed = matrix * self.scale_ + self.min_
    if self.cost_features_.size:
        transformed[:, self.cost_features_] = (
            lower + upper - transformed[:, self.cost_features_]
        )
    if self.clip:
        np.clip(transformed, lower, upper, out=transformed)
    return transformed

inverse_transform

inverse_transform(X: ArrayLike) -> ndarray

Undo the normalization and cost-feature reversal.

Source code in src/capacities_ml_fin/ml/preprocessing/normalization.py
def inverse_transform(self, X: ArrayLike) -> np.ndarray:
    """Undo the normalization and cost-feature reversal."""
    check_is_fitted(self, ["data_min_", "scale_", "cost_features_"])
    transformed = self._validate_input(X)
    lower, upper = self.feature_range_
    restored = transformed.copy()
    if self.clip:
        np.clip(restored, lower, upper, out=restored)
    if self.cost_features_.size:
        restored[:, self.cost_features_] = (
            lower + upper - restored[:, self.cost_features_]
        )
    safe_scale = np.where(self.scale_ == 0.0, 1.0, self.scale_)
    return (restored - self.min_) / safe_scale

get_feature_names_out

get_feature_names_out(
    input_features: ArrayLike | None = None,
) -> ndarray

Return feature names unchanged.

Source code in src/capacities_ml_fin/ml/preprocessing/normalization.py
def get_feature_names_out(
    self,
    input_features: ArrayLike | None = None,
) -> np.ndarray:
    """Return feature names unchanged."""
    check_is_fitted(self, ["n_features_in_"])
    if input_features is not None:
        features = np.asarray(input_features, dtype=object)
        if features.shape != (self.n_features_in_,):
            raise ValueError("input_features has an incompatible size.")
        return features
    if hasattr(self, "feature_names_in_"):
        return self.feature_names_in_.copy()
    return np.asarray([f"x{i}" for i in range(self.n_features_in_)], dtype=object)

Capacity sparsity grids

capacity_sparsity_grid

capacity_sparsity_grid

capacity_sparsity_grid(
    orders: Iterable[int],
    *,
    shapes: Iterable[CapacityShape] = (GENERAL,)
) -> list[CapacitySparsity]

Build sparsity candidates for capacity model selection.

Source code in src/capacities_ml_fin/ml/model_selection/grids.py
def capacity_sparsity_grid(
    orders: Iterable[int],
    *,
    shapes: Iterable[CapacityShape] = (CapacityShape.GENERAL,),
) -> list[CapacitySparsity]:
    """Build sparsity candidates for capacity model selection."""
    order_values = tuple(orders)
    shape_values = tuple(shapes)
    if not order_values:
        raise ValueError("orders must contain at least one value.")
    if not shape_values:
        raise ValueError("shapes must contain at least one value.")
    if any(not isinstance(order, int) or order < 1 for order in order_values):
        raise ValueError("orders must contain positive integers.")
    if any(not isinstance(shape, CapacityShape) for shape in shape_values):
        raise TypeError("shapes must contain CapacityShape enum members.")
    if any(
        shape is not CapacityShape.GENERAL and order != 2
        for shape in shape_values
        for order in order_values
    ):
        raise ValueError(
            "Convex and concave capacity shapes are currently available only "
            "for order=2."
        )
    return [
        KAdditivity(order=order, shape=shape)
        for order in order_values
        for shape in shape_values
    ]

capacity_shape_grid

capacity_shape_grid

capacity_shape_grid(
    *,
    order: int = 2,
    shapes: Iterable[CapacityShape] = (
        GENERAL,
        CONVEX,
        CONCAVE,
    )
) -> list[CapacitySparsity]

Build candidates that compare capacity shapes at one order.

Source code in src/capacities_ml_fin/ml/model_selection/grids.py
def capacity_shape_grid(
    *,
    order: int = 2,
    shapes: Iterable[CapacityShape] = (
        CapacityShape.GENERAL,
        CapacityShape.CONVEX,
        CapacityShape.CONCAVE,
    ),
) -> list[CapacitySparsity]:
    """Build candidates that compare capacity shapes at one order."""
    return capacity_sparsity_grid((order,), shapes=shapes)

interaction_order_grid

interaction_order_grid

interaction_order_grid(
    orders: Iterable[int], *, shape: CapacityShape = GENERAL
) -> list[CapacitySparsity]

Build candidates that compare the maximum interaction order.

Source code in src/capacities_ml_fin/ml/model_selection/grids.py
def interaction_order_grid(
    orders: Iterable[int],
    *,
    shape: CapacityShape = CapacityShape.GENERAL,
) -> list[CapacitySparsity]:
    """Build candidates that compare the maximum interaction order."""
    return capacity_sparsity_grid(orders, shapes=(shape,))

pairwise_interaction_grid

pairwise_interaction_grid

pairwise_interaction_grid(
    orders: Iterable[int],
    *,
    pairs: tuple[tuple[int, int], ...] | None = None,
    target: float = 0.0,
    shape: CapacityShape = GENERAL
) -> list[CapacitySparsity]

Build candidates with selected pairwise interactions fixed.

Source code in src/capacities_ml_fin/ml/model_selection/grids.py
def pairwise_interaction_grid(
    orders: Iterable[int],
    *,
    pairs: tuple[tuple[int, int], ...] | None = None,
    target: float = 0.0,
    shape: CapacityShape = CapacityShape.GENERAL,
) -> list[CapacitySparsity]:
    """Build candidates with selected pairwise interactions fixed."""
    order_values = tuple(orders)
    if any(order < 2 for order in order_values):
        raise ValueError("Pairwise interaction grids require order >= 2.")
    if shape is not CapacityShape.GENERAL and any(order != 2 for order in order_values):
        raise ValueError(
            "Convex and concave capacity shapes are currently available only "
            "for order=2."
        )
    return [
        PairwiseInteractionSparsity(
            order=order,
            pairs=pairs,
            target=target,
            shape=shape,
        )
        for order in order_values
    ]

capacity_parameter_grid

Convenience wrapper returning a dictionary ready for scikit-learn GridSearchCV.

capacity_parameter_grid

capacity_parameter_grid(
    *,
    parameter_name: str = "sparsity",
    orders: Iterable[int] = (1, 2),
    shapes: Iterable[CapacityShape] = (GENERAL,)
) -> dict[str, list[CapacitySparsity]]

Return a parameter grid ready for GridSearchCV.

Source code in src/capacities_ml_fin/ml/model_selection/grids.py
def capacity_parameter_grid(
    *,
    parameter_name: str = "sparsity",
    orders: Iterable[int] = (1, 2),
    shapes: Iterable[CapacityShape] = (CapacityShape.GENERAL,),
) -> dict[str, list[CapacitySparsity]]:
    """Return a parameter grid ready for ``GridSearchCV``."""
    if not parameter_name:
        raise ValueError("parameter_name cannot be empty.")
    return {
        parameter_name: capacity_sparsity_grid(orders, shapes=shapes),
    }