Skip to content

Fitting API

Top-level fitting helpers are documented under Top-level API. This page documents prepared Gaussian-mixture fits, optimizer and objective configurations, and candidate-selection helpers from gmm_divergence.fitting.

The notation conventions distinguish \(L\) candidate distributions \(q_i\) and their fitted weights \(w_i\) from the \(K_i\) Gaussian components inside each candidate. Fitting holds candidate parameters fixed and changes only \(\mathbf{w}\in\Delta_L\).

gmm_divergence.fitting

Public fitting API.

Fitting From Samples

Fit mixture parameters from observations directly with scikit-learn, then convert the fitted estimator using GaussianMixture.from_sklearn. The constructor supports all four sklearn covariance types and expands them into full covariance matrices.

import numpy as np
from sklearn.mixture import GaussianMixture

import gmm_divergence as gd

rng = np.random.default_rng(0)
samples = np.concatenate([rng.normal(-2, 1, size=(100, 1)), rng.normal(2, 0.5, size=(100, 1))])
estimator = GaussianMixture(n_components=2, covariance_type="diag", n_init=3, random_state=0).fit(
    samples
)
gmm = gd.GaussianMixture.from_sklearn(estimator)
assert gmm.n_components == 2

See GaussianMixture for the conversion constructor and other ways to construct mixtures.

Component Statistics

Use fixed responsibilities or a shared reference mixture to estimate empirical component statistics. Component indices stay aligned with the supplied assignments, and components with zero responsibility mass are rejected. Regularization is applied only when converting statistics into a mixture.

import gmm_divergence as gd

stats = gd.fitting.component_statistics(
    [[0.0], [2.0], [4.0]], responsibilities=[[1, 0], [0.5, 0.5], [0, 1]]
)
population = stats.to_gaussian_mixture(regularizer=gd.covariance.DiagonalLoading())
assert population.n_components == 2

component_statistics

component_statistics(
    x: ArrayLike,
    /,
    *,
    responsibilities: ArrayLike | None = None,
    mixture: GaussianMixture | None = None,
    empty_component_policy: Literal["raise", "reference"] = "raise",
) -> ComponentStatistics

Compute empirical component statistics from fixed responsibilities.

For \(N\) observations \(x_n\in\mathbb{R}^d\) and responsibilities \(r_{nk}\) over \(K\) components, with \(r_{nk}\geq0\) and \(\sum_{k=1}^{K}r_{nk}=1\), compute

\[ N_k = \sum_{n=1}^{N}r_{nk}, \qquad \widehat\pi_k=N_k/N, \qquad \widehat\mu_k=\frac{\sum_{n=1}^{N}r_{nk}x_n}{N_k}, \]
\[ \widehat\Sigma_k=\frac{\sum_{n=1}^{N}r_{nk}(x_n-\widehat\mu_k) (x_n-\widehat\mu_k)^\top}{N_k}, \qquad N_{\mathrm{eff},k}=\frac{N_k^2}{\sum_{n=1}^{N}r_{nk}^2}. \]

Here \(N_k\) is the soft count, \(\widehat\pi_k\) the empirical component probability, \(\widehat\mu_k\) and \(\widehat\Sigma_k\) its estimated mean and covariance, and \(N_{\mathrm{eff},k}\) the Kish concentration measure.

Parameters:

  • x ((array - like, shape(n_samples, n_features))) –

    Nonempty, finite observations.

  • responsibilities ((array - like, shape(n_samples, n_components)), default: None ) –

    Finite, nonnegative assignments summing to one per observation. Exactly one of responsibilities or mixture must be provided.

  • mixture (GaussianMixture, default: None ) –

    Reference mixture used to compute responsibilities without refitting.

Returns:

  • ComponentStatistics –

    Independent, read-only weights, means, covariances, soft_counts, and effective_sample_sizes, preserving component order.

Notes

This performs a single moment-estimation step, not an iterative GMM fit. Invalid inputs and components with zero responsibility mass raise ValueError; empty components are rejected rather than dropped to preserve alignment.

Covariances use weighted maximum-likelihood estimates without an unbiasedness correction and may be singular. Apply optional regularization through ComponentStatistics.to_gaussian_mixture(regularizer=...). Small soft counts may give unreliable estimates; regularization cannot compensate for insufficient data.

Kish effective sample size measures concentration of responsibility weights, not component mass or the number of independent observations.

Source code in src/gmm_divergence/fitting/_component_statistics.py
def component_statistics(
    x: npt.ArrayLike,
    /,
    *,
    responsibilities: npt.ArrayLike | None = None,
    mixture: GaussianMixture | None = None,
    empty_component_policy: Literal["raise", "reference"] = "raise",
) -> ComponentStatistics:
    r"""Compute empirical component statistics from fixed responsibilities.

    For $N$ observations $x_n\in\mathbb{R}^d$ and responsibilities $r_{nk}$
    over $K$ components, with $r_{nk}\geq0$ and $\sum_{k=1}^{K}r_{nk}=1$, compute

    $$
    N_k = \sum_{n=1}^{N}r_{nk}, \qquad \widehat\pi_k=N_k/N,
    \qquad \widehat\mu_k=\frac{\sum_{n=1}^{N}r_{nk}x_n}{N_k},
    $$

    $$
    \widehat\Sigma_k=\frac{\sum_{n=1}^{N}r_{nk}(x_n-\widehat\mu_k)
    (x_n-\widehat\mu_k)^\top}{N_k},
    \qquad N_{\mathrm{eff},k}=\frac{N_k^2}{\sum_{n=1}^{N}r_{nk}^2}.
    $$

    Here $N_k$ is the soft count, $\widehat\pi_k$ the empirical component
    probability, $\widehat\mu_k$ and $\widehat\Sigma_k$ its estimated mean and
    covariance, and $N_{\mathrm{eff},k}$ the Kish concentration measure.

    Parameters
    ----------
    x : array-like, shape (n_samples, n_features)
        Nonempty, finite observations.
    responsibilities : array-like, shape (n_samples, n_components), optional
        Finite, nonnegative assignments summing to one per observation.
        Exactly one of `responsibilities` or `mixture` must be provided.
    mixture : GaussianMixture, optional
        Reference mixture used to compute responsibilities without refitting.

    Returns
    -------
    ComponentStatistics
        Independent, read-only `weights`, `means`, `covariances`, `soft_counts`,
        and `effective_sample_sizes`, preserving component order.

    Notes
    -----
    This performs a single moment-estimation step, not an iterative GMM fit.
    Invalid inputs and components with zero responsibility mass raise `ValueError`;
    empty components are rejected rather than dropped to preserve alignment.

    Covariances use weighted maximum-likelihood estimates without an
    unbiasedness correction and may be singular. Apply optional regularization
    through `ComponentStatistics.to_gaussian_mixture(regularizer=...)`.
    Small soft counts may give unreliable estimates; regularization cannot
    compensate for insufficient data.

    Kish effective sample size measures concentration of responsibility weights,
    not component mass or the number of independent observations.
    """
    if (responsibilities is None) == (mixture is None):
        msg = "Exactly one of 'responsibilities' or 'mixture' must be provided."
        raise ValueError(msg)

    if empty_component_policy == "reference" and mixture is None:
        msg_0 = "empty_component_policy='reference' requires mixture."
        raise ValueError(msg_0)

    x = np.asarray(x, dtype=np.float64)
    if x.ndim != 2 or 0 in x.shape or not np.isfinite(x).all():
        msg = "x must be a nonempty, finite 2D array."
        raise ValueError(msg)

    r = np.asarray(
        mixture.responsibilities(x) if mixture is not None else responsibilities, dtype=np.float64
    )
    if r.ndim != 2 or r.shape[0] != len(x) or r.shape[1] == 0:
        msg = "responsibilities must have shape (n_samples, n_components)."
        raise ValueError(msg)
    r = as_probability_rows(r, name="responsibilities")

    n_samples, n_features = x.shape
    n_components = r.shape[1]
    counts = r.sum(axis=0)
    empty = np.flatnonzero(counts == 0)

    if empty.size and empty_component_policy == "raise":
        msg = f"Components with zero responsibility mass: {empty.tolist()}."
        raise ValueError(msg)

    if empty_component_policy == "reference" and mixture is not None:
        means = mixture.means.copy()
        covariances = mixture.covariances.copy()
    else:
        means = np.empty((n_components, n_features), dtype=np.float64)
        covariances = np.empty((n_components, n_features, n_features), dtype=np.float64)

    effective_sample_sizes = np.zeros(n_components, dtype=np.float64)

    for k in np.flatnonzero(counts > 0):
        # Scale before normalization to handle extremely small responsibilities.
        column = r[:, k]
        scaled = column / column.max()
        weights = scaled / scaled.sum()

        means[k] = weights @ x
        centered = x - means[k]
        covariance = (centered * weights[:, None]).T @ centered
        covariances[k] = 0.5 * (covariance + covariance.T)

        # Equivalent to counts[k]**2 / sum(r[:, k]**2), without underflow.
        effective_sample_sizes[k] = 1.0 / (weights @ weights)

    return ComponentStatistics(
        weights=counts / n_samples,
        means=means,
        covariances=covariances,
        soft_counts=counts,
        effective_sample_sizes=effective_sample_sizes,
    )

ComponentStatistics dataclass

ComponentStatistics(
    weights: FloatArray,
    means: FloatArray,
    covariances: FloatArray,
    soft_counts: FloatArray,
    effective_sample_sizes: FloatArray,
)

Responsibility-weighted empirical statistics with read-only arrays.

covariances instance-attribute

covariances: FloatArray

Weighted maximum-likelihood covariances, which may be singular. Shape (n_components, n_features, n_features).

effective_sample_sizes instance-attribute

effective_sample_sizes: FloatArray

Kish concentration measure, soft_counts squared divided by the sum of squared responsibilities; not a count of independent observations. Shape (n_components,).

means instance-attribute

means: FloatArray

Responsibility-weighted empirical means. Shape (n_components, n_features).

soft_counts instance-attribute

soft_counts: FloatArray

Sum of responsibilities for each component. Shape (n_components,).

weights instance-attribute

weights: FloatArray

Soft counts divided by the number of observations. Shape (n_components,).

to_gaussian_mixture

to_gaussian_mixture(
    *, regularizer: CovarianceRegularizer | None = None
) -> GaussianMixture

Convert statistics, optionally regularizing covariances without modifying them.

Singular empirical covariances require regularization for conversion.

Parameters:

  • regularizer (CovarianceRegularizer or None, default: None ) –

    Optional configuration applied to each empirical covariance.

Returns:

  • GaussianMixture –

    Independent mixture preserving empirical component order.

Notes

Construction raises ValueError if a covariance is not positive definite after any regularization.

Source code in src/gmm_divergence/fitting/_component_statistics.py
def to_gaussian_mixture(
    self, *, regularizer: CovarianceRegularizer | None = None
) -> GaussianMixture:
    """Convert statistics, optionally regularizing covariances without modifying them.

    Singular empirical covariances require regularization for conversion.

    Parameters
    ----------
    regularizer : CovarianceRegularizer or None, default=None
        Optional configuration applied to each empirical covariance.

    Returns
    -------
    GaussianMixture
        Independent mixture preserving empirical component order.

    Notes
    -----
    Construction raises ValueError if a covariance is not positive definite
    after any regularization.
    """
    return GaussianMixture(
        weights=self.weights,
        means=self.means,
        covariances=self.covariances
        if regularizer is None
        else regularize_covariance(self.covariances, regularizer=regularizer),
    )

Probability Validation

Categorical targets, candidate probability rows, and component responsibilities share the same validation policy: values must be finite and nonnegative, and sums must be one within rtol=1e-7, atol=1e-8. Inputs are copied without normalization or negative-value clipping. Categorical KL uses the same policy. Optimizer weight vectors retain their separate validation, which permits unnormalized nonnegative weights with positive total mass when evaluating gradients.

Objective Configuration

Sampled objectives accept sampling.Stratified on either side. Each observation from source component \(k\) receives its component probability divided by \(n_k\), the number of draws allocated to that component. For the target this is \(\pi_{p,k}/n_k\); for candidate \(i\) it is \(\pi_{i,k}/n_{i,k}\). These integration weights are distinct from the optimized candidate weights \(w_i\). Objective values and gradients therefore preserve the mixture weights even when rounded sample counts differ from the component proportions. Raw Draw, Samples, and SampleBatches observations use ordinary sample means. Precomputed SampleBatch records retain their integration weights and component IDs.

ForwardKL dataclass

ForwardKL(*, target_sampling: SampleSpec = Draw())

Forward KL fitting objective configuration.

Fits the candidate-mixture weights by minimizing

\[ D_{\mathrm{KL}}\!\left(p \,\|\, q_{\mathbf{w}}\right) = \mathbb{E}_{X \sim p} \left[ \log p(X) - \log q_{\mathbf{w}}(X) \right], \]

where \(p\) is the target density and \(q_{\mathbf{w}}=\sum_{i=1}^{L}w_iq_i\) combines \(L\) fixed candidate densities with nonnegative weights summing to one. \(X\) denotes a random observation from the first distribution. Since \(\log p(X)\) does not depend on \(\mathbf{w}\), its contribution is cached. Reported values include this constant and estimate KL in nats.

Parameters:

  • target_sampling (SampleSpec, default: Draw() ) –

    Source of fixed target observations. Draw defaults to 10000 samples; Samples reuses target observations; Stratified retains integration mass.

target_sampling class-attribute instance-attribute

target_sampling: SampleSpec = field(default_factory=Draw)

Sampling specification for the expectation under target.

Use sampling.Draw(...) to draw fresh samples, sampling.Samples(...) for precomputed reference samples, or sampling.Stratified(...) when p is a Gaussian-family distribution and fixed per-component counts are desired.

ReverseKL dataclass

ReverseKL(*, candidate_sampling: BatchSampleSpec = Draw())

Reverse KL fitting objective configuration.

Fits the candidate-mixture weights by minimizing

\[ D_{\mathrm{KL}}\!\left(q_{\mathbf{w}} \,\|\, p\right) = \mathbb{E}_{X \sim q_{\mathbf{w}}} \left[ \log q_{\mathbf{w}}(X) - \log p(X) \right]. \]

Here \(p\) is the target density and \(q_{\mathbf{w}}=\sum_{i=1}^{L}w_iq_i\) combines \(L\) fixed candidate densities with nonnegative weights summing to one. \(X\) is a random observation under the indicated distribution. The implementation evaluates a fixed-sample estimator using samples from each candidate mixture \(q_i\). The reference density \(p\) is evaluated at those samples, so no samples from \(p\) are required.

Parameters:

  • candidate_sampling (BatchSampleSpec, default: Draw() ) –

    Fixed batch per candidate. Draw defaults to 10000 observations per retained candidate. SampleBatches must cover every original candidate; filtering and reordering are applied to those batches during preparation.

candidate_sampling class-attribute instance-attribute

candidate_sampling: BatchSampleSpec = field(default_factory=Draw)

Sampling specification for fixed batches from each q_i.

Use sampling.Draw(...) to draw one batch per candidate distribution, sampling.Stratified(...) for fixed per-component counts, or sampling.SampleBatches(...) to provide those batches directly.

BidirectionalKL dataclass

BidirectionalKL(
    *,
    target_sampling: SampleSpec = Draw(),
    candidate_sampling: BatchSampleSpec = Draw(),
    forward_weight: float = 0.5,
)

Bidirectional KL fitting objective configuration.

Fits the candidate-mixture weights by minimizing a weighted combination of forward and reverse KL objectives:

\[ \beta\,D_{\mathrm{KL}}\!\left(p \,\|\, q_{\mathbf{w}}\right) + (1-\beta)\,D_{\mathrm{KL}}\!\left(q_{\mathbf{w}} \,\|\, p\right), \qquad \beta\in[0,1]. \]

Here \(p\) is the target density, \(q_{\mathbf{w}}=\sum_{i=1}^{L}w_iq_i\) is the combined candidate density, and \(\beta\) is forward_weight. Values of \(\beta\) closer to one emphasize coverage of \(p\) by \(q_{\mathbf{w}}\), while values closer to zero emphasize the reverse-KL objective.

Parameters:

  • target_sampling (SampleSpec, default: Draw() ) –

    Fixed observations from the target for the forward term. Not consumed when forward_weight is zero.

  • candidate_sampling (BatchSampleSpec, default: Draw() ) –

    Fixed batch per candidate for the reverse term. Precomputed batches cover original candidates. Not consumed when forward_weight is one.

  • forward_weight (float, default: 0.5 ) –

    Finite weight in [0, 1], represented by beta in the formula. The reverse term receives 1 - forward_weight.

candidate_sampling class-attribute instance-attribute

candidate_sampling: BatchSampleSpec = field(default_factory=Draw)

Sampling specification for the reverse term under each q_i.

Use sampling.Draw(...) to draw one batch per candidate distribution, sampling.Stratified(...) for fixed per-component counts, or sampling.SampleBatches(...) to provide those batches directly.

forward_weight class-attribute instance-attribute

forward_weight: float = 0.5

Weight assigned to the forward KL term.

target_sampling class-attribute instance-attribute

target_sampling: SampleSpec = field(default_factory=Draw)

Sampling specification for the forward term under p.

JensenShannon dataclass

JensenShannon(
    *,
    target_sampling: SampleSpec = Draw(),
    candidate_sampling: BatchSampleSpec = Draw(),
)

Jensen-Shannon fitting objective configuration.

Fits the candidate-mixture weights by minimizing

\[ D_{\mathrm{JS}}\!\left(p, q_{\mathbf{w}}\right) = \frac{1}{2}D_{\mathrm{KL}}\!\left(p \,\|\, m_{\mathbf{w}}\right) + \frac{1}{2}D_{\mathrm{KL}}\!\left(q_{\mathbf{w}} \,\|\, m_{\mathbf{w}}\right), \]

where

\[ m_{\mathbf{w}} = \frac{1}{2}p + \frac{1}{2}q_{\mathbf{w}}. \]

Here \(p\) is the target density and \(q_{\mathbf{w}}=\sum_{i=1}^{L}w_iq_i\) combines fixed candidate densities with nonnegative weights summing to one. The exact divergence is symmetric and bounded by \(\log 2\) nats. Fitting evaluates its sampled approximation using fixed observations from p and each candidate mixture q_i during optimization.

Parameters:

  • target_sampling (SampleSpec, default: Draw() ) –

    Fixed observations from the target for its midpoint-divergence term.

  • candidate_sampling (BatchSampleSpec, default: Draw() ) –

    Fixed batch per candidate for the fitted mixture's midpoint term. Precomputed batches cover every original candidate.

Notes

Values estimate divergence in nats, not its square-root distance. Finite samples may produce estimates outside the exact [0, log(2)] range.

candidate_sampling class-attribute instance-attribute

candidate_sampling: BatchSampleSpec = field(default_factory=Draw)

Sampling specification for fixed batches from each q_i.

Use sampling.Draw(...) to draw one batch per candidate distribution, sampling.Stratified(...) for fixed per-component counts, or sampling.SampleBatches(...) to provide those batches directly.

target_sampling class-attribute instance-attribute

target_sampling: SampleSpec = field(default_factory=Draw)

Sampling specification for the term under p.

MomentMatching dataclass

MomentMatching(*, fit_second_moments: bool = False)

Moment-matching fitting objective configuration.

Fits weights by matching moments of \(q_{\mathbf{w}}\) to moments of the reference distribution \(p\) instead of optimizing a sampled KL estimate. The first-moment objective compares mixture means,

\[ \left\|\mu_{q_{\mathbf{w}}} - \mu_p\right\|_2^2, \]

where \(\mu_p\) and \(\mu_{q_{\mathbf{w}}}\) are the aggregate means of target \(p\) and combined density \(q_{\mathbf{w}}=\sum_{i=1}^{L}w_iq_i\). With raw second moments \(M_{2,p}=\Sigma_p+\mu_p\mu_p^\top\) and \(M_{2,q_{\mathbf{w}}}=\Sigma_{q_{\mathbf{w}}} +\mu_{q_{\mathbf{w}}}\mu_{q_{\mathbf{w}}}^\top\), the optional objective is

\[ \|\mu_{q_{\mathbf{w}}}-\mu_p\|_2^2 +\|M_{2,q_{\mathbf{w}}}-M_{2,p}\|_{\mathrm{F}}^2. \]

Here \(\Sigma\) denotes aggregate covariance and the Frobenius norm squares and sums every matrix entry, matching the flattened array implementation.

Parameters:

  • fit_second_moments (bool, default: False ) –

    Include the flattened raw second moment covariance + outer(mean, mean) alongside the mean. These are raw moments, not covariances alone.

Notes

No samples are drawn. The value is the squared Euclidean residual of the concatenated raw moments; it is not a divergence in nats and depends on feature scale.

fit_second_moments class-attribute instance-attribute

fit_second_moments: bool = False

Whether to include raw second moments alongside the feature means.

Optimizer

Gaussian and categorical weight fitting use SLSQP directly on simplex-constrained weights. Use initial_weights to supply a warm start and min_weight to control the lower bound for each candidate weight.

SimplexSLSQP dataclass

SimplexSLSQP(
    *,
    tol: float = 1e-08,
    max_iterations: int = 1000,
    min_weight: float = 1e-12,
    initial_weights: ArrayLike | None = None,
)

SLSQP optimizer over simplex-constrained weights.

The optimizer works directly with the mixture weights \(\mathbf{w}\in\Delta_L\) for \(L\) retained candidates, where

\[ \Delta_L = \left\{ \mathbf{w}\in\mathbb{R}^{L}: w_i\geq0,\ \sum_{i=1}^{L}w_i=1 \right\}. \]

This keeps the optimization variables interpretable but requires the optimizer to enforce the simplex equality and bound constraints.

Parameters:

  • tol (float, default: 1e-8 ) –

    Finite, positive convergence tolerance passed to scipy.optimize.minimize.

  • max_iterations (int, default: 1000 ) –

    Positive iteration budget.

  • min_weight (float, default: 1e-12 ) –

    Finite, nonnegative lower bound per retained candidate. The product of min_weight and the number of retained candidates must not exceed one.

  • initial_weights (array - like or None, default: None ) –

    Finite, nonnegative 1D coefficients with positive total mass and one entry per retained candidate. Normalized at fitting time. None starts uniformly. Inputs are copied and made read-only.

initial_weights class-attribute instance-attribute

initial_weights: ArrayLike | None = None

Optional initial simplex weights for the active candidates.

max_iterations class-attribute instance-attribute

max_iterations: int = 1000

Maximum number of optimizer iterations.

min_weight class-attribute instance-attribute

min_weight: float = 1e-12

Lower bound for each retained candidate weight.

Ideally, this would be zero, but SLSQP can fail when weights are exactly zero. Setting it to small positive values avoids numerical issues while still allowing negligible candidate weights. This bound does not remove candidates or their Gaussian components from the fitted mixture.

tol class-attribute instance-attribute

tol: float = 1e-08

Optimizer convergence tolerance.

Prepared Gaussian Weight Fits

prepared.fit(optimizer=...) is the direct route to a complete result. prepared.evaluate(weights) returns the cached objective value and gradient. For an SLSQP warm start, use the previous result's weights at prepared.active_candidate_indices as initial_weights. Forward and bidirectional KL values include the cached target log-density constant, so objective_value estimates the mathematical objective in nats.

MomentMatching instead returns a squared raw-moment residual, without nats or sampling. See the objective formulations for the equations.

Gaussian results expose mixture directly. Its mapping refers to original candidate indices, including after filtering or reordering. Result weights include zero entries for rejected candidates. Categorical results expose read-only probabilities and use the fixed objective="forward_kl". Both result types provide optimizer, objective_value, converged, n_iterations, and message.

Precomputed candidate batches must contain one batch per original candidate. Preparation validates the full sequence, then selects batches alongside the retained candidates. Generated samples are drawn only from retained candidates.

prepare_gaussian_weight_fit

prepare_gaussian_weight_fit(
    target: Gaussian | GaussianMixture,
    candidates: Sequence[Gaussian | GaussianMixture],
    *,
    objective: FitObjective,
    candidate_selector: CandidateSelector | None = None,
) -> PreparedGaussianWeightFit

Prepare a reusable Gaussian-mixture weight-fitting objective.

Candidate selection, sampling, and density or moment calculations happen once during preparation. The returned object can evaluate gradients and run repeated optimizations without recomputing those inputs.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty candidate sequence with the same feature dimension as target.

  • objective (FitObjective) –

    Explicit fitting-objective configuration.

  • candidate_selector (CandidateSelector or None, default: None ) –

    Optional strategy applied once before sampling and caching densities. Precomputed candidate batches must cover all original candidates.

Returns:

Source code in src/gmm_divergence/fitting/_api.py
def prepare_gaussian_weight_fit(
    target: Gaussian | GaussianMixture,
    candidates: Sequence[Gaussian | GaussianMixture],
    *,
    objective: FitObjective,
    candidate_selector: CandidateSelector | None = None,
) -> PreparedGaussianWeightFit:
    """Prepare a reusable Gaussian-mixture weight-fitting objective.

    Candidate selection, sampling, and density or moment calculations happen
    once during preparation. The returned object can evaluate gradients and run
    repeated optimizations without recomputing those inputs.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty candidate sequence with the same feature dimension as target.
    objective : FitObjective
        Explicit fitting-objective configuration.
    candidate_selector : CandidateSelector or None, default=None
        Optional strategy applied once before sampling and caching densities.
        Precomputed candidate batches must cover all original candidates.

    Returns
    -------
    PreparedGaussianWeightFit
        Cached objective data with `fit` and `evaluate` methods.
    """
    return gaussian.prepare_gaussian_weight_fit(
        target=target,
        candidates=candidates,
        objective=objective,
        candidate_selection=candidate_selector,
    )

PreparedGaussianWeightFit dataclass

PreparedGaussianWeightFit(
    objective: FitObjective,
    active_candidates: tuple[Gaussian | GaussianMixture, ...],
    active_candidate_indices: tuple[int, ...],
    n_candidates: int,
    _objective_fn: ObjectiveFn,
)

Reusable data and objective for fitting mixture weights.

Preparation performs candidate selection, sampling, and all log-density or moment calculations required by the objective. Call :meth:fit any number of times without repeating that work, or inspect the objective and gradient with :meth:evaluate.

Notes

Obtain this object with fitting.prepare_gaussian_weight_fit. The target, objective configuration, selected candidates, and sample batches are fixed for its lifetime. Changing them requires a new preparation. Optimizer choices and initial conditions can change between fit calls.

active_candidate_indices instance-attribute

active_candidate_indices: tuple[int, ...]

Indices of active candidates in the original candidate sequence.

active_candidates instance-attribute

active_candidates: tuple[Gaussian | GaussianMixture, ...]

Candidate distributions retained for optimization.

n_active_candidates property

n_active_candidates: int

Number of candidates represented by the prepared objective.

n_candidates instance-attribute

n_candidates: int

Number of candidates in the original sequence.

objective instance-attribute

objective: FitObjective

Fitting-objective configuration used during preparation.

evaluate

evaluate(weights: ArrayLike) -> tuple[float, FloatArray]

Evaluate the cached objective and gradient at active weights.

The weights must be nonnegative and have a positive sum. They are not normalized, which permits finite-difference gradient checks around a simplex point.

Parameters:

  • weights ((array - like, shape(n_active_candidates))) –

    Finite, nonnegative weights with positive total mass in retained candidate order. Use unit total mass for the fitting objective.

Returns:

  • value ( float ) –

    Cached objective value. KL and Jensen-Shannon objectives use nats; MomentMatching returns a squared raw-moment residual.

  • gradient ( (ndarray, shape(n_active_candidates)) ) –

    Derivatives with respect to the supplied weights.

Source code in src/gmm_divergence/fitting/_gaussian.py
def evaluate(self, weights: npt.ArrayLike) -> tuple[float, FloatArray]:
    """Evaluate the cached objective and gradient at active weights.

    The weights must be nonnegative and have a positive sum. They are not
    normalized, which permits finite-difference gradient checks around a
    simplex point.

    Parameters
    ----------
    weights : array-like, shape (n_active_candidates,)
        Finite, nonnegative weights with positive total mass in retained
        candidate order. Use unit total mass for the fitting objective.

    Returns
    -------
    value : float
        Cached objective value. KL and Jensen-Shannon objectives use nats;
        MomentMatching returns a squared raw-moment residual.
    gradient : ndarray, shape (n_active_candidates,)
        Derivatives with respect to the supplied weights.
    """
    weights_arr = as_weights(
        weights, expected_length=self.n_active_candidates, name="weights", normalize=False
    )
    value, gradient = self._objective_fn(weights_arr)
    return float(value), np.asarray(gradient, dtype=np.float64)

fit

fit(*, optimizer: Optimizer) -> GaussianWeightFitResult

Optimize this cached problem and return a complete immutable result.

For a warm start, pass the previous result's weights at active_candidate_indices as SimplexSLSQP.initial_weights.

Parameters:

  • optimizer (Optimizer) –

    Explicit optimizer configuration. Initial vectors refer to retained candidates in active_candidate_indices order, not all candidates.

Returns:

  • GaussianWeightFitResult –

    Complete result with weights for the original candidate sequence, a combined mixture with provenance, and termination diagnostics. Rejected candidates receive zero weight.

Source code in src/gmm_divergence/fitting/_gaussian.py
def fit(self, *, optimizer: Optimizer) -> GaussianWeightFitResult:
    """Optimize this cached problem and return a complete immutable result.

    For a warm start, pass the previous result's weights at
    `active_candidate_indices` as `SimplexSLSQP.initial_weights`.

    Parameters
    ----------
    optimizer : Optimizer
        Explicit optimizer configuration. Initial vectors refer to retained
        candidates in active_candidate_indices order, not all candidates.

    Returns
    -------
    GaussianWeightFitResult
        Complete result with weights for the original candidate sequence,
        a combined mixture with provenance, and termination diagnostics.
        Rejected candidates receive zero weight.
    """
    solution = optimize_simplex(
        self._objective_fn, n_weights=self.n_active_candidates, optimizer=optimizer
    )
    return _build_fit_result(self, solution)

Fitting Results

GaussianWeightFitResult dataclass

GaussianWeightFitResult(
    *,
    weights: Weights,
    objective: FitObjective,
    optimizer: Optimizer,
    objective_value: float,
    mixture: GaussianMixture,
    converged: bool,
    n_iterations: int,
    message: str,
    active_candidate_indices: tuple[int, ...] = (),
)

Fitted candidate weights and a directly usable mixture with provenance.

active_candidate_indices class-attribute instance-attribute

active_candidate_indices: tuple[int, ...] = ()

Retained positions in their optimization order. Slice weights by these indices when constructing a warm start for the prepared problem.

converged instance-attribute

converged: bool

Whether the optimizer reported successful termination.

message instance-attribute

message: str

Optimizer termination explanation.

mixture instance-attribute

mixture: GaussianMixture

Combined fitted distribution. Its mapping identifies original candidate indices and component positions within those candidates.

n_iterations instance-attribute

n_iterations: int

Number of optimizer iterations.

objective instance-attribute

objective: FitObjective

Objective and sampling configuration used for preparation.

objective_value instance-attribute

objective_value: float

Final cached objective: KL or JS in nats, including target constants, or a squared raw-moment residual for MomentMatching.

optimizer instance-attribute

optimizer: Optimizer

Optimizer configuration, including any initial conditions.

weights instance-attribute

weights: Weights

Independent, read-only weights in original candidate order. Rejected candidates receive zero weight. Shape (n_candidates,).

candidate_weight_dict

candidate_weight_dict() -> dict[int, float]

Return weights keyed by original candidate index.

Returns:

  • dict –

    Candidate indices mapped to float weights, including zero weights. Insertion order follows candidate_weights(), descending by weight.

Source code in src/gmm_divergence/results.py
def candidate_weight_dict(self) -> dict[int, float]:
    """Return weights keyed by original candidate index.

    Returns
    -------
    dict
        Candidate indices mapped to float weights, including zero weights.
        Insertion order follows candidate_weights(), descending by weight.
    """
    return dict(self.candidate_weights())

candidate_weights

candidate_weights() -> list[tuple[int, float]]

List original candidate indices and weights in descending weight order.

Returns:

  • list of tuple –

    Index and weight pairs, including rejected candidates with zero weight. Ties preserve the original candidate order.

Source code in src/gmm_divergence/results.py
def candidate_weights(self) -> list[tuple[int, float]]:
    """List original candidate indices and weights in descending weight order.

    Returns
    -------
    list of tuple
        Index and weight pairs, including rejected candidates with zero
        weight. Ties preserve the original candidate order.
    """
    return sorted(enumerate(map(float, self.weights)), key=lambda item: -item[1])

CategoricalWeightFitResult dataclass

CategoricalWeightFitResult(
    *,
    weights: FloatArray,
    probabilities: FloatArray,
    optimizer: Optimizer,
    objective_value: float,
    converged: bool,
    n_iterations: int,
    message: str,
)

Categorical forward-KL fit with independently owned, read-only arrays.

converged instance-attribute

converged: bool

Whether the optimizer reported successful termination.

message instance-attribute

message: str

Optimizer termination explanation.

n_iterations instance-attribute

n_iterations: int

Number of optimizer iterations.

objective class-attribute instance-attribute

objective: Literal['forward_kl'] = field(default='forward_kl', init=False)

Always forward_kl; categorical fitting supports this objective only.

objective_value instance-attribute

objective_value: float

Exact forward KL from the target to fitted probabilities, in nats.

optimizer instance-attribute

optimizer: Optimizer

Optimizer configuration, including any initial conditions.

probabilities instance-attribute

probabilities: FloatArray

Weighted combination of candidate rows in original category order. Shape (n_categories,).

weights instance-attribute

weights: FloatArray

Simplex weights in original candidate-row order. Shape (n_candidates,).

Candidate Scoring and Selection

Choose an explicit scorer. ForwardKLScore evaluates \(D_{\mathrm{KL}}(p\|q_i)\); ReverseKLScore evaluates \(D_{\mathrm{KL}}(q_i\|p)\). When using Monte Carlo, their observations originate from the target and candidate, respectively. Reverse scoring accepts a reusable generated estimator or one estimator per original candidate. Precomputed reverse observations require the per-candidate form, preventing accidental reuse of target samples. BidirectionalKLScore configures both directions and their forward_weight. Ranking preserves input order for tied scores.

Writing \(\beta\) for forward_weight, bidirectional scores are \(\beta D_{\mathrm{KL}}(p\|q_i)+(1-\beta)D_{\mathrm{KL}}(q_i\|p)\), or the corresponding estimates. These are pairwise scores for selection; they do not equal divergence to the combined fitted density \(q_{\mathbf{w}}\).

import gmm_divergence as gd

target = gd.Gaussian.univariate()
candidates = [gd.Gaussian.univariate(10), gd.Gaussian.univariate(-4)]
scorer = gd.fitting.ReverseKLScore(
    estimators=[
        gd.divergence.MonteCarlo(sampling=gd.sampling.Samples([[10]])),
        gd.divergence.MonteCarlo(sampling=gd.sampling.Samples([[-4]])),
    ]
)
assert gd.fitting.score_candidates(target, candidates, scorer=scorer).tolist() == [50, 8]
selector = gd.fitting.TopKSelector(k=1, scorer=scorer)
fit = gd.fit_gaussian_weights(
    target,
    candidates,
    objective=gd.fitting.MomentMatching(),
    optimizer=gd.fitting.SimplexSLSQP(),
    candidate_selector=selector,
)
assert fit.active_candidate_indices == (1,)

Custom scorers implement CandidateScorer.score(target, candidates) and custom selectors implement CandidateSelector.select(target, candidates), returning a complete selected/rejected partition of the original indices.

ForwardKLScore dataclass

ForwardKLScore(*, estimator: KLEstimator)

Score directed KL from the target to each candidate.

Parameters:

  • estimator (KLEstimator) –

    Estimator configuration reused for every target-to-candidate call. Precomputed observations must come from the target. Generated observations follow the configured random stream semantics on each call.

score

score(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray

Evaluate target-to-candidate KL with the configured estimator.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Original candidate sequence with the same feature dimension as target.

Returns:

  • (ndarray, shape(n_candidates)) –

    One score per original candidate in input order. Lower scores are preferred.

Source code in src/gmm_divergence/fitting/_selector.py
def score(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray:
    """Evaluate target-to-candidate KL with the configured estimator.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Original candidate sequence with the same feature dimension as target.

    Returns
    -------
    ndarray, shape (n_candidates,)
        One score per original candidate in input order. Lower scores are preferred.
    """
    return np.array([
        kl_divergence(target, candidate, estimator=self.estimator).value
        for candidate in candidates
    ])

ReverseKLScore dataclass

ReverseKLScore(*, estimators: KLEstimator | Sequence[KLEstimator])

Score directed KL from each candidate to the target.

Parameters:

  • estimators (KLEstimator or sequence of KLEstimator) –

    Reusable estimator configuration, or one estimator per original candidate in input order. MonteCarlo with precomputed Samples requires the sequence form so each batch originates from its own candidate. Generated estimators may be reused; generator state advances as candidates are scored.

score

score(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray

Evaluate candidate-to-target KL with candidate-specific sources.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Original candidate sequence with the same feature dimension as target.

Returns:

  • (ndarray, shape(n_candidates)) –

    One score per original candidate in input order. Lower scores are preferred.

Source code in src/gmm_divergence/fitting/_selector.py
def score(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray:
    """Evaluate candidate-to-target KL with candidate-specific sources.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Original candidate sequence with the same feature dimension as target.

    Returns
    -------
    ndarray, shape (n_candidates,)
        One score per original candidate in input order. Lower scores are preferred.
    """
    estimators = self.estimators
    if isinstance(estimators, Sequence):
        if len(estimators) != len(candidates):
            msg = "estimators must contain one estimator per original candidate."
            raise ValueError(msg)
    else:
        estimators = (estimators,) * len(candidates)
    return np.array([
        kl_divergence(candidate, target, estimator=estimator).value
        for candidate, estimator in zip(candidates, estimators, strict=True)
    ])

BidirectionalKLScore dataclass

BidirectionalKLScore(
    *,
    forward: CandidateScorer,
    reverse: CandidateScorer,
    forward_weight: float = 0.5,
)

Combine forward and reverse scores with separate sample sources.

Parameters:

  • forward (CandidateScorer) –

    Forward scorer, normally ForwardKLScore with target observations.

  • reverse (CandidateScorer) –

    Reverse scorer, normally ReverseKLScore with candidate observations.

  • forward_weight (float, default: 0.5 ) –

    Finite weight in [0, 1]. Reverse scores receive 1 - forward_weight. At either endpoint, only the nonzero-weight scorer is evaluated.

score

score(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray

Evaluate the weighted combination of directional scores.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Original candidate sequence with the same feature dimension as target.

Returns:

  • (ndarray, shape(n_candidates)) –

    One score per original candidate in input order. Lower scores are preferred.

Source code in src/gmm_divergence/fitting/_selector.py
def score(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray:
    """Evaluate the weighted combination of directional scores.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Original candidate sequence with the same feature dimension as target.

    Returns
    -------
    ndarray, shape (n_candidates,)
        One score per original candidate in input order. Lower scores are preferred.
    """
    if self.forward_weight == 1:
        return score_candidates(target, candidates, scorer=self.forward)
    if self.forward_weight == 0:
        return score_candidates(target, candidates, scorer=self.reverse)
    return self.forward_weight * score_candidates(target, candidates, scorer=self.forward) + (
        1 - self.forward_weight
    ) * score_candidates(target, candidates, scorer=self.reverse)

CandidateScorer

Bases: Protocol

Custom scoring over the entire original candidate sequence.

score

score(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray

Assign scores to the original candidate sequence.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Original candidate sequence with the same feature dimension as target.

Returns:

  • (ndarray, shape(n_candidates)) –

    One score per original candidate in input order. Lower scores are preferred.

Source code in src/gmm_divergence/fitting/_selector.py
def score(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> FloatArray:
    """Assign scores to the original candidate sequence.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Original candidate sequence with the same feature dimension as target.

    Returns
    -------
    ndarray, shape (n_candidates,)
        One score per original candidate in input order. Lower scores are preferred.
    """
    ...

CandidateSelector

Bases: Protocol

Protocol for filtering candidate distributions during fitting.

select

select(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection

Select candidates for a fixed target.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty original sequence sharing the target's feature dimension.

Returns:

  • CandidateSelection –

    Selected and rejected indices forming a complete, non-overlapping partition of the original sequence. Selected order controls fitting order.

Source code in src/gmm_divergence/fitting/_selector.py
def select(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection:
    """Select candidates for a fixed target.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty original sequence sharing the target's feature dimension.

    Returns
    -------
    CandidateSelection
        Selected and rejected indices forming a complete, non-overlapping
        partition of the original sequence. Selected order controls fitting order.
    """
    ...

CandidateSelection dataclass

CandidateSelection(
    selected_indices: tuple[int, ...],
    rejected_indices: tuple[int, ...],
    scores: FloatArray | None = None,
)

Selected and rejected positions in the original candidate sequence.

Parameters:

  • selected_indices (tuple of int) –

    Retained positions, in the order used for fitting. Fitting requires at least one retained candidate.

  • rejected_indices (tuple of int) –

    Rejected positions. Together with selected_indices, must partition the original candidate sequence without overlap when used in fitting.

  • scores (array - like or None, default: None ) –

    Optional scores in original candidate order, copied into a read-only float64 array. Built-in selectors supply one score per candidate.

Optimizer module-attribute

Optimizer: TypeAlias = SimplexSLSQP

FitObjective module-attribute

FitObjective: TypeAlias = (
    ForwardKL | ReverseKL | BidirectionalKL | JensenShannon | MomentMatching
)

score_candidates

score_candidates(
    target: GaussianDistribution,
    candidates: Sequence[GaussianDistribution],
    *,
    scorer: CandidateScorer,
) -> FloatArray

Compute scores for the original candidate sequence.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty candidate sequence sharing the target's feature dimension.

  • scorer (CandidateScorer) –

    Configuration or custom scorer implementing score(target, candidates). It must return one non-NaN score per candidate; infinite scores are allowed.

Returns:

  • (ndarray, shape(n_candidates)) –

    Independent, read-only float64 scores in original input order.

Source code in src/gmm_divergence/fitting/_selector.py
def score_candidates(
    target: GaussianDistribution,
    candidates: Sequence[GaussianDistribution],
    *,
    scorer: CandidateScorer,
) -> FloatArray:
    """Compute scores for the original candidate sequence.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty candidate sequence sharing the target's feature dimension.
    scorer : CandidateScorer
        Configuration or custom scorer implementing score(target, candidates).
        It must return one non-NaN score per candidate; infinite scores are allowed.

    Returns
    -------
    ndarray, shape (n_candidates,)
        Independent, read-only float64 scores in original input order.
    """
    if not candidates:
        msg = "candidates must contain at least one distribution."
        raise ValueError(msg)
    if any(candidate.n_features != target.n_features for candidate in candidates):
        msg = "candidates must have the same n_features as target."
        raise ValueError(msg)
    _validate_scorer(scorer)
    scores = readonly_copy(scorer.score(target, candidates), dtype=np.float64)
    if scores.shape != (len(candidates),) or np.any(np.isnan(scores)):
        msg = "scorer must return one non-NaN score per candidate."
        raise ValueError(msg)
    return scores

rank_candidates

rank_candidates(
    target: GaussianDistribution,
    candidates: Sequence[GaussianDistribution],
    *,
    scorer: CandidateScorer,
    limit: int | None = None,
) -> list[tuple[int, float]]

Rank candidates from lowest score to highest with stable ties.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty candidate sequence sharing the target's feature dimension.

  • scorer (CandidateScorer) –

    Explicit scoring configuration or custom scorer; lower scores are preferred.

  • limit (int or None, default: None ) –

    Positive maximum number of entries to return. None returns all candidates; values above the candidate count also return all entries.

Returns:

  • list of tuple –

    Original candidate indices and float scores in ascending score order. Equal scores retain original candidate order.

Source code in src/gmm_divergence/fitting/_selector.py
def rank_candidates(
    target: GaussianDistribution,
    candidates: Sequence[GaussianDistribution],
    *,
    scorer: CandidateScorer,
    limit: int | None = None,
) -> list[tuple[int, float]]:
    """Rank candidates from lowest score to highest with stable ties.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty candidate sequence sharing the target's feature dimension.
    scorer : CandidateScorer
        Explicit scoring configuration or custom scorer; lower scores are preferred.
    limit : int or None, default=None
        Positive maximum number of entries to return. None returns all candidates;
        values above the candidate count also return all entries.

    Returns
    -------
    list of tuple
        Original candidate indices and float scores in ascending score order.
        Equal scores retain original candidate order.
    """
    if limit is not None:
        limit = validate_positive_int(limit, name="limit")
    scores = score_candidates(target, candidates, scorer=scorer)
    indices = np.argsort(scores, kind="stable")
    return [(int(index), float(scores[index])) for index in indices[:limit]]

TopKSelector dataclass

TopKSelector(*, scorer: CandidateScorer, k: int)

Bases: _KLSelectorBase

Retain up to k candidates with the lowest scores.

Parameters:

  • scorer (CandidateScorer) –

    Explicit scoring configuration; lower scores are preferred.

  • k (int) –

    Positive maximum number to retain. Values above the candidate count retain all candidates. Ties favor earlier input positions. Retained indices are returned in original input order rather than score order.

select

select(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection

Partition candidates using the configured score rule.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty original sequence sharing the target's feature dimension.

Returns:

  • CandidateSelection –

    Selected and rejected indices, each in original input order, with an independent read-only score array for all original candidates.

Source code in src/gmm_divergence/fitting/_selector.py
@override
def select(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection:
    """Partition candidates using the configured score rule.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty original sequence sharing the target's feature dimension.

    Returns
    -------
    CandidateSelection
        Selected and rejected indices, each in original input order, with an
        independent read-only score array for all original candidates.
    """
    kl_values = self._compute_kl_values(target, candidates)
    mask = self._select_mask(kl_values)
    return CandidateSelection(
        selected_indices=tuple(int(index) for index in np.flatnonzero(mask)),
        rejected_indices=tuple(int(index) for index in np.flatnonzero(~mask)),
        scores=kl_values,
    )

ThresholdSelector dataclass

ThresholdSelector(*, scorer: CandidateScorer, threshold: float)

Bases: _KLSelectorBase

Retain candidates with scores at or below a fixed threshold.

Parameters:

  • scorer (CandidateScorer) –

    Explicit scoring configuration; lower scores are preferred.

  • threshold (float) –

    Finite, nonnegative upper score threshold, inclusive. Selection may be empty; fitting rejects a selection retaining no candidates.

select

select(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection

Partition candidates using the configured score rule.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty original sequence sharing the target's feature dimension.

Returns:

  • CandidateSelection –

    Selected and rejected indices, each in original input order, with an independent read-only score array for all original candidates.

Source code in src/gmm_divergence/fitting/_selector.py
@override
def select(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection:
    """Partition candidates using the configured score rule.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty original sequence sharing the target's feature dimension.

    Returns
    -------
    CandidateSelection
        Selected and rejected indices, each in original input order, with an
        independent read-only score array for all original candidates.
    """
    kl_values = self._compute_kl_values(target, candidates)
    mask = self._select_mask(kl_values)
    return CandidateSelection(
        selected_indices=tuple(int(index) for index in np.flatnonzero(mask)),
        rejected_indices=tuple(int(index) for index in np.flatnonzero(~mask)),
        scores=kl_values,
    )

ToleranceSelector dataclass

ToleranceSelector(
    *,
    scorer: CandidateScorer,
    delta: float,
    mode: Literal["absolute", "relative"] = "absolute",
)

Bases: _KLSelectorBase

Retain candidates within a tolerance of the minimum score.

Parameters:

  • scorer (CandidateScorer) –

    Explicit scoring configuration; lower scores are preferred.

  • delta (float) –

    Finite, nonnegative tolerance amount.

  • mode (('absolute', 'relative'), default: "absolute" ) –

    Absolute mode retains scores at most minimum_score + delta. Relative mode uses minimum_score + delta * abs(minimum_score), including for negative estimates. A zero minimum gives zero relative tolerance.

select

select(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection

Partition candidates using the configured score rule.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty original sequence sharing the target's feature dimension.

Returns:

  • CandidateSelection –

    Selected and rejected indices, each in original input order, with an independent read-only score array for all original candidates.

Source code in src/gmm_divergence/fitting/_selector.py
@override
def select(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection:
    """Partition candidates using the configured score rule.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty original sequence sharing the target's feature dimension.

    Returns
    -------
    CandidateSelection
        Selected and rejected indices, each in original input order, with an
        independent read-only score array for all original candidates.
    """
    kl_values = self._compute_kl_values(target, candidates)
    mask = self._select_mask(kl_values)
    return CandidateSelection(
        selected_indices=tuple(int(index) for index in np.flatnonzero(mask)),
        rejected_indices=tuple(int(index) for index in np.flatnonzero(~mask)),
        scores=kl_values,
    )

QuantileSelector dataclass

QuantileSelector(*, scorer: CandidateScorer, quantile: float)

Bases: _KLSelectorBase

Retain candidates at or below an interpolated score quantile.

Parameters:

  • scorer (CandidateScorer) –

    Explicit scoring configuration; lower scores are preferred.

  • quantile (float) –

    Finite quantile strictly between zero and one, passed to numpy.quantile. Ties are included, so the retained count need not equal this fraction of the candidate count.

select

select(
    target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection

Partition candidates using the configured score rule.

Parameters:

  • target (Gaussian or GaussianMixture) –

    Reference distribution.

  • candidates (sequence of Gaussian or GaussianMixture) –

    Nonempty original sequence sharing the target's feature dimension.

Returns:

  • CandidateSelection –

    Selected and rejected indices, each in original input order, with an independent read-only score array for all original candidates.

Source code in src/gmm_divergence/fitting/_selector.py
@override
def select(
    self, target: GaussianDistribution, candidates: Sequence[GaussianDistribution]
) -> CandidateSelection:
    """Partition candidates using the configured score rule.

    Parameters
    ----------
    target : Gaussian or GaussianMixture
        Reference distribution.
    candidates : sequence of Gaussian or GaussianMixture
        Nonempty original sequence sharing the target's feature dimension.

    Returns
    -------
    CandidateSelection
        Selected and rejected indices, each in original input order, with an
        independent read-only score array for all original candidates.
    """
    kl_values = self._compute_kl_values(target, candidates)
    mask = self._select_mask(kl_values)
    return CandidateSelection(
        selected_indices=tuple(int(index) for index in np.flatnonzero(mask)),
        rejected_indices=tuple(int(index) for index in np.flatnonzero(~mask)),
        scores=kl_values,
    )