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_gaussians |
Build a combined Gaussian mixture |
kl_divergence, symmetric_kl_divergence, jensen_shannon_divergence |
Main divergence helpers |
component_kl_matrix |
Pairwise component KL diagnostics |
fit_mixture_weights, prune_mixture |
Main fitting helpers |
DivergenceResult, FitResult |
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 |
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)
method = gd.divergence.MonteCarlo(sampling=gd.sampling.Draw(50_000, rng=0))
result = gd.kl_divergence(p, q, method=method)
The sections below document the root exports explicitly. Namespace-only configuration objects are documented on their namespace pages.
Distributions¶
Gaussian
dataclass
¶
covariance
instance-attribute
¶
Covariance array of shape (n_features, n_features).
chol
¶
Compute or retrieve the Cholesky factor of the covariance.
Source code in src/gmm_divergence/distributions/_gaussian.py
component_arrays
¶
Return the mean and covariance as component arrays.
from_arrays
classmethod
¶
from_arrays(mean: ArrayLike, covariance: ArrayLike) -> Gaussian
Create a Gaussian instance from array-like inputs.
Source code in src/gmm_divergence/distributions/_gaussian.py
from_regularized_arrays
classmethod
¶
from_regularized_arrays(
mean: ArrayLike,
covariance: ArrayLike,
*,
regularization: CovarianceRegularizer = "diagonal_loading",
) -> Gaussian
Create a Gaussian after explicitly regularizing its covariance.
This constructor keeps from_arrays strict while providing a convenient
path for estimated or nearly singular covariances.
Source code in src/gmm_divergence/distributions/_gaussian.py
isotropic
classmethod
¶
isotropic(mean: ArrayLike, variance: float = 1.0) -> Gaussian
Create an isotropic Gaussian instance.
Source code in src/gmm_divergence/distributions/_gaussian.py
log_det
¶
Compute or retrieve the log-determinant of the covariance.
Source code in src/gmm_divergence/distributions/_gaussian.py
logpdf
¶
Evaluate the log-density of the Gaussian at given points.
Source code in src/gmm_divergence/distributions/_gaussian.py
moments
¶
pdf
¶
sample
¶
Draw samples from the Gaussian.
Source code in src/gmm_divergence/distributions/_gaussian.py
standard
classmethod
¶
standard(dim: int) -> Gaussian
Create a standard Gaussian instance with zero mean and identity covariance.
GaussianMixture
dataclass
¶
covariances
instance-attribute
¶
Covariance array of shape (n_components, n_features, n_features).
as_gaussian
¶
as_gaussian(*, require_single: Literal[True]) -> Gaussian | None
as_gaussian(*, require_single: Literal[False] = False) -> Gaussian
as_gaussian(*, require_single: bool = False) -> Gaussian | None
Return a Gaussian approximation of the mixture using moment matching.
Source code in src/gmm_divergence/distributions/_mixture.py
chol
¶
Compute or retrieve the cached Cholesky factors.
Source code in src/gmm_divergence/distributions/_mixture.py
component_arrays
¶
Return the weights, means, and covariances as arrays.
diagnostics
¶
Return diagnostics for the Gaussian mixture.
Source code in src/gmm_divergence/distributions/_mixture.py
from_arrays
classmethod
¶
from_arrays(
weights: ArrayLike, means: ArrayLike, covariances: ArrayLike
) -> GaussianMixture
Create a Gaussian mixture from array-like parameters.
Source code in src/gmm_divergence/distributions/_mixture.py
from_components
classmethod
¶
from_components(
components: Sequence[Gaussian], weights: ArrayLike | None = None
) -> GaussianMixture
Create a Gaussian mixture from a sequence of Gaussian components and optional weights.
Source code in src/gmm_divergence/distributions/_mixture.py
from_regularized_arrays
classmethod
¶
from_regularized_arrays(
weights: ArrayLike,
means: ArrayLike,
covariances: ArrayLike,
*,
regularization: CovarianceRegularizer = "diagonal_loading",
) -> GaussianMixture
Create a Gaussian mixture after explicitly regularizing covariances.
This constructor keeps from_arrays strict while providing a convenient
path for estimated or nearly singular component covariances.
Source code in src/gmm_divergence/distributions/_mixture.py
get_component
¶
get_component(index: int) -> Gaussian
Return the Gaussian component at the specified index.
Source code in src/gmm_divergence/distributions/_mixture.py
log_dets
¶
Compute or retrieve the cached log-determinants of the covariances.
Source code in src/gmm_divergence/distributions/_mixture.py
logpdf
¶
Evaluate the log-density of the Gaussian mixture at given points.
moments
¶
Return the mean and covariance of the Gaussian mixture.
Source code in src/gmm_divergence/distributions/_mixture.py
pdf
¶
sample
¶
Draw samples from the Gaussian mixture.
select_components
¶
select_components(indices: ArrayLike) -> GaussianMixture
Return a new Gaussian mixture containing only the specified components.
Source code in src/gmm_divergence/distributions/_mixture.py
combine_gaussians
¶
combine_gaussians(
sources: Sequence[Gaussian | GaussianMixture],
weights: ArrayLike | None = None,
*,
include_mapping: Literal[False] = False,
) -> GaussianMixture
combine_gaussians(
sources: Sequence[Gaussian | GaussianMixture],
weights: ArrayLike | None = None,
*,
include_mapping: Literal[True],
) -> CombinedGaussianMixture
combine_gaussians(
sources: Sequence[Gaussian | GaussianMixture],
weights: ArrayLike | None = None,
*,
include_mapping: bool = False,
) -> GaussianMixture | CombinedGaussianMixture
Combine Gaussian mixtures and/or Gaussians into a single GaussianMixture.
A single Gaussian is internally converted to a GaussianMixture with one component. The resulting GaussianMixture has a number of components equal to the sum of the number of components in the input.
Parameters:
-
sources(Sequence[Gaussian | GaussianMixture]) –The input distributions to combine.
-
weights(ArrayLike, default:None) –Weights for each input distribution. If None, equal weights are used.
-
include_mapping(bool, default:False) –Whether to return a CombinedMixture with mapping information. If False, only the combined GaussianMixture is returned. The mapping information includes the index of the original input distribution and the local component index within that distribution for each component in the combined mixture.
Returns:
-
GaussianMixture or CombinedMixture–The combined GaussianMixture. If
return_mappingis True, a CombinedMixture containing the combined mixture and mapping information is returned.
Source code in src/gmm_divergence/distributions/_combine.py
Divergence Helpers¶
kl_divergence
¶
kl_divergence(
p: GaussianLike,
q: GaussianLike,
/,
*,
method: KLMethod = "monte_carlo",
prefer_closed_form: bool = True,
) -> DivergenceResult
Compute the Kullback--Leibler divergence between two Gaussian-family distributions.
Computes
Here, p is treated as the reference distribution and q as the
approximating distribution.
Parameters:
-
p(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
q(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
method(str or KL method configuration, default:"monte_carlo") –Method used to compute or estimate the KL divergence. Passing a string runs that method with its defaults. Use a method configuration object, such as
divergence.MonteCarlo(sampling=sampling.Draw(50_000, rng=0)), for method-specific options. -
prefer_closed_form(bool, default:True) –If
True, the function will attempt use closed form if both inputs are Gaussian, even if the user specified a different method.
Returns:
-
DivergenceResult–Result object containing the estimated KL divergence and metadata about the computation, such as the method used and whether the result is exact or approximate.
Notes
The KL divergence is asymmetric:
Therefore, swapping p and q generally gives a different result.
Examples:
Compute the KL divergence using the default Monte Carlo estimator:
Require a closed-form expression:
Configure Monte Carlo sampling:
result = kl_divergence(
p,
q,
method=divergence.MonteCarlo(sampling=sampling.Draw(50_000, rng=0)),
)
Use precomputed samples:
samples = p.sample(50_000, rng=0)
result = kl_divergence(
p, q, method=divergence.MonteCarlo(sampling=sampling.Samples(samples))
)
Source code in src/gmm_divergence/divergence/_api.py
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
symmetric_kl_divergence
¶
symmetric_kl_divergence(
p: GaussianLike,
q: GaussianLike,
/,
*,
method: KLMethod = "monte_carlo",
prefer_closed_form: bool = True,
) -> DivergenceResult
Compute the symmetric KL divergence between two Gaussian-family distributions.
Computes
The same KL estimation method is used in both directions.
Parameters:
-
p(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
q(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
method(str or KL method configuration, default:"monte_carlo") –Method used for each directed KL estimate.
-
prefer_closed_form(bool, default:True) –If
True, each directed estimate will attempt to use closed form when both inputs are Gaussian.
Returns:
-
DivergenceResult–Result containing the symmetric KL value. For sampled methods,
num_samplesis the total sample count across both directed estimates when both counts are available.
Source code in src/gmm_divergence/divergence/_api.py
jensen_shannon_divergence
¶
jensen_shannon_divergence(
p: GaussianLike,
q: GaussianLike,
/,
*,
method: KLMethod = "monte_carlo",
prefer_closed_form: bool = True,
) -> DivergenceResult
Compute the Jensen-Shannon divergence between two Gaussian-family distributions.
Computes
For Gaussian and Gaussian-mixture inputs, the midpoint distribution m is
represented as a Gaussian mixture using existing component-combination
logic.
Parameters:
-
p(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
q(Gaussian or GaussianMixture) –The two Gaussian-family distributions to compare. They must have the same dimensionality.
-
method(str or KL method configuration, default:"monte_carlo") –Method used for the two KL estimates against the midpoint mixture.
-
prefer_closed_form(bool, default:True) –Passed through to
kl_divergence. Note that the midpoint is generally a Gaussian mixture, so closed form is only available for methods and inputs that support it.
Returns:
-
DivergenceResult–Result containing the Jensen-Shannon divergence value. For sampled methods,
num_samplesis the total sample count across both directed estimates when both counts are available.
Source code in src/gmm_divergence/divergence/_api.py
component_kl_matrix
¶
component_kl_matrix(p: GaussianLike, q: GaussianLike) -> FloatArray
Return pairwise Gaussian-component KL divergences.
The returned matrix has shape (p_components, q_components), where entry
(i, j) is
for component i of p and component j of q. A single Gaussian is
treated as a one-component Gaussian mixture.
Parameters:
-
p(Gaussian or GaussianMixture) –Gaussian-family distributions whose components are compared.
-
q(Gaussian or GaussianMixture) –Gaussian-family distributions whose components are compared.
Returns:
-
FloatArray–Pairwise component KL matrix.
Source code in src/gmm_divergence/divergence/_api.py
Fitting Helpers¶
fit_mixture_weights
¶
fit_mixture_weights(
p: Gaussian | GaussianMixture,
q_i: Sequence[Gaussian | GaussianMixture],
/,
*,
method: FitMethod = "softmax_lbfgsb",
objective: FitObjective = "forward",
x0: ArrayLike | None = None,
candidate_selector: CandidateSelector | None = None,
) -> FitResult
Fit weights for a mixture of fixed candidate distributions.
Fits nonnegative weights w_i such that the weighted mixture
approximates the reference distribution p according to the selected
objective.
Parameters:
-
p(Gaussian or GaussianMixture) –Reference distribution.
-
q_i(sequence of Gaussian or GaussianMixture) –Candidate distributions whose weights are fitted.
-
method(str or optimizer configuration, default:'softmax_lbfgsb') –Optimizer used for the weights. Passing a string runs that optimizer with defaults. Use
SoftmaxLBFGSB(...)orSimplexSLSQP(...)for optimizer-specific options. -
objective(str or WeightFitObjective configuration, default:'forward') –Objective used for fitting. Passing a string runs that objective with defaults. Use
ForwardKL(...),ReverseKL(...),BidirectionalKL(...),JensenShannon(...), orMomentMatching(...)for objective-specific options. -
x0(array - like, default:None) –Initial weights for the optimized variables. If
None, the optimizer's default initialization is used.
Returns:
-
FitResult–Result containing the fitted weights, fitted mixture, fit objective, objective value, forward/reverse KL diagnostics, and optimizer metadata.
Source code in src/gmm_divergence/fitting/_api.py
prune_mixture
¶
prune_mixture(
mixture: GaussianMixture, *, min_weight: float = 0.0001
) -> GaussianMixture
Prune components of a Gaussian mixture with small weights.
This is a common post-processing step after fitting to remove components that contribute negligibly to the mixture, improving efficiency and interpretability.
Parameters:
-
mixture(GaussianMixture) –The mixture to prune.
-
min_weight(float, default:0.0001) –Minimum weight threshold for keeping components. Components with weights below this threshold will be removed. Default is 1e-4.
Returns:
-
GaussianMixture–The pruned mixture with weights normalized to sum to one.
Raises:
-
ValueError–If all components are pruned.
Source code in src/gmm_divergence/fitting/_api.py
Results¶
DivergenceResult
dataclass
¶
DivergenceResult(
value: float,
method: str | None = None,
num_samples: int | None = None,
monte_carlo_stats: MonteCarloStatistics | None = None,
)
Result of a divergence estimation.
method
class-attribute
instance-attribute
¶
The method used for estimation, if applicable.
monte_carlo_stats
class-attribute
instance-attribute
¶
Monte Carlo statistics related to the estimation, if applicable.
Contains the sample mean, sample variance, standard error, and effective sample size of the pointwise divergence estimates when using Monte Carlo estimation.
num_samples
class-attribute
instance-attribute
¶
The number of samples used for estimation, if applicable.
FitResult
dataclass
¶
FitResult(
weights: Weights,
objective_value: float,
scipy_result: OptimizeResult | None,
fitted_mixture: CombinedGaussianMixture,
fit_objective: FitObjective,
fit_method: FitMethod,
alpha: float | None = None,
iterations: int | None = None,
converged: bool | None = None,
used_candidate_indices: list[int] | None = None,
)
Result of fitting a Gaussian mixture.
Primary result when using
fit_mixture_weights
and related functions.
alpha
class-attribute
instance-attribute
¶
Forward-objective weight used by bidirectional fitting, if applicable.
converged
class-attribute
instance-attribute
¶
Whether the optimization routine reported convergence, if applicable.
fit_method
instance-attribute
¶
The optimization method used to fit the mixture weights.
fit_objective
instance-attribute
¶
The objective used to fit the mixture weights.
fitted_mixture
instance-attribute
¶
fitted_mixture: CombinedGaussianMixture
The full combined Gaussian mixture corresponding to the fitted weights.
iterations
class-attribute
instance-attribute
¶
The number of iterations taken by the optimization routine, if applicable.
objective_value
instance-attribute
¶
The final scalar objective value minimized by the optimizer.
scipy_result
instance-attribute
¶
The full result object returned by the optimization routine, if used.
candidate_weight_dict
¶
candidate_weights
¶
Return fitted weights paired with original candidate indices.
If candidate selection was used, indices refer to the original q_i
sequence passed to fit_mixture_weights. Otherwise they are simply
0, 1, ..., n_candidates - 1.