Исходный код pysatl_mpest.estimators.base_estimator

"""Abstract base class for mixture model parameter estimators."""

__author__ = "Danil Totmyanin, Aleksandra Ri"
__copyright__ = "Copyright (c) 2025 PySATL project"
__license__ = "SPDX-License-Identifier: MIT"

import functools
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Any

import numpy as np
from numpy.typing import ArrayLike

from ..core import MixtureModel
from ..core._validation import sample_coverage, zero_weight_components
from ..typings import UnivariateFloatArray, UnivariateIntArray


[документация] class BaseEstimator(ABC): """Abstract base class for mixture model parameter estimators. Every subclass that defines ``fit`` gets the check of the starting mixture automatically: before its ``fit`` runs, the start is checked on the sample. The signature and the docstring of ``fit`` stay those of the subclass. Methods ------- .. autosummary:: :toctree: generated/ fit """ def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # An abstract ``fit`` stays abstract after wrapping: ``functools.wraps`` copies ``__isabstractmethod__``. fit = cls.__dict__.get("fit") if fit is not None: setattr(cls, "fit", _with_start_check(fit))
[документация] @abstractmethod def fit(self, X: ArrayLike, mixture: MixtureModel) -> MixtureModel: """Fit mixture model parameters to input data. Parameters ---------- X : ArrayLike Input data sample. mixture : MixtureModel Initial mixture model to fit; not modified in-place. Returns ------- MixtureModel Fitted mixture model with estimated parameters. Raises ------ ValueError If the starting mixture leaves a sample point uncovered, has a NaN or +inf log-density at a sample point, or has a zero-weight component (checked in this order; the first violation is reported). """
def _with_start_check(fit: Callable[..., MixtureModel]) -> Callable[..., MixtureModel]: """Wrap the ``fit`` of a subclass so that it checks the starting mixture first.""" @functools.wraps(fit) def checked_fit( self: BaseEstimator, X: ArrayLike, mixture: MixtureModel, *args: Any, **kwargs: Any ) -> MixtureModel: _validate_start(mixture, np.asarray(X, dtype=np.float64)) return fit(self, X, mixture, *args, **kwargs) return checked_fit def _validate_start(mixture: MixtureModel, X: UnivariateFloatArray) -> None: """Raise ``ValueError`` on the first violation of the starting mixture found on the sample. The checks run in the order "uncovered points, then points with NaN or +inf log-density, then zero-weight components"; only the first violation is reported. """ coverage = sample_coverage(mixture, X) n = len(X) if len(coverage.uncovered) != 0: raise ValueError( f"{len(coverage.uncovered)} of {n} sample points are not covered by any component of the " f"starting mixture, for example {_point_examples(X, coverage.uncovered)}." ) if len(coverage.undefined) != 0: raise ValueError( f"The log-density of the starting mixture is NaN or +inf at {len(coverage.undefined)} of {n} " f"sample points, for example {_point_examples(X, coverage.undefined)}." ) zero_weight = zero_weight_components(mixture) if len(zero_weight) != 0: indices = ", ".join(str(int(j)) for j in zero_weight) raise ValueError(f"The starting mixture has components with zero weight, which EM never updates: {indices}.") def _point_examples(X: UnivariateFloatArray, indices: UnivariateIntArray) -> str: """Values of the sample in the first three points with the given indices.""" return ", ".join(str(float(X[index])) for index in indices[:3])