Skip to content

Distributions

Common Gaussian-family classes are documented under Top-level API. This page documents Gaussian-family metadata objects that are available from gmm_divergence.distributions but are not exported at the root.

Both constructors accept array-like parameters directly and copy them into read-only float64 arrays. regularizer is keyword-only. Mixture weights are nonnegative coefficients normalized to sum to one; categorical probabilities must already sum to one and are never normalized or clipped.

Gaussian.mean and GaussianMixture.mean have shape (n_features,); their covariance properties have shape (n_features, n_features). Mixture component arrays remain means (n_components, n_features) and covariances (n_components, n_features, n_features).

Gaussian.from_samples requires finite two-dimensional observations with at least two rows and uses unbiased covariance. Use regularizer for singular empirical covariances. Fit mixtures with explicit scikit-learn configuration, then call GaussianMixture.from_sklearn. to_sklearn copies parameters into an evaluable sklearn model; it does not fit observations.

mixture.as_gaussian() requires exactly one component. Use mixture.moment_match() for an approximation matching aggregate moments.

For a mixture \(p(x)=\sum_{k=1}^{K_p}\pi_{p,k} \mathcal{N}(x;\mu_{p,k},\Sigma_{p,k})\), the aggregate moments are

\[ \mu_p=\sum_{k=1}^{K_p}\pi_{p,k}\mu_{p,k}, \qquad \Sigma_p=\sum_{k=1}^{K_p}\pi_{p,k} \left[\Sigma_{p,k}+(\mu_{p,k}-\mu_p)(\mu_{p,k}-\mu_p)^\top\right]. \]

Here \(K_p\) counts components, \(\pi_{p,k}\) are normalized component probabilities, and each mean and covariance describes one component in \(d\) features. The between-component term is essential; covariance is not simply an average of component covariances. See the notation guide.

For \(N\geq2\) observations \(x_n\), Gaussian.from_samples uses \(\widehat\mu=N^{-1}\sum_{n=1}^{N}x_n\) and

\[ \widehat\Sigma=\frac{1}{N-1}\sum_{n=1}^{N} (x_n-\widehat\mu)(x_n-\widehat\mu)^\top. \]

This unbiased sample covariance differs from the responsibility-weighted maximum-likelihood covariance in component_statistics, which divides by the soft count without an unbiasedness correction.

combine_distributions always returns a directly usable GaussianMixture. Its mapping identifies the immediate source and local component of each flattened component. Nested combination maps to its immediate inputs. select_components and prune_mixture preserve retained mapping rows; component indices must be integers and in bounds.

import gmm_divergence as gd

target = gd.Gaussian.from_samples([[0], [1], [2]])
mixture = gd.combine_distributions([target, gd.Gaussian.univariate(3)], weights=[3, 1])
assert mixture.mapping is not None
assert mixture.mapping.source_of(1) == (1, 0)
assert mixture.mean.shape == (1,)
approximation = mixture.moment_match()
result = gd.kl_divergence(mixture, approximation, estimator=gd.divergence.Unscented())

gmm_divergence.distributions

Immutable Gaussian distributions and composition.

GaussianDistribution module-attribute

GaussianDistribution: TypeAlias = Gaussian | GaussianMixture

MixtureDiagnostics dataclass

MixtureDiagnostics(
    n_components: int,
    n_features: int,
    weight_sum: float,
    max_weight: float,
    min_weight: float,
    weight_entropy: float,
    covariance_condition_numbers: FloatArray,
)

Diagnostics for a Gaussian mixture model.

covariance_condition_numbers instance-attribute

covariance_condition_numbers: FloatArray

Condition numbers of the covariance matrices of the components.

max_weight instance-attribute

max_weight: float

Maximum weight among the components.

min_weight instance-attribute

min_weight: float

Minimum weight among the components.

n_components instance-attribute

n_components: int

Number of components in the mixture.

n_features instance-attribute

n_features: int

Dimensionality of the mixture.

weight_entropy instance-attribute

weight_entropy: float

Entropy of the weights of the components in nats.

weight_sum instance-attribute

weight_sum: float

Sum of the weights of the components.

MixtureMapping dataclass

MixtureMapping(source_index: ArrayLike, local_component_index: ArrayLike)

Immediate-source provenance for every flattened mixture component.

Parameters:

  • source_index ((array - like, shape(n_components))) –

    Nonempty vector of nonnegative integer source positions.

  • local_component_index ((array - like, shape(n_components))) –

    Nonnegative integer positions within each source, matching source_index.

Notes

Both arrays are copied into read-only intp arrays. Combination refers to immediate inputs; fitting refers to the original candidate sequence. Nested source mappings are not recursively flattened.

Source code in src/gmm_divergence/distributions/_mapping.py
def __init__(self, source_index: npt.ArrayLike, local_component_index: npt.ArrayLike) -> None:
    sources = index_array(source_index, name="source_index")
    components = index_array(local_component_index, name="local_component_index")
    if sources.shape != components.shape:
        msg = "mapping indices must be one-dimensional arrays with matching shapes."
        raise ValueError(msg)
    object.__setattr__(self, "source_index", sources)
    object.__setattr__(self, "local_component_index", components)

component_of

component_of(input_index: int, local_component_index: int) -> int

Find a flattened component by its source and local position.

Parameters:

  • input_index (int) –

    Source position recorded in source_index.

  • local_component_index (int) –

    Component position within that source.

Returns:

  • int –

    First matching flattened component position if rows are duplicated.

Raises:

  • TypeError –

    If either argument is not an integer or is a boolean.

  • ValueError –

    If the requested source and component pair is absent.

Source code in src/gmm_divergence/distributions/_mapping.py
def component_of(self, input_index: int, local_component_index: int) -> int:
    """Find a flattened component by its source and local position.

    Parameters
    ----------
    input_index : int
        Source position recorded in source_index.
    local_component_index : int
        Component position within that source.

    Returns
    -------
    int
        First matching flattened component position if rows are duplicated.

    Raises
    ------
    TypeError
        If either argument is not an integer or is a boolean.
    ValueError
        If the requested source and component pair is absent.
    """
    for name, index in (
        ("input_index", input_index),
        ("local_component_index", local_component_index),
    ):
        if isinstance(index, bool) or not isinstance(index, Integral):
            msg = f"{name} must be an integer, got {index!r}."
            raise TypeError(msg)
    matches = np.flatnonzero(
        (self.source_index == input_index)
        & (self.local_component_index == local_component_index)
    )
    if matches.size == 0:
        msg = (
            f"No component found for input_index={input_index}, "
            f"local_component_index={local_component_index}."
        )
        raise ValueError(msg)
    return int(matches[0])

source_of

source_of(component_index: int) -> tuple[int, int]

Look up the source of a flattened component.

Parameters:

  • component_index (int) –

    Position in [0, n_components); booleans are not accepted.

Returns:

  • tuple of int –

    Source index and local component index, respectively.

Notes

Index validation raises TypeError for noninteger positions and IndexError for positions outside the mapping.

Source code in src/gmm_divergence/distributions/_mapping.py
def source_of(self, component_index: int) -> tuple[int, int]:
    """Look up the source of a flattened component.

    Parameters
    ----------
    component_index : int
        Position in `[0, n_components)`; booleans are not accepted.

    Returns
    -------
    tuple of int
        Source index and local component index, respectively.

    Notes
    -----
    Index validation raises TypeError for noninteger positions and
    IndexError for positions outside the mapping.
    """
    validate_index(component_index, self.source_index.size)
    return int(self.source_index[component_index]), int(
        self.local_component_index[component_index]
    )