Skip to content

Machine-learning model API

ChoquetRegressor

Least-squares scikit-learn regressor with a learned capacity and separate intercept.

ChoquetRegressor

ChoquetRegressor(
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    fit_intercept: bool = True,
)

Bases: RegressorMixin, BaseEstimator

Least-squares regression with a learned Choquet integral.

The estimator learns a normalized monotone capacity together with an unconstrained intercept. It follows the scikit-learn estimator contract and can be used in pipelines, cross-validation, grid search, pickle, and joblib.

Parameters

sparsity : CapacitySparsity, optional Capacity parameterization. None fits a full explicit capacity. solver : {"scipy", "cvxpy", "pymoo"} or Solver, default="scipy" Optimization backend. solver_options : dict, optional Keyword arguments forwarded to the selected backend. penalty : callable or penalty object, optional Regularization term added to the squared-error objective. fit_intercept : bool, default=True Whether to learn an unconstrained additive intercept. Set to False when the Choquet integral itself must be the complete prediction, as in model aggregation.

Attributes

capacity_ : BaseCapacity Fitted immutable capacity. intercept_ : float Fitted additive intercept. universe_ : VariableUniverse Feature universe inferred from X. problem_ : Problem Solver-independent optimization problem used during fitting. result_ : OptimizationResult Numerical optimizer result and diagnostics. n_features_in_ : int Number of input features seen during :meth:fit. feature_names_in_ : ndarray of str Input feature names when X provides string column names.

Notes

Inputs should be made commensurable before fitting, typically with :class:~capacities_ml_fin.ml.preprocessing.CapacityNormalizer.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def __init__(
    self,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    fit_intercept: bool = True,
) -> None:
    self.sparsity = sparsity
    self.solver = solver
    self.solver_options = solver_options
    self.penalty = penalty
    self.fit_intercept = fit_intercept

fit

fit(X: ArrayLike, y: ArrayLike) -> 'ChoquetRegressor'

Fit the capacity and the regression intercept.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def fit(self, X: ArrayLike, y: ArrayLike) -> "ChoquetRegressor":
    """Fit the capacity and the regression intercept."""
    matrix, target = validate_data(
        self,
        X,
        y,
        dtype=float,
        ensure_2d=True,
        ensure_min_samples=1,
    )
    self.universe_ = fitted_universe(self)
    target = np.asarray(target, dtype=float).reshape(-1)
    if not np.all(np.isfinite(target)):
        raise ValueError("y must contain only finite values.")
    if not isinstance(self.fit_intercept, (bool, np.bool_)):
        raise TypeError("fit_intercept must be boolean.")
    self.solver_ = resolve_solver(self.solver)

    sparsity = self.sparsity if self.sparsity is not None else FullCapacity()
    compilation = sparsity.compile(self.universe_.n_elements)
    design = capacity_design(
        matrix,
        compilation.bundle.parameter_masks,
        compilation.bundle.representation,
    )
    capacity_initial = compilation.initial_parameters
    intercept_initial = float(np.mean(target - design @ capacity_initial))
    blocks = [ParameterBlock("capacity", compilation.bundle.n_parameters)]
    if self.fit_intercept:
        blocks.append(ParameterBlock("intercept", 1))
    layout = ParameterLayout(*blocks)
    capacity_slice = layout.slice("capacity")
    intercept_slice = layout.slice("intercept") if self.fit_intercept else None

    predictor = partial(
        regression_predictor,
        design=design,
        capacity_slice=capacity_slice,
        intercept_slice=intercept_slice,
    )

    objective = SquaredErrorObjective(
        target=target,
        predictor=predictor,
        penalty=self.penalty,
        symbolic_predictor=predictor,
    )
    problem = Problem.from_capacity(
        universe=self.universe_,
        objective=objective,
        sparsity=sparsity,
        parameter_layout=layout,
        initial_parameters=(
            np.concatenate([capacity_initial, np.array([intercept_initial])])
            if self.fit_intercept
            else capacity_initial
        ),
        name="choquet_regression",
    )
    options = {} if self.solver_options is None else dict(self.solver_options)
    result = Optimizer(solver=self.solver_, **options).solve(problem)
    if not result.success:
        raise RuntimeError(
            f"Choquet regression optimization failed: {result.message}"
        )

    self.problem_ = problem
    self.result_ = result
    self.capacity_ = problem.decode_result(result)
    self.intercept_ = (
        float(result.parameters[intercept_slice][0])
        if intercept_slice is not None
        else 0.0
    )
    self.sparsity_ = sparsity
    return self

predict

predict(X: ArrayLike) -> ndarray

Predict continuous responses.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def predict(self, X: ArrayLike) -> np.ndarray:
    """Predict continuous responses."""
    check_is_fitted(self, ["capacity_", "intercept_"])
    matrix = validate_data(self, X, reset=False, dtype=float)
    return batch_choquet_integral(matrix, self.capacity_) + self.intercept_

fit_predict

fit_predict(X: ArrayLike, y: ArrayLike) -> ndarray

Fit the model and return predictions for X.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def fit_predict(self, X: ArrayLike, y: ArrayLike) -> np.ndarray:
    """Fit the model and return predictions for ``X``."""
    return self.fit(X, y).predict(X)

get_feature_names_out

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

Return the feature names used by the fitted estimator.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def get_feature_names_out(
    self, input_features: ArrayLike | None = None
) -> np.ndarray:
    """Return the feature names used by the fitted estimator."""
    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
    return np.asarray(self.universe_.var_names, dtype=object)

ScaledChoquetRegressor

Scaled Choquet regression \(c + qC_\mu(x)\) with a normalized monotone capacity, a learned intercept, and configurable bounds on \(q\).

ScaledChoquetRegressor

ScaledChoquetRegressor(
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    q_bounds: tuple[float, float] = (0.0, inf),
)

Bases: RegressorMixin, BaseEstimator

Least-squares regression of the form c + q * C_mu(X).

This separate estimator implements the scaled Choquet submodel discussed by Grabisch after Wang et al. The capacity remains normalized and monotone; q controls the response scale without changing that normalization.

Parameters

sparsity : CapacitySparsity, optional Capacity parameterization. None fits a full explicit capacity. solver : {"scipy", "pymoo"} or Solver, default="scipy" Numerical backend. CVXPY is unavailable because q * C_mu is bilinear in the jointly learned parameters. solver_options : dict, optional Keyword arguments forwarded to the selected backend. penalty : callable or penalty object, optional Regularization added to the squared-error objective. q_bounds : pair of float, default=(0.0, inf) Bounds for q. The nonnegative default preserves monotonicity of the complete regression function. Negative values can be enabled explicitly.

Attributes

capacity_ : BaseCapacity Fitted normalized monotone capacity. q_ : float Fitted scale multiplying the Choquet integral. intercept_ : float Fitted error-center/intercept c. problem_ : Problem Joint constrained optimization problem. result_ : OptimizationResult Numerical optimizer result and diagnostics.

Notes

The initial q and c are obtained by ordinary least squares for the initial feasible capacity, as in the paper's proposed submodels. Joint numerical minimization then retains all capacity and q constraints. Inputs must be commensurable before aggregation.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def __init__(
    self,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    q_bounds: tuple[float, float] = (0.0, np.inf),
) -> None:
    self.sparsity = sparsity
    self.solver = solver
    self.solver_options = solver_options
    self.penalty = penalty
    self.q_bounds = q_bounds

fit

fit(X: ArrayLike, y: ArrayLike) -> 'ScaledChoquetRegressor'

Fit the capacity, scale q, and intercept c.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def fit(self, X: ArrayLike, y: ArrayLike) -> "ScaledChoquetRegressor":
    """Fit the capacity, scale ``q``, and intercept ``c``."""
    matrix, target = validate_data(
        self, X, y, dtype=float, ensure_2d=True, ensure_min_samples=1
    )
    self.universe_ = fitted_universe(self)
    target = np.asarray(target, dtype=float).reshape(-1)
    if not np.all(np.isfinite(target)):
        raise ValueError("y must contain only finite values.")
    self.solver_ = resolve_solver(self.solver)
    if self.solver_ is Solver.CVXPY:
        raise ValueError(
            "The q-times-capacity model is non-convex; use SCIPY or PYMOO."
        )
    q_lower, q_upper = self._validated_q_bounds()

    sparsity = self.sparsity if self.sparsity is not None else FullCapacity()
    compilation = sparsity.compile(self.universe_.n_elements)
    design = capacity_design(
        matrix,
        compilation.bundle.parameter_masks,
        compilation.bundle.representation,
    )
    capacity_initial = compilation.initial_parameters

    # For a fixed feasible capacity, q and c are linear-regression terms.
    aggregate = design @ capacity_initial
    linear_initial, *_ = np.linalg.lstsq(
        np.column_stack([aggregate, np.ones(target.size)]), target, rcond=None
    )
    q_initial = float(np.clip(linear_initial[0], q_lower, q_upper))
    intercept_initial = float(np.mean(target - q_initial * aggregate))

    layout = ParameterLayout(
        ParameterBlock("capacity", compilation.bundle.n_parameters),
        ParameterBlock("q", 1, lower=q_lower, upper=q_upper),
        ParameterBlock("intercept", 1),
    )
    predictor = partial(
        scaled_regression_predictor,
        design=design,
        capacity_slice=layout.slice("capacity"),
        q_slice=layout.slice("q"),
        intercept_slice=layout.slice("intercept"),
    )
    objective = SquaredErrorObjective(
        target=target, predictor=predictor, penalty=self.penalty
    )
    problem = Problem.from_capacity(
        universe=self.universe_,
        objective=objective,
        sparsity=sparsity,
        parameter_layout=layout,
        initial_parameters=np.concatenate(
            [capacity_initial, np.array([q_initial, intercept_initial])]
        ),
        name="scaled_choquet_regression",
        metadata={"formulation": "c + q * C_mu(X)"},
    )
    options = {} if self.solver_options is None else dict(self.solver_options)
    result = Optimizer(solver=self.solver_, **options).solve(problem)
    if not result.success:
        raise RuntimeError(
            f"Scaled Choquet regression optimization failed: {result.message}"
        )

    blocks = layout.unpack(result.parameters)
    self.problem_ = problem
    self.result_ = result
    self.capacity_ = problem.decode_result(result)
    self.q_ = float(blocks["q"][0])
    self.intercept_ = float(blocks["intercept"][0])
    self.sparsity_ = sparsity
    return self

predict

predict(X: ArrayLike) -> ndarray

Predict continuous responses.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def predict(self, X: ArrayLike) -> np.ndarray:
    """Predict continuous responses."""
    check_is_fitted(self, ["capacity_", "q_", "intercept_"])
    matrix = validate_data(self, X, reset=False, dtype=float)
    return self.intercept_ + self.q_ * batch_choquet_integral(
        matrix, self.capacity_
    )

fit_predict

fit_predict(X: ArrayLike, y: ArrayLike) -> ndarray

Fit the model and return predictions for X.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def fit_predict(self, X: ArrayLike, y: ArrayLike) -> np.ndarray:
    """Fit the model and return predictions for ``X``."""
    return self.fit(X, y).predict(X)

get_feature_names_out

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

Return the feature names used by the fitted estimator.

Source code in src/capacities_ml_fin/ml/models/regression/choquet.py
def get_feature_names_out(
    self, input_features: ArrayLike | None = None
) -> np.ndarray:
    """Return the feature names used by the fitted estimator."""
    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
    return np.asarray(self.universe_.var_names, dtype=object)

ChoquetClassifier

Deterministic binary threshold classifier. Inputs must lie in \([0,1]\) and be oriented so larger values favor the positive class. It exposes choquet_score() and decision_function() but intentionally no predict_proba().

ChoquetClassifier

ChoquetClassifier(
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "pymoo",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    learn_feature_scales: bool = True,
)

Bases: ClassifierMixin, BaseEstimator

Binary threshold classifier based on a learned Choquet score.

The decision rule compares C_mu(b * x) with a learned threshold. When feature scaling is enabled, non-negative scales b are fitted jointly with the capacity and normalized to have maximum one. Inputs must lie in [0, 1] and larger values must favor the positive class.

Parameters

sparsity : CapacitySparsity, optional Capacity parameterization. None fits a full explicit capacity. solver : {"scipy", "cvxpy", "pymoo"} or Solver, default="pymoo" Optimization backend. PYMOO is suitable for the discontinuous zero-one training loss. solver_options : dict, optional Keyword arguments forwarded to the selected backend. penalty : callable or penalty object, optional Regularization term added to the classification objective. learn_feature_scales : bool, default=True Whether to jointly learn normalized criterion scales.

Attributes

classes_ : ndarray of shape (2,) Original binary class labels. capacity_ : BaseCapacity Fitted immutable capacity. threshold_ : float Learned decision threshold in [0, 1]. feature_scales_ : ndarray of shape (n_features,) Learned scales, or ones when scale learning is disabled. result_ : OptimizationResult Numerical optimizer result and diagnostics. n_features_in_ : int Number of input features seen during :meth:fit.

Notes

The model is a deterministic classifier and therefore intentionally does not implement predict_proba. Use :meth:decision_function to inspect signed margins around the fitted threshold.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def __init__(
    self,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "pymoo",
    solver_options: dict[str, Any] | None = None,
    penalty: Any = None,
    learn_feature_scales: bool = True,
) -> None:
    self.sparsity = sparsity
    self.solver = solver
    self.solver_options = solver_options
    self.penalty = penalty
    self.learn_feature_scales = learn_feature_scales

fit

fit(X: ArrayLike, y: ArrayLike) -> 'ChoquetClassifier'

Fit the capacity, optional feature scales and decision threshold.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def fit(self, X: ArrayLike, y: ArrayLike) -> "ChoquetClassifier":
    """Fit the capacity, optional feature scales and decision threshold."""
    # input and binary-label validation
    matrix, raw_target = validate_data(
        self,
        X,
        y,
        dtype=float,
        ensure_2d=True,
        ensure_min_samples=1,
    )
    self.universe_ = fitted_universe(self)
    matrix = validate_unit_interval(matrix)
    raw_target = column_or_1d(raw_target, warn=True)
    if raw_target.shape != (matrix.shape[0],):
        raise ValueError("y must contain one label per observation.")
    label_encoder = LabelEncoder()
    target = label_encoder.fit_transform(raw_target)
    if label_encoder.classes_.size != 2:
        raise ValueError("y must contain exactly two distinct labels.")
    self.solver_ = resolve_solver(self.solver)
    if not isinstance(self.learn_feature_scales, (bool, np.bool_)):
        raise TypeError("learn_feature_scales must be boolean.")

    # capacity design and threshold initialization
    sparsity = self.sparsity if self.sparsity is not None else FullCapacity()
    compilation = sparsity.compile(self.universe_.n_elements)
    design = capacity_design(
        matrix,
        compilation.bundle.parameter_masks,
        compilation.bundle.representation,
    )
    capacity_initial = compilation.initial_parameters
    threshold_initial = float(
        np.clip(np.median(design @ capacity_initial), 0.0, 1.0)
    )
    blocks = [
        ParameterBlock("capacity", compilation.bundle.n_parameters)
    ]
    if self.learn_feature_scales:
        blocks.append(
            ParameterBlock(
                "feature_scales",
                self.universe_.n_elements,
                lower=1e-8,
                upper=1.0,
            )
        )
    blocks.append(ParameterBlock("threshold", 1, lower=0.0, upper=1.0))
    layout = ParameterLayout(*blocks)
    capacity_slice = layout.slice("capacity")
    threshold_slice = layout.slice("threshold")

    initial_parts = [capacity_initial]
    if self.learn_feature_scales:
        feature_scales_slice = layout.slice("feature_scales")
        initial_parts.append(np.ones(self.universe_.n_elements, dtype=float))
        classifier = partial(
            scaled_linear_classifier,
            matrix=matrix,
            parameter_masks=compilation.bundle.parameter_masks,
            representation=compilation.bundle.representation,
            capacity_slice=capacity_slice,
            feature_scales_slice=feature_scales_slice,
            threshold_slice=threshold_slice,
        )
    else:
        feature_scales_slice = None
        classifier = partial(
            linear_classifier,
            design=design,
            capacity_slice=capacity_slice,
            threshold_slice=threshold_slice,
        )
    initial_parts.append(np.array([threshold_initial]))

    # direct 0-1 loss optimization
    objective = ZeroOneLossObjective(
        target=target,
        predictor=classifier,
        penalty=self.penalty,
    )
    problem = Problem.from_capacity(
        universe=self.universe_,
        objective=objective,
        sparsity=sparsity,
        parameter_layout=layout,
        initial_parameters=np.concatenate(initial_parts),
        name="choquet_linear_classifier",
    )
    options = {} if self.solver_options is None else dict(self.solver_options)
    result = Optimizer(solver=self.solver_, **options).solve(problem)
    if not result.success:
        violation = result.diagnostics.get("maximum_constraint_violation")
        raise RuntimeError(
            "Choquet classification optimization failed: "
            f"{result.message} Maximum constraint violation: {violation}."
        )

    # fitted scikit-learn state
    self.problem_ = problem
    self.result_ = result
    self.capacity_ = problem.decode_result(result)
    self.threshold_ = float(result.parameters[threshold_slice][0])
    self.feature_scales_ = (
        normalized_feature_scales(result.parameters[feature_scales_slice])
        if feature_scales_slice is not None
        else np.ones(self.universe_.n_elements, dtype=float)
    )
    self.classes_ = label_encoder.classes_
    self.n_classes_ = self.classes_.size
    self.sparsity_ = sparsity
    return self

decision_function

decision_function(X: ArrayLike) -> ndarray

Return signed margins relative to the learned decision threshold.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def decision_function(self, X: ArrayLike) -> np.ndarray:
    """Return signed margins relative to the learned decision threshold."""
    return self.choquet_score(X) - self.threshold_

choquet_score

choquet_score(X: ArrayLike) -> ndarray

Return the Choquet projection before thresholding.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def choquet_score(self, X: ArrayLike) -> np.ndarray:
    """Return the Choquet projection before thresholding."""
    check_is_fitted(self, ["capacity_", "threshold_", "feature_scales_"])
    matrix = validate_data(self, X, reset=False, dtype=float)
    matrix = validate_unit_interval(matrix)
    return batch_choquet_integral(
        matrix * self.feature_scales_,
        self.capacity_,
    )

predict

predict(X: ArrayLike) -> ndarray

Predict binary labels using the fitted threshold.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def predict(self, X: ArrayLike) -> np.ndarray:
    """Predict binary labels using the fitted threshold."""
    encoded_predictions = (self.decision_function(X) >= 0.0).astype(int)
    return self.classes_[encoded_predictions]

get_feature_names_out

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

Return the feature names used by the fitted estimator.

Source code in src/capacities_ml_fin/ml/models/classification/linear.py
def get_feature_names_out(self, input_features: ArrayLike | None = None) -> np.ndarray:
    """Return the feature names used by the fitted estimator."""
    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
    return np.asarray(self.universe_.var_names, dtype=object)

ChoquisticRegression

Probabilistic binary Choquet classifier with latent utility \(C_\mu(x)\) and logistic link \(\gamma(C_\mu(x)-\beta)\).

ChoquisticRegression

ChoquisticRegression(
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    class_weight: dict[Any, float] | str | None = None,
    penalty: Any = None,
)

Bases: ClassifierMixin, BaseEstimator

Probabilistic binary regression with a Choquet logistic link.

The latent utility is C_mu(x) and the positive-class log-odds are gamma * (C_mu(x) - beta). The normalized monotone capacity mu, location beta, and positive scale gamma are learned jointly.

Parameters

sparsity : CapacitySparsity, optional Capacity parameterization. None uses a k-additive default. solver : {"scipy", "cvxpy", "pymoo"} or Solver, default="scipy" Optimization backend. solver_options : dict, optional Options forwarded to the backend. class_weight : dict, "balanced", or None, default=None Per-class weights applied to the negative log-likelihood. penalty : callable or penalty object, optional Regularization term added to the objective.

Attributes

classes_ : ndarray of shape (2,) Original binary labels. capacity_ : BaseCapacity Fitted immutable capacity. beta_ : float Learned utility location. gamma_ : float Learned positive log-odds scale. result_ : OptimizationResult Numerical optimizer result and diagnostics. n_features_in_ : int Number of features seen during :meth:fit.

Notes

Unlike :class:ChoquetClassifier, this model defines positive-class probabilities through the logistic link and implements predict_proba.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def __init__(
    self,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    class_weight: dict[Any, float] | str | None = None,
    penalty: Any = None,
) -> None:
    self.sparsity = sparsity
    self.solver = solver
    self.solver_options = solver_options
    self.class_weight = class_weight
    self.penalty = penalty

fit

fit(
    X: ArrayLike,
    y: ArrayLike,
    sample_weight: ArrayLike | None = None,
) -> "ChoquisticRegression"

Fit the capacity, utility threshold and scale by maximum likelihood.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def fit(
    self,
    X: ArrayLike,
    y: ArrayLike,
    sample_weight: ArrayLike | None = None,
) -> "ChoquisticRegression":
    """Fit the capacity, utility threshold and scale by maximum likelihood."""
    # input and binary-label validation
    matrix, raw_target = validate_data(
        self,
        X,
        y,
        dtype=float,
        ensure_2d=True,
        ensure_min_samples=1,
    )
    self.universe_ = fitted_universe(self)
    matrix = validate_unit_interval(matrix)
    encoder = LabelEncoder()
    target = encoder.fit_transform(raw_target)
    if encoder.classes_.size != 2:
        raise ValueError("y must contain exactly two distinct labels.")
    self.solver_ = resolve_solver(self.solver)
    if self.solver_ is not Solver.SCIPY:
        raise ValueError(
            "The paper formulation is fitted with sequential quadratic "
            "programming; use Solver.SCIPY."
        )

    # optional class and observation weights
    weights = compute_sample_weight(self.class_weight, raw_target).astype(float)
    if sample_weight is not None:
        supplied = np.asarray(sample_weight, dtype=float).reshape(-1)
        if supplied.shape != target.shape:
            raise ValueError("sample_weight must contain one value per observation.")
        if np.any(~np.isfinite(supplied)) or np.any(supplied < 0.0):
            raise ValueError("sample_weight must be finite and non-negative.")
        weights *= supplied
    if not np.any(weights > 0.0):
        raise ValueError("At least one sample must have positive weight.")

    # full Mobius capacity by default, or the requested sparse capacity
    sparsity = (
        self.sparsity
        if self.sparsity is not None
        else KAdditivity(order=self.universe_.n_elements)
    )
    compilation = sparsity.compile(self.universe_.n_elements)
    design = capacity_design(
        matrix,
        compilation.bundle.parameter_masks,
        compilation.bundle.representation,
    )
    capacity_initial = compilation.initial_parameters
    initial_scores = design @ capacity_initial

    # paper parameters gamma and beta with feasible initial values
    negative_mean = float(
        np.average(initial_scores[target == 0], weights=weights[target == 0])
    )
    positive_mean = float(
        np.average(initial_scores[target == 1], weights=weights[target == 1])
    )
    beta_initial = float(
        np.clip((negative_mean + positive_mean) / 2.0, 0.0, 1.0)
    )
    gamma_initial = 1.0

    layout = ParameterLayout(
        ParameterBlock("capacity", compilation.bundle.n_parameters),
        ParameterBlock("gamma", 1, lower=_MIN_GAMMA),
        ParameterBlock("beta", 1, lower=0.0, upper=1.0),
    )
    capacity_slice = layout.slice("capacity")
    gamma_slice = layout.slice("gamma")
    beta_slice = layout.slice("beta")
    linear_predictor = partial(
        choquistic_logits,
        design=design,
        capacity_slice=capacity_slice,
        gamma_slice=gamma_slice,
        beta_slice=beta_slice,
    )

    # constrained maximum-likelihood problem
    objective = LogisticNegativeLogLikelihood(
        target=target,
        predictor=linear_predictor,
        sample_weight=weights,
        penalty=self.penalty,
    )
    problem = Problem.from_capacity(
        universe=self.universe_,
        objective=objective,
        sparsity=sparsity,
        parameter_layout=layout,
        initial_parameters=np.concatenate(
            [capacity_initial, np.array([gamma_initial, beta_initial])]
        ),
        name="choquistic_regression",
    )
    options = {} if self.solver_options is None else dict(self.solver_options)
    result = Optimizer(solver=self.solver_, **options).solve(problem)
    if not result.success:
        raise RuntimeError(f"Choquistic optimization failed: {result.message}")

    # fitted scikit-learn state
    self.problem_ = problem
    self.result_ = result
    self.capacity_ = problem.decode_result(result)
    self.gamma_ = float(result.parameters[gamma_slice][0])
    self.beta_ = float(result.parameters[beta_slice][0])
    self.classes_ = encoder.classes_
    self.sparsity_ = sparsity
    return self

utility_function

utility_function(X: ArrayLike) -> ndarray

Return the latent utility C_mu(X) from the paper's first stage.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def utility_function(self, X: ArrayLike) -> np.ndarray:
    """Return the latent utility ``C_mu(X)`` from the paper's first stage."""
    check_is_fitted(self, ["capacity_", "gamma_", "beta_"])
    matrix = validate_unit_interval(
        validate_data(self, X, reset=False, dtype=float)
    )
    return batch_choquet_integral(matrix, self.capacity_)

decision_function

decision_function(X: ArrayLike) -> ndarray

Return the fitted log-odds gamma * (C_mu(X) - beta).

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def decision_function(self, X: ArrayLike) -> np.ndarray:
    """Return the fitted log-odds ``gamma * (C_mu(X) - beta)``."""
    scores = self.utility_function(X)
    return apply_choquistic_link(
        scores,
        gamma=self.gamma_,
        beta=self.beta_,
    )

predict_proba

predict_proba(X: ArrayLike) -> ndarray

Return probabilities for the two encoded classes.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def predict_proba(self, X: ArrayLike) -> np.ndarray:
    """Return probabilities for the two encoded classes."""
    positive = expit(self.decision_function(X))
    return np.column_stack((1.0 - positive, positive))

predict_log_proba

predict_log_proba(X: ArrayLike) -> ndarray

Return numerically stable log-probabilities.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def predict_log_proba(self, X: ArrayLike) -> np.ndarray:
    """Return numerically stable log-probabilities."""
    logits = self.decision_function(X)
    return np.column_stack((-np.logaddexp(0.0, logits), -np.logaddexp(0.0, -logits)))

predict

predict(X: ArrayLike) -> ndarray

Predict class labels using a probability threshold of 0.5.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def predict(self, X: ArrayLike) -> np.ndarray:
    """Predict class labels using a probability threshold of 0.5."""
    encoded = (self.decision_function(X) >= 0.0).astype(int)
    return self.classes_[encoded]

get_feature_names_out

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

Return the feature names used by the fitted estimator.

Source code in src/capacities_ml_fin/ml/models/classification/choquistic.py
def get_feature_names_out(self, input_features: ArrayLike | None = None) -> np.ndarray:
    """Return the feature names used by the fitted estimator."""
    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
    return np.asarray(self.universe_.var_names, dtype=object)

ChoquetAutoRegressor

Native sktime univariate forecaster. It aggregates autoregressive lags through a capacity and supports optional exogenous regressors, recursive prediction intervals and updates.

ChoquetAutoRegressor

ChoquetAutoRegressor(
    lags: int = 1,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    fit_intercept: bool = True,
    enforce_stationarity: bool = True,
    stability_bound: float = 0.999,
)

Bases: BaseForecaster

Univariate Choquet autoregression compatible with sktime.

The conditional mean is intercept + phi * C_nu(y[t-1], ..., y[t-p]). Optional exogenous variables enter additively. When stationarity is enforced, abs(phi) <= stability_bound < 1.

Parameters

lags : int, default=1 Number of lagged observations aggregated by the Choquet integral. sparsity : CapacitySparsity or None, default=None Capacity parametrization. None uses a full capacity. solver : {"scipy", "pymoo"} or Solver, default="scipy" Numerical optimizer used to estimate the model. solver_options : dict or None, default=None Options forwarded to :class:~capacities_ml_fin.ml.optimization.Optimizer. fit_intercept : bool, default=True Whether to estimate an intercept. enforce_stationarity : bool, default=True Whether to constrain the autoregressive scale to a contraction. stability_bound : float, default=0.999 Absolute upper bound for phi when stationarity is enforced.

Attributes

capacity_ : BaseCapacity Capacity learned over lagged observations. phi_ : float Autoregressive scale multiplying the Choquet aggregate. intercept_ : float Fitted intercept, or zero when fit_intercept=False. exogenous_coef_ : ndarray Coefficients of optional exogenous regressors. fittedvalues_ : Series In-sample conditional-mean estimates after the initial lags. resid_ : Series In-sample residuals aligned with fittedvalues_. result_ : OptimizationResult Numerical optimizer result and diagnostics. order_ : tuple of int AR-style order (lags, 0, 0).

Notes

Forecasts beyond one step are generated recursively through the sktime forecasting horizon interface.

Source code in src/capacities_ml_fin/ml/models/time_series/choquet.py
def __init__(
    self,
    lags: int = 1,
    sparsity: CapacitySparsity | None = None,
    solver: Solver | str = "scipy",
    solver_options: dict[str, Any] | None = None,
    fit_intercept: bool = True,
    enforce_stationarity: bool = True,
    stability_bound: float = 0.999,
) -> None:
    self.lags = lags
    self.sparsity = sparsity
    self.solver = solver
    self.solver_options = solver_options
    self.fit_intercept = fit_intercept
    self.enforce_stationarity = enforce_stationarity
    self.stability_bound = stability_bound
    super().__init__()

resid

resid() -> Series

Return one-step training residuals.

Source code in src/capacities_ml_fin/ml/models/time_series/choquet.py
def resid(self) -> pd.Series:
    """Return one-step training residuals."""
    self.check_is_fitted()
    return self.resid_.copy()

aic

aic() -> float

Return the Gaussian Akaike information criterion.

Source code in src/capacities_ml_fin/ml/models/time_series/choquet.py
def aic(self) -> float:
    """Return the Gaussian Akaike information criterion."""
    return self._information_criterion(penalty=2.0)

bic

bic() -> float

Return the Gaussian Bayesian information criterion.

Source code in src/capacities_ml_fin/ml/models/time_series/choquet.py
def bic(self) -> float:
    """Return the Gaussian Bayesian information criterion."""
    self.check_is_fitted()
    return self._information_criterion(penalty=float(np.log(self.resid_.size)))

get_test_params classmethod

get_test_params(
    parameter_set: str = "default",
) -> list[dict[str, Any]]

Return a fast configuration for sktime estimator checks.

Source code in src/capacities_ml_fin/ml/models/time_series/choquet.py
@classmethod
def get_test_params(
    cls, parameter_set: str = "default"
) -> list[dict[str, Any]]:
    """Return a fast configuration for ``sktime`` estimator checks."""
    return [{"lags": 1}, {"lags": 2, "fit_intercept": False}]