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
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
responsibilitiesormixturemust be provided. -
mixture(GaussianMixture, default:None) –Reference mixture used to compute responsibilities without refitting.
Returns:
-
ComponentStatistics–Independent, read-only
weights,means,covariances,soft_counts, andeffective_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
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
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
¶
Weighted maximum-likelihood covariances, which may be singular. Shape (n_components, n_features, n_features).
effective_sample_sizes
instance-attribute
¶
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
¶
Responsibility-weighted empirical means. Shape (n_components, n_features).
soft_counts
instance-attribute
¶
Sum of responsibilities for each component. Shape (n_components,).
weights
instance-attribute
¶
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
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
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
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:
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
¶
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
where
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
¶
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,
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
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
¶
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
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
¶
Optional initial simplex weights for the active candidates.
max_iterations
class-attribute
instance-attribute
¶
Maximum number of optimizer iterations.
min_weight
class-attribute
instance-attribute
¶
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.
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:
-
PreparedGaussianWeightFit–Cached objective data with
fitandevaluatemethods.
Source code in src/gmm_divergence/fitting/_api.py
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
¶
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
¶
Number of candidates represented by the prepared objective.
objective
instance-attribute
¶
objective: FitObjective
Fitting-objective configuration used during preparation.
evaluate
¶
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
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
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
¶
Retained positions in their optimization order. Slice weights by these indices when constructing a warm start for the prepared problem.
converged
instance-attribute
¶
Whether the optimizer reported successful termination.
mixture
instance-attribute
¶
mixture: GaussianMixture
Combined fitted distribution. Its mapping identifies original candidate indices and component positions within those candidates.
objective
instance-attribute
¶
objective: FitObjective
Objective and sampling configuration used for preparation.
objective_value
instance-attribute
¶
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
¶
Independent, read-only weights in original candidate order. Rejected candidates receive zero weight. Shape (n_candidates,).
candidate_weight_dict
¶
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
candidate_weights
¶
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
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
¶
Whether the optimizer reported successful termination.
objective
class-attribute
instance-attribute
¶
Always forward_kl; categorical fitting supports this objective only.
objective_value
instance-attribute
¶
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
¶
Weighted combination of candidate rows in original category order. Shape (n_categories,).
weights
instance-attribute
¶
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
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
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
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
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
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.
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
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
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
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
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
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.