Top-level API¶
The top-level gmm_divergence namespace is intentionally small. It exposes the
classes and functions most users reach for first, plus namespace modules for
configuration objects.
What Lives At The Root¶
| Symbol | Purpose |
|---|---|
Gaussian, GaussianMixture |
Core Gaussian-family classes |
combine_distributions |
Build a combined Gaussian mixture |
kl_divergence, categorical_kl_divergence, symmetric_kl_divergence, jensen_shannon_divergence |
Main divergence helpers |
component_kl_matrix |
Pairwise component KL diagnostics |
aligned_joint_kl_divergence |
Joint KL for aligned component labels and observations |
fit_gaussian_weights, fit_categorical_weights, prune_mixture |
Main fitting helpers |
DivergenceResult, GaussianWeightFitResult, CategoricalWeightFitResult |
Result containers |
What Lives In Namespaces¶
Configuration and specialized helpers are grouped by namespace:
| Namespace | Contains |
|---|---|
gmm_divergence.divergence |
Estimator configuration such as MonteCarlo |
gmm_divergence.fitting |
Prepared fits, objectives, optimizers, and candidate selectors |
gmm_divergence.sampling |
Sampling specifications such as Draw and Samples |
gmm_divergence.covariance |
Covariance regularizers and epsilon heuristics |
gmm_divergence.distributions |
Gaussian-family details and combination metadata |
Example¶
import gmm_divergence as gd
p = gd.Gaussian.univariate(mean=0.0, variance=1.0)
q = gd.Gaussian.univariate(mean=1.0, variance=2.0)
estimator = gd.divergence.MonteCarlo(sampling=gd.sampling.Draw(n_samples=50_000, rng=0))
result = gd.kl_divergence(p, q, estimator=estimator)
The sections below document the root exports explicitly. Namespace-only configuration objects are documented on their namespace pages.
Distributions¶
Gaussian
dataclass
¶
Gaussian(
mean: ArrayLike,
covariance: ArrayLike,
*,
regularizer: CovarianceRegularizer | None = None,
)
Gaussian with mean (n_features,) and positive-definite covariance.
Array-like inputs are copied into read-only float64 arrays. An optional regularizer is applied before validating positive definiteness.
Parameters:
-
mean((array - like, shape(n_features))) –Nonempty, finite feature means.
-
covariance((array - like, shape(n_features, n_features))) –Finite, symmetric covariance. Must be positive definite after any regularization.
-
regularizer(CovarianceRegularizer or None, default:None) –Optional covariance regularization applied before construction.
Source code in src/gmm_divergence/distributions/_gaussian.py
cholesky
¶
Return the cached, read-only lower covariance factor, shape (n_features, n_features).
Source code in src/gmm_divergence/distributions/_gaussian.py
component_arrays
¶
Return weight, mean, and covariance arrays for one Gaussian component.
Shapes are (1,), (1, n_features), and (1, n_features, n_features).
The weight array is newly allocated; the other arrays are read-only views of this Gaussian's parameters.
Source code in src/gmm_divergence/distributions/_gaussian.py
from_samples
classmethod
¶
from_samples(
samples: ArrayLike, *, regularizer: CovarianceRegularizer | None = None
) -> Gaussian
Estimate a Gaussian from finite observations (n_samples, n_features).
At least two observations are required. Covariance uses the unbiased
estimate (divisor n_samples - 1). Singular covariance requires an
explicit regularizer.
Parameters:
-
samples((array - like, shape(n_samples, n_features))) –Finite observations with at least two rows and one feature. For one feature, provide a column matrix rather than a 1D vector.
-
regularizer(CovarianceRegularizer or None, default:None) –Optional regularization for the empirical covariance.
Returns:
-
Gaussian–Distribution with the sample mean and unbiased sample covariance.
Source code in src/gmm_divergence/distributions/_gaussian.py
isotropic
classmethod
¶
isotropic(mean: ArrayLike, *, variance: float = 1.0) -> Gaussian
Create a Gaussian with the same variance along every feature.
Parameters:
-
mean((array - like, shape(n_features))) –Nonempty, finite feature means.
-
variance(float, default:1.0) –Finite, strictly positive variance; covariance is
variance * I.
Returns:
-
Gaussian–Gaussian with independent features and equal marginal variances.
Source code in src/gmm_divergence/distributions/_gaussian.py
log_determinant
¶
Return the cached natural logarithm of the covariance determinant.
Source code in src/gmm_divergence/distributions/_gaussian.py
logpdf
¶
Evaluate natural-log densities at one or more points.
Parameters:
-
x((array - like, shape(n_features) or (n_points, n_features))) –Finite observations. A 1D input represents one observation.
Returns:
-
(ndarray, shape(n_points))–Log densities, including a length-one array for a single point.
Source code in src/gmm_divergence/distributions/_gaussian.py
pdf
¶
Evaluate densities at one or more points.
Parameters:
-
x((array - like, shape(n_features) or (n_points, n_features))) –Finite observations. A 1D input represents one observation.
Returns:
-
(ndarray, shape(n_points))–Densities, including a length-one array for a single point.
Source code in src/gmm_divergence/distributions/_gaussian.py
sample
¶
Draw independent observations from this Gaussian.
Parameters:
-
n_samples(int) –Positive number of observations to draw.
-
rng(numpy.random.Generator, int, or None, default:None) –Random source. An integer restarts a reproducible stream on each call; a generator advances its state. None uses fresh entropy.
Returns:
-
(ndarray, shape(n_samples, n_features))–Newly allocated float64 observations.
Source code in src/gmm_divergence/distributions/_gaussian.py
standard
classmethod
¶
standard(n_features: int) -> Gaussian
Create a zero-mean Gaussian with identity covariance.
Parameters:
-
n_features(int) –Positive number of features.
Returns:
-
Gaussian–Standard multivariate Gaussian of the requested dimension.
Source code in src/gmm_divergence/distributions/_gaussian.py
univariate
classmethod
¶
univariate(mean: float = 0.0, variance: float = 1.0) -> Gaussian
Create a one-feature Gaussian from mean and variance.
Parameters:
-
mean(float, default:0.0) –Finite feature mean.
-
variance(float, default:1.0) –Finite, strictly positive feature variance.
Returns:
-
Gaussian–Gaussian with one feature.
Source code in src/gmm_divergence/distributions/_gaussian.py
GaussianMixture
dataclass
¶
GaussianMixture(
weights: ArrayLike,
means: ArrayLike,
covariances: ArrayLike,
*,
regularizer: CovarianceRegularizer | None = None,
mapping: MixtureMapping | None = None,
)
Immutable mixture of full-covariance Gaussian components.
Parameters:
-
weights((array - like, shape(n_components))) –Finite, nonnegative coefficients with positive total mass. Normalized to sum to one; zero-weight components are retained.
-
means((array - like, shape(n_components, n_features))) –Finite component means, with at least one component and feature.
-
covariances((array - like, shape(n_components, n_features, n_features))) –Finite, symmetric component covariances. Each must be positive definite after any regularization.
-
regularizer(CovarianceRegularizer or None, default:None) –Optional regularization applied to component covariances.
-
mapping(MixtureMapping or None, default:None) –Optional provenance with one row per component.
Notes
Parameter arrays are copied and made read-only. means and covariances
describe components; mean and covariance describe the full mixture.
Source code in src/gmm_divergence/distributions/_mixture.py
covariance
property
¶
Aggregate covariance, shape (n_features, n_features), read-only.
covariances
instance-attribute
¶
Covariance array of shape (n_components, n_features, n_features).
mapping
class-attribute
instance-attribute
¶
mapping: MixtureMapping | None = None
Optional immediate-source provenance, one row per flattened component.
mean
property
¶
Aggregate mean, shape (n_features,), independently owned and read-only.
as_gaussian
¶
as_gaussian() -> Gaussian
Convert an exactly single-component mixture to a Gaussian.
Returns:
-
Gaussian–Exact distribution with copied component parameters.
Raises:
-
ValueError–If the mixture has multiple components. Use
moment_matchfor an approximation in that case.
Source code in src/gmm_divergence/distributions/_mixture.py
cholesky
¶
Return cached, read-only lower factors, shape (n_components, d, d).
Source code in src/gmm_divergence/distributions/_mixture.py
component_arrays
¶
Return read-only weight, mean, and covariance parameter arrays.
Shapes are (n_components,), (n_components, n_features), and
(n_components, n_features, n_features). These are the stored arrays,
not copies or aggregate moments.
Source code in src/gmm_divergence/distributions/_mixture.py
diagnostics
¶
diagnostics() -> MixtureDiagnostics
Summarize component weights and covariance conditioning.
Returns:
-
MixtureDiagnostics–Component and feature counts, weight sum and extrema, weight entropy in nats, and independent read-only per-component condition numbers.
Source code in src/gmm_divergence/distributions/_mixture.py
from_components
classmethod
¶
from_components(
components: Sequence[Gaussian], *, weights: ArrayLike | None = None
) -> GaussianMixture
Create a mixture from fixed Gaussian components.
Parameters:
-
components(sequence of Gaussian) –Nonempty sequence of components with equal feature dimensions.
-
weights(array-like, shape (n_components,), or None, default:None) –Finite, nonnegative coefficients with positive total mass. They are normalized; None assigns equal component weights.
Returns:
-
GaussianMixture–Independent mixture preserving the supplied component order.
Source code in src/gmm_divergence/distributions/_mixture.py
from_sklearn
classmethod
¶
from_sklearn(gmm: GaussianMixture) -> GaussianMixture
Convert a fitted scikit-learn mixture to full covariance matrices.
Parameters:
-
gmm(GaussianMixture) –Fitted estimator using full, tied, diagonal, or spherical covariance.
Returns:
-
GaussianMixture–Independent distribution with the same component order and weights.
Raises:
-
ValueError–If the estimator is unfitted or its covariance type is unsupported.
Source code in src/gmm_divergence/distributions/_mixture.py
get_component
¶
get_component(index: int) -> Gaussian
Return a Gaussian component independently of the mixture.
Parameters:
-
index(int) –Component position in
[0, n_components). Negative indices and booleans are not accepted.
Returns:
-
Gaussian–Gaussian with copied parameters from the requested component.
Notes
Index validation raises TypeError for noninteger positions and IndexError for positions outside the component range.
Source code in src/gmm_divergence/distributions/_mixture.py
log_determinants
¶
Return cached covariance log-determinants, shape (n_components,).
The returned float64 array is read-only and uses natural logarithms.
Source code in src/gmm_divergence/distributions/_mixture.py
logpdf
¶
Evaluate natural-log mixture densities at one or more points.
Parameters:
-
x((array - like, shape(n_features) or (n_points, n_features))) –Finite observations. A 1D input represents one observation.
Returns:
-
(ndarray, shape(n_points))–Log densities, including a length-one array for a single point.
Source code in src/gmm_divergence/distributions/_mixture.py
moment_match
¶
moment_match() -> Gaussian
Approximate the mixture with a Gaussian sharing its aggregate moments.
Returns:
-
Gaussian–Gaussian with the mixture mean and covariance, including the covariance contributed by differences between component means.
Source code in src/gmm_divergence/distributions/_mixture.py
pdf
¶
Evaluate mixture densities at one or more points.
Parameters:
-
x((array - like, shape(n_features) or (n_points, n_features))) –Finite observations. A 1D input represents one observation.
Returns:
-
(ndarray, shape(n_points))–Densities, including a length-one array for a single point.
Source code in src/gmm_divergence/distributions/_mixture.py
responsibilities
¶
Compute the responsibilities of each component for the given points.
Parameters:
-
x((array - like, shape(n_features) or (n_samples, n_features))) –Finite points at which to compute responsibilities. A 1D input represents one observation.
Returns:
-
responsibilities((array, shape(n_samples, n_components))) –The responsibilities of each component for each point, normalized to sum to 1 across components.
Source code in src/gmm_divergence/distributions/_mixture.py
sample
¶
Draw independent observations from the mixture.
Parameters:
-
n_samples(int) –Positive number of observations to draw.
-
rng(numpy.random.Generator, int, or None, default:None) –Random source. An integer restarts a reproducible stream on each call; a generator advances its state. None uses fresh entropy.
Returns:
-
(ndarray, shape(n_samples, n_features))–Newly allocated float64 observations in random component order.
Source code in src/gmm_divergence/distributions/_mixture.py
select_components
¶
select_components(indices: ArrayLike) -> GaussianMixture
Select components in the requested order and normalize their weights.
Parameters:
-
indices((array - like, shape(n_selected))) –Nonempty vector of integer positions in
[0, n_components). Repeated positions are allowed. Selected weights must have positive total mass.
Returns:
-
GaussianMixture–Independent mixture in the requested order, retaining mapping rows.
Raises:
-
IndexError–If a component position is out of range.
Notes
Input validation raises TypeError for a noninteger dtype and ValueError for an invalid index shape or zero selected mass.
Source code in src/gmm_divergence/distributions/_mixture.py
to_sklearn
¶
Convert to a sklearn mixture ready for evaluation and sampling.
Parameters are copied without fitting data. Optimization history and convergence diagnostics are unavailable because no fitting is performed.
Returns:
-
GaussianMixture–Estimator with independent parameter arrays and full covariances. Mixture provenance is not transferred.
Source code in src/gmm_divergence/distributions/_mixture.py
combine_distributions
¶
combine_distributions(
sources: Sequence[GaussianDistribution], *, weights: ArrayLike | None = None
) -> GaussianMixture
Combine fixed distributions with nonnegative source weights.
Coefficients are normalized; omitted weights give equal source mass. The returned mixture works directly with divergence and fitting APIs. Its mapping identifies immediate source indices and local component indices, even when an input source already carries provenance.
Parameters:
-
sources(sequence of Gaussian or GaussianMixture) –Nonempty sequence of distributions with the same number of features. Components are flattened in source order, then local component order.
-
weights(array-like, shape (n_sources,), or None, default:None) –Finite, nonnegative source coefficients with positive total mass. Coefficients are normalized; None assigns equal mass to each source.
Returns:
-
GaussianMixture–Combined distribution with independent, read-only parameter arrays and a mapping to the immediate sources. Zero-weight components remain.
Source code in src/gmm_divergence/distributions/_combine.py
Divergence Helpers¶
categorical_kl_divergence
¶
categorical_kl_divergence(
p: ArrayLike, q: ArrayLike, *, epsilon: float = 0.0
) -> DivergenceResult
Compute directed categorical KL between probability vectors over shared categories.
For probability vectors \(\boldsymbol{\pi}_p\) and \(\boldsymbol{\pi}_q\) over \(K\) shared categories, the exact quantity is
Parameters:
-
p(array - like) –Nonempty, finite, nonnegative probability vectors of equal length, each summing to one. Index
kmust represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked withrtol=1e-7,atol=1e-8; negative values are rejected without clipping. -
q(array - like) –Nonempty, finite, nonnegative probability vectors of equal length, each summing to one. Index
kmust represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked withrtol=1e-7,atol=1e-8; negative values are rejected without clipping. -
epsilon(float, default:0.0) –Finite, nonnegative additive smoothing amount. For
Kcategories, each vector becomes(probabilities + epsilon) / (1 + K * epsilon). Smoothing changes the probability distributions being compared.
Returns:
-
DivergenceResult–Categorical \(D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)\) in nats with divergence
"categorical_kl". The vectors are the supplied p and q probabilities, after smoothing if requested. Without smoothing, a positive reference probability paired with a zero comparison probability gives positive infinity.
Notes
Categories may represent mode occupancies or any other shared outcomes. When comparing Gaussian mixture weights, the caller must align components; independently fitted mixtures may order components differently, and components need not represent distinct modes. Inputs are not modified.
Source code in src/gmm_divergence/divergence/_api.py
kl_divergence
¶
kl_divergence(
p: GaussianDistribution, q: GaussianDistribution, *, estimator: KLEstimator
) -> DivergenceResult
Compute the directed Kullback-Leibler divergence \(D_{\mathrm{KL}}(p \| q)\).
Computes
The estimator is always explicit: it is never replaced automatically when
the inputs happen to be Gaussian. Select :class:ClosedForm for an exact
Gaussian-to-Gaussian result, or a sampled or approximate estimator for
mixtures.
Parameters:
-
p(Gaussian or GaussianMixture) –Reference and comparison distributions. They must have equal dimensionality; the divergence is evaluated from
ptoq. -
q(Gaussian or GaussianMixture) –Reference and comparison distributions. They must have equal dimensionality; the divergence is evaluated from
ptoq. -
estimator(KLEstimator) –Explicit estimator configuration.
ClosedFormrequires two :class:Gaussianinputs.MonteCarlosamples fromp; thereforesampling.Samplesmust contain samples drawn fromp.
Returns:
-
DivergenceResult–KL estimate in nats with the supplied estimator configuration.
n_evaluationscounts integration points when applicable;monte_carlocontains sampling counts and supported uncertainty estimates.
Notes
Approximate or finite-sample estimates may be negative and are not clipped.
Source code in src/gmm_divergence/divergence/_api.py
symmetric_kl_divergence
¶
symmetric_kl_divergence(
p: GaussianDistribution,
q: GaussianDistribution,
*,
forward: KLEstimator,
reverse: KLEstimator,
) -> DivergenceResult
Compute the averaged symmetric Kullback-Leibler divergence.
Computes
Here \(p\) and \(q\) are the reference and comparison distributions. The quantity
is the average, not the unscaled sum, of directed KL values in nats.
The directional estimators are intentionally separate. In particular,
precomputed samples for forward must originate from p, while those
for reverse must originate from q.
Parameters:
-
p(Gaussian or GaussianMixture) –Distributions to compare. They must have equal dimensionality.
-
q(Gaussian or GaussianMixture) –Distributions to compare. They must have equal dimensionality.
-
forward(KLEstimator) –Estimator for \(D_{\mathrm{KL}}(p \| q)\).
-
reverse(KLEstimator) –Estimator for \(D_{\mathrm{KL}}(q \| p)\).
Returns:
-
DivergenceResult–Average of the directed estimates in nats.
termsholds forward then reverse results.n_evaluationsis summed only when both directions report evaluation counts; uncertainty remains on the directional terms.
Source code in src/gmm_divergence/divergence/_api.py
jensen_shannon_divergence
¶
jensen_shannon_divergence(
p: GaussianDistribution,
q: GaussianDistribution,
*,
p_to_midpoint: KLEstimator,
q_to_midpoint: KLEstimator,
) -> DivergenceResult
Compute the Jensen-Shannon divergence between two distributions.
Computes
The midpoint is represented as a Gaussian mixture. Each directed term has an independent estimator so that precomputed samples remain attached to the distribution from which they were drawn.
Parameters:
-
p(Gaussian or GaussianMixture) –Distributions to compare. They must have equal dimensionality.
-
q(Gaussian or GaussianMixture) –Distributions to compare. They must have equal dimensionality.
-
p_to_midpoint(KLEstimator) –Estimator for \(D_{\mathrm{KL}}(p \| m)\). Any supplied samples must be drawn from
p. -
q_to_midpoint(KLEstimator) –Estimator for \(D_{\mathrm{KL}}(q \| m)\). Any supplied samples must be drawn from
q.
Returns:
-
DivergenceResult–Jensen-Shannon divergence in nats, without taking its square root.
termsholds the p-to-midpoint then q-to-midpoint results.n_evaluationsis summed only when both terms report evaluation counts; uncertainty remains on the directional terms.
Notes
ClosedForm is unsuitable because the midpoint is a GaussianMixture. The exact divergence is bounded by log(2); approximations need not preserve this bound and are not clipped.
Source code in src/gmm_divergence/divergence/_api.py
component_kl_matrix
¶
component_kl_matrix(
p: GaussianDistribution, q: GaussianDistribution
) -> FloatArray
Return pairwise closed-form KL divergences between components.
The result has shape (p_components, q_components) and element
(k, j) equals \(D_{\mathrm{KL}}(p_k \| q_j)\), where \(p_k\) and \(q_j\) are
Gaussian component densities of p and q. A :class:Gaussian is treated as a
one-component mixture.
Parameters:
-
p(Gaussian or GaussianMixture) –Distributions whose Gaussian components are compared. They must have equal dimensionality.
-
q(Gaussian or GaussianMixture) –Distributions whose Gaussian components are compared. They must have equal dimensionality.
Returns:
-
FloatArray–A
float64diagnostic matrix. It is not the KL divergence between the full mixtures.
Source code in src/gmm_divergence/divergence/_api.py
aligned_joint_kl_divergence
¶
aligned_joint_kl_divergence(
p: GaussianMixture, q: GaussianMixture
) -> AlignedJointKLResult
Compute joint KL of component labels and observations with aligned components.
Given two Gaussian mixtures with corresponding component indices,
compute the exact joint KL divergence:
Here \(k\in\{1,\ldots,K\}\) is a shared component label, \(x\in\mathbb{R}^d\) an observation, and \(\boldsymbol{\pi}_p\), \(\boldsymbol{\pi}_q\) the component probability vectors. The conditional densities are \(p_k(x)=\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k})\) and analogously \(q_k(x)\). Covariances are positive-definite \(d\times d\) matrices. This compares the joint distributions of component label and observation, assuming component indices correspond. No component matching is performed. Marginalizing over the label gives p(x) and q(x); their KL cannot exceed this joint KL. The two quantities are not generally equal. Values are in nats.
Parameters:
-
p(GaussianMixture) –Gaussian mixtures with equal numbers of components and equal feature dimensions. Component indices must be aligned.
-
q(GaussianMixture) –Gaussian mixtures with equal numbers of components and equal feature dimensions. Component indices must be aligned.
Returns:
-
AlignedJointKLResult–KL decomposition containing:
value: Total joint KL divergence.weight_kl: KL divergence between mixture weights.component_kls: Individual Gaussian component KL values.weighted_component_kl: Weighted sum of component KL values.
Source code in src/gmm_divergence/divergence/methods/_aligned_component.py
Fitting Helpers¶
fit_categorical_weights
¶
fit_categorical_weights(
target: ArrayLike, candidates: ArrayLike, *, optimizer: Optimizer
) -> CategoricalWeightFitResult
Fit a weighted mixture of categorical distributions using forward KL.
Find nonnegative candidate weights that sum to one and minimize
where \(\boldsymbol{\pi}_p\) is the target probability vector over \(K\) categories, \(\pi_{i,k}\) is candidate \(i\)'s probability of category \(k\), and \(\mathbf{w}\in\Delta_L\) has \(L\) nonnegative candidate weights summing to one. Indices refer to the same categories in every probability vector.
Parameters:
-
target((array - like, shape(n_categories))) –Target categorical probability distribution.
-
candidates((array - like, shape(n_candidates, n_categories))) –Candidate probability distributions, one per row.
-
optimizer(Optimizer) –Explicit optimizer configuration. Initial vectors have one entry per candidate row.
Returns:
-
CategoricalWeightFitResult–Optimized candidate weights, fitted categorical probabilities, KL divergence, and optimizer convergence information.
Notes
Probabilities must be finite and strictly nonnegative. Target and candidate
rows must sum to one within rtol=1e-7, atol=1e-8. Inputs are not
normalized or clipped.
Every category with positive target mass must have positive mass in at least one candidate. The objective is evaluated exactly over categories; it uses no sampling or approximation. Only forward KL fitting is supported.
Source code in src/gmm_divergence/fitting/_api.py
fit_gaussian_weights
¶
fit_gaussian_weights(
target: Gaussian | GaussianMixture,
candidates: Sequence[Gaussian | GaussianMixture],
*,
optimizer: Optimizer,
objective: FitObjective,
candidate_selector: CandidateSelector | None = None,
) -> GaussianWeightFitResult
Fit weights for a mixture of fixed Gaussian-family candidate distributions.
Fits nonnegative weights w_i such that the weighted mixture
approximates target density \(p\) according to the selected objective. Here \(L\) counts candidate distributions, \(\mathbf{w}\) their fitted weights, and \(x\in\mathbb{R}^d\) one observation. A candidate \(q_i\) may itself contain several Gaussian components; its internal component probabilities are fixed.
Parameters:
-
target(Gaussian or GaussianMixture) –Reference distribution.
-
candidates(sequence of Gaussian or GaussianMixture) –Nonempty candidate sequence with the same feature dimension as target.
-
optimizer(Optimizer) –Explicit optimizer configuration.
-
objective(FitObjective) –Explicit fitting-objective configuration.
-
candidate_selector(CandidateSelector or None, default:None) –Optional candidate selection before preparation. Initial optimizer vectors refer to retained candidates in selected order. Precomputed sampling batches refer to all original candidates.
Returns:
-
GaussianWeightFitResult–Result containing the fitted weights, combined mixture, final objective value, objective and optimizer configurations, and termination metadata. Weights remain aligned to the original candidates, with zeros for those rejected by selection. KL and Jensen-Shannon values are in nats; MomentMatching reports a squared raw-moment residual.
Source code in src/gmm_divergence/fitting/_api.py
prune_mixture
¶
prune_mixture(
mixture: GaussianMixture, *, min_weight: float = 0.0001
) -> GaussianMixture
Remove components below a threshold and normalize retained weights.
Parameters:
-
mixture(GaussianMixture) –Distribution to prune without modifying it.
-
min_weight(float, default:1e-4) –Finite, nonnegative threshold. Components with weights equal to the threshold are retained.
Returns:
-
GaussianMixture–Retained components in their original order, with normalized weights and retained provenance rows.
Raises:
-
ValueError–If the threshold is invalid or no positive mass remains.
Source code in src/gmm_divergence/distributions/_combine.py
Results¶
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,).
DivergenceResult
dataclass
¶
DivergenceResult(
*,
value: float,
divergence: str = "kl",
estimator: KLEstimator | None = None,
n_evaluations: int | None = None,
monte_carlo: MonteCarloStatistics | None = None,
terms: tuple[DivergenceResult, ...] = (),
)
A divergence in nats with estimator and evaluation metadata.
divergence
class-attribute
instance-attribute
¶
Quantity computed: kl, categorical_kl, symmetric_kl, or jensen_shannon.
estimator
class-attribute
instance-attribute
¶
estimator: KLEstimator | None = None
Configuration used for a directed Gaussian-family estimate. None for categorical and composite results; composites retain it on their terms.
monte_carlo
class-attribute
instance-attribute
¶
monte_carlo: MonteCarloStatistics | None = None
Sampling diagnostics for a directed Monte Carlo estimate. Other methods and composites have no aggregate sampling-uncertainty record.
n_evaluations
class-attribute
instance-attribute
¶
Number of sample or deterministic integration points evaluated. None for methods without such counts, or composites with an uncounted term. Each point counts once, even though both densities are evaluated there.
n_samples
property
¶
Monte Carlo observation counts, excluding deterministic points.
Composite results sum counts from their sampled terms. Returns None when no term reports Monte Carlo observations; repeated observations in different terms are counted separately.
terms
class-attribute
instance-attribute
¶
terms: tuple[DivergenceResult, ...] = ()
Ordered directional results for composite quantities: forward then reverse for symmetric KL, p-to-midpoint then q-to-midpoint for JS.
value
instance-attribute
¶
Directed or composite divergence value. Estimates may be negative; categorical KL may be infinite when comparison support is missing.
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.