Skip to content

Divergence API

Top-level divergence helpers are documented under Top-level API. This page documents estimator configuration classes and categorical KL divergence from gmm_divergence.divergence.

Divergence calls accept p and q by keyword. Estimators are explicit and keyword-only. Compared Gaussian-family distributions must have the same feature dimension. Mathematical expressions follow the notation conventions: \(p\) is the reference and \(q\) the comparison distribution.

MomentMatchedGaussian() always matches aggregate moments, including mixture weights. For nearest component analysis, use component_kl_matrix(p, q).min(); this is a component diagnostic, not mixture KL.

Results separate divergence from estimator. n_evaluations counts integration points, including deterministic sigma points; n_samples counts Monte Carlo observations only. Composite results retain directional terms and omit aggregate uncertainty because directional dependence is not inferred.

monte_carlo.standard_error is None when the integration design cannot estimate uncertainty, including singleton iid draws and singleton positive strata. Adaptive Draw sampling reports monte_carlo.target_reached; False means the sample budget was exhausted. Monte Carlo estimates can be negative from sampling error and are not clipped.

Symmetric KL averages both directions. Jensen-Shannon returns divergence in nats; its square root is a distance and is not returned by this API.

\[ D_{\mathrm{SKL}}(p,q)=\tfrac12\left[D_{\mathrm{KL}}(p\|q) +D_{\mathrm{KL}}(q\|p)\right], \]
\[ D_{\mathrm{JS}}(p,q)=\tfrac12D_{\mathrm{KL}}(p\|m) +\tfrac12D_{\mathrm{KL}}(q\|m),\qquad m=\tfrac12p+\tfrac12q. \]

The exact Jensen-Shannon divergence is bounded by \(\log 2\) nats. Sampling and deterministic approximations need not preserve the bounds of exact divergences.

gmm_divergence.divergence

Public divergence API.

MonteCarlo dataclass

MonteCarlo(
    *,
    sampling: SampleSpec = Draw(),
    target_standard_error: float | None = None,
    max_samples: int | None = None,
    batch_size: int | None = None,
)

Estimate KL with an explicit sample source.

Set target_standard_error to enable adaptive sampling. Adaptive sampling is intentionally restricted to Draw because it needs additional samples.

Parameters:

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

    Source of observations from the first distribution in a directed KL call. Draw defaults to 10000 observations. Precomputed samples must originate from that same distribution.

  • target_standard_error (float or None, default: None ) –

    Finite, positive stopping threshold in nats. None uses one fixed batch. Adaptive runs check the estimated standard error after drawing at least sampling.n_samples observations.

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

    Required positive budget for adaptive runs, at least sampling.n_samples. Unused budgets are rejected when target_standard_error is None.

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

    Positive adaptive draw size; None uses sampling.n_samples. The final batch is shortened to respect max_samples.

Notes

Standard error is available for equally weighted observations with at least two samples, or stratified batches with at least two observations in every positive-weight component. Arbitrary weighted batches have no uncertainty estimate. Precomputed observations must satisfy the assumed sampling design. Adaptive results report whether the target was reached; the estimated error does not bound approximation bias or guarantee an absolute error.

Unscented dataclass

Unscented()

Estimate directed KL using deterministic points from reference components.

Uses twice the number of features in sigma points per reference component, weighted by component mass. Reports n_evaluations, without a Monte Carlo sample count or standard error. The approximation can be negative.

MomentMatchedGaussian dataclass

MomentMatchedGaussian()

Compute KL between Gaussian approximations of both distributions.

Each approximation matches its distribution's aggregate mean and covariance. This is exact for Gaussian inputs, but ignores higher moments of mixtures. No samples or uncertainty estimates are produced.

ClosedForm dataclass

ClosedForm()

Compute exact directed KL for two Gaussian objects, in nats.

GaussianMixture inputs are rejected even when they have one component. Convert those explicitly with as_gaussian() before calling kl_divergence.

Variational dataclass

Variational()

Estimate KL with the Hershey--Olsen variational approximation.

Uses pairwise component KL values and mixture weights without sampling. The mixture approximation is not a certified bound on the true divergence.

Categorical KL Divergence

categorical_kl_divergence compares probability vectors over shared categories. Corresponding indices must refer to the same category. Mode occupancy is one use case: independently fitted GMM components must be aligned first, and components need not represent distinct modes. This function computes categorical KL, rather than divergence between mixture densities.

For \(K\) categories with probabilities \(\boldsymbol{\pi}_p\) and \(\boldsymbol{\pi}_q\), the exact quantity is

\[ D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) =\sum_{k:\pi_{p,k}>0}\pi_{p,k}\log\frac{\pi_{p,k}}{\pi_{q,k}}. \]

Zero reference probabilities contribute zero. A positive reference probability with zero comparison probability gives infinity. Smoothing with \(\varepsilon\) (epsilon) replaces each vector's entries by \((\pi_k+\varepsilon)/(1+K\varepsilon)\); it changes the distributions compared.

import gmm_divergence as gd

result = gd.divergence.categorical_kl_divergence([0.8, 0.2], [0.5, 0.5])
assert result.value > 0

# Smoothing changes the probability vectors and makes this comparison finite.
smoothed = gd.divergence.categorical_kl_divergence([1.0, 0.0], [0.0, 1.0], epsilon=1e-8)
assert smoothed.value > 0

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

\[ D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) =\sum_{k:\pi_{p,k}>0}\pi_{p,k}\log\frac{\pi_{p,k}}{\pi_{q,k}}. \]

Parameters:

  • p (array - like) –

    Nonempty, finite, nonnegative probability vectors of equal length, each summing to one. Index k must represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked with rtol=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 k must represent the same category in both vectors; the caller is responsible for this correspondence. Sums are checked with rtol=1e-7, atol=1e-8; negative values are rejected without clipping.

  • epsilon (float, default: 0.0 ) –

    Finite, nonnegative additive smoothing amount. For K categories, 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
def categorical_kl_divergence(
    p: npt.ArrayLike, q: npt.ArrayLike, *, epsilon: float = 0.0
) -> DivergenceResult:
    r"""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

    $$
    D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)
    =\sum_{k:\pi_{p,k}>0}\pi_{p,k}\log\frac{\pi_{p,k}}{\pi_{q,k}}.
    $$

    Parameters
    ----------
    p, q : array-like
        Nonempty, finite, nonnegative probability vectors of equal length,
        each summing to one. Index `k` must represent the same category in
        both vectors; the caller is responsible for this correspondence.
        Sums are checked with `rtol=1e-7`, `atol=1e-8`; negative values are
        rejected without clipping.
    epsilon : float, default=0.0
        Finite, nonnegative additive smoothing amount. For `K` categories,
        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.
    """
    return kl_categorical(p, q, epsilon=epsilon)

Aligned Joint KL

aligned_joint_kl_divergence computes exact KL between the joint distributions of component label and observation. Both mixtures must have the same number of components and feature dimensions, and corresponding indices must represent the same component. No component matching is performed.

\[ D_{\mathrm{KL}}(p(k,x) \| q(k,x)) = D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) +\sum_{k=1}^{K}\pi_{p,k}D_{\mathrm{KL}}(p_k\|q_k). \]

Here \(k\in\{1,\ldots,K\}\) is the common component label, \(x\in\mathbb{R}^d\) an observation, and \(p(k,x)=\pi_{p,k}p_k(x)\) with \(p_k(x)=\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k})\), and likewise for \(q\). The vectors \(\boldsymbol{\pi}_p\), \(\boldsymbol{\pi}_q\) contain component probabilities. The result separates differences in component weights from differences within components. This is a joint KL, rather than the marginal KL between mixture densities; reordering just one mixture changes the assumed correspondence. A positive reference weight paired with a zero comparison weight gives infinite joint KL.

Marginalizing over the component label cannot increase KL, so this joint value is an upper bound on the marginal mixture KL. Combining candidates flattens their components; its provenance alone does not establish the correspondence required for an aligned comparison.

import gmm_divergence as gd

components = [gd.Gaussian.univariate(-1), gd.Gaussian.univariate(1)]
p = gd.GaussianMixture.from_components(components, weights=[0.8, 0.2])
q = gd.GaussianMixture.from_components(components, weights=[0.5, 0.5])
result = gd.aligned_joint_kl_divergence(p, q)
assert result.value == result.weight_kl
assert result.weighted_component_kl == 0

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,

\[ p(k,x) = \pi_{p,k}\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k}), \]
\[ q(k,x) = \pi_{q,k}\mathcal{N}(x;\mu_{q,k},\Sigma_{q,k}), \]

compute the exact joint KL divergence:

\[ D_{\mathrm{KL}}(p(k,x)\|q(k,x)) = D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q) + \sum_{k=1}^{K} \pi_{p,k} D_{\mathrm{KL}}(p_k\|q_k). \]

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
def aligned_joint_kl_divergence(p: GaussianMixture, q: GaussianMixture) -> AlignedJointKLResult:
    r"""Compute joint KL of component labels and observations with aligned components.

    Given two Gaussian mixtures with corresponding component indices,

    $$
    p(k,x) = \pi_{p,k}\mathcal{N}(x;\mu_{p,k},\Sigma_{p,k}),
    $$

    $$
    q(k,x) = \pi_{q,k}\mathcal{N}(x;\mu_{q,k},\Sigma_{q,k}),
    $$

    compute the exact joint KL divergence:

    $$
    D_{\mathrm{KL}}(p(k,x)\|q(k,x))
    =
    D_{\mathrm{KL}}(\boldsymbol{\pi}_p\|\boldsymbol{\pi}_q)
    +
    \sum_{k=1}^{K}
    \pi_{p,k}
    D_{\mathrm{KL}}(p_k\|q_k).
    $$

    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, 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.
    """
    _validate_mixture(p, name="p")
    _validate_mixture(q, name="q")
    if p.n_components != q.n_components:
        msg = (
            "Aligned-component KL requires equal numbers of components, "
            f"got {p.n_components} and {q.n_components}."
        )
        raise ValueError(msg)

    if p.n_features != q.n_features:
        msg = (
            f"Aligned-component KL requires equal feature dimensions, got "
            f"{p.n_features} and {q.n_features}."
        )
        raise ValueError(msg)

    weight_kl = kl_categorical(p.weights, q.weights).value

    component_kls = gaussian_kl_from_factors(
        p.covariances, q.means - p.means, q.cholesky(), p.log_determinants(), q.log_determinants()
    )
    component_kls.setflags(write=False)
    weighted_component_kl = float(np.dot(p.weights, component_kls))

    return AlignedJointKLResult(
        value=weight_kl + weighted_component_kl,
        weight_kl=weight_kl,
        component_kls=component_kls,
        weighted_component_kl=weighted_component_kl,
    )

AlignedJointKLResult dataclass

AlignedJointKLResult(
    *,
    value: float,
    weight_kl: float,
    component_kls: FloatArray,
    weighted_component_kl: float,
)

Joint KL of aligned labels and observations, an upper bound on marginal KL.

component_kls instance-attribute

component_kls: FloatArray

Independent, read-only directed Gaussian KL values for aligned pairs. Shape (n_components,).

value instance-attribute

value: float

Total joint KL in nats, equal to weight_kl + weighted_component_kl.

weight_kl instance-attribute

weight_kl: float

Categorical KL between aligned mixture weights. Infinite when a positive reference weight has zero comparison weight.

weighted_component_kl instance-attribute

weighted_component_kl: float

Sum of component_kls weighted by the reference mixture's weights.

MonteCarloStatistics dataclass

MonteCarloStatistics(
    *,
    n_samples: int,
    standard_error: float | None,
    target_reached: bool | None = None,
)

Monte Carlo sampling diagnostics for one directed estimate.

n_samples instance-attribute

n_samples: int

Number of observations used, including all adaptive batches.

standard_error instance-attribute

standard_error: float | None

Estimated standard error in nats, when supported by the sampling design. None indicates that uncertainty cannot be estimated, not zero error.

target_reached class-attribute instance-attribute

target_reached: bool | None = None

Whether adaptive sampling reached its requested standard error. False means the sample budget was exhausted first; None means a fixed run.

KLEstimator module-attribute

KLEstimator: TypeAlias = (
    MonteCarlo | Unscented | MomentMatchedGaussian | ClosedForm | Variational
)