Skip to content

Covariance regularization

Covariance regularization utilities are imported from gmm_divergence.covariance.

Regularization can improve covariance conditioning and repair singular empirical estimates, for example when observations are sparse relative to feature dimension. It does not guarantee positive definiteness for every input and configuration; the returned matrices are validated, and invalid results are rejected.

Following the notation conventions, \(\Sigma\) is a symmetric \(d\times d\) input matrix, \(I_d\) is the identity, \(\varepsilon\geq0\) is diagonal loading, \(\eta\in[0,1]\) is shrinkage strength, \(s>0\) is heuristic scale, and \(r\) is retained rank. Eigenvalues are ordered \(\lambda_1\leq\cdots\leq\lambda_d\). Symbols are mapped to their Python configuration fields in the generated docstrings below.

Regularization never modifies the input array. Every regularizer returns an independent, read-only float64 array.

gmm_divergence.covariance

Public covariance regularizers and epsilon heuristics.

Input shape determines single versus batched matrix behavior: (n_features, n_features) or (n_matrices, n_features, n_features). estimate_epsilon returns a scalar or one value per matrix. Configure epsilon, heuristic scale and rank, shrinkage strength, or max_condition_number explicitly by keyword. Shrinkage defaults to strength=1e-2 for both isotropic and diagonal targets.

Trace scaling and residual-variance heuristics clip negative contributions to zero. Retaining full rank gives zero residual variance. The condition-number heuristic computes loading from the extreme eigenvalues; an all-zero covariance still receives zero loading, so use positive loading or eigenvalue clipping when that case must be repaired.

import gmm_divergence as gd

covariance = gd.covariance.regularize_covariance(
    [[1, 0], [0, 0]], regularizer=gd.covariance.DiagonalLoading(epsilon=0.1)
)
gaussian = gd.Gaussian([0, 0], covariance)
assert gaussian.n_features == 2

Functions

regularize_covariance

regularize_covariance(
    covariance: ArrayLike, *, regularizer: CovarianceRegularizer
) -> FloatArray

Regularize a single covariance matrix or a batch of matrices.

The shape determines batching. Returns an independent, read-only float64 array of the same shape. Inputs may be singular, but the regularized matrices must be positive definite.

Parameters:

  • covariance ((array - like, shape(n_features, n_features) or (n_matrices, n_features, n_features))) –

    Nonempty, finite, symmetric covariance matrix or batch. Symmetry is checked with NumPy's default allclose tolerance, then roundoff asymmetry is averaged out. Positive definiteness is checked after regularization.

  • regularizer (CovarianceRegularizer) –

    Explicit loading, shrinkage, clipping, or low-rank configuration. Epsilon heuristics are resolved separately for each covariance.

Returns:

  • ndarray –

    Independent, read-only float64 array matching the input shape.

Raises:

  • TypeError –

    If regularizer is unsupported.

Notes

Invalid shapes, values, ranks, or non-positive-definite results raise ValueError through covariance validation. Regularization does not guarantee positive definiteness for every input and configuration.

Source code in src/gmm_divergence/covariance/_api.py
def regularize_covariance(
    covariance: npt.ArrayLike, *, regularizer: CovarianceRegularizer
) -> FloatArray:
    """Regularize a single covariance matrix or a batch of matrices.

    The shape determines batching. Returns an independent, read-only float64
    array of the same shape. Inputs may be singular, but the regularized
    matrices must be positive definite.

    Parameters
    ----------
    covariance : array-like, shape (n_features, n_features) or (n_matrices, n_features, n_features)
        Nonempty, finite, symmetric covariance matrix or batch. Symmetry is
        checked with NumPy's default allclose tolerance, then roundoff asymmetry
        is averaged out. Positive definiteness is checked after regularization.
    regularizer : CovarianceRegularizer
        Explicit loading, shrinkage, clipping, or low-rank configuration.
        Epsilon heuristics are resolved separately for each covariance.

    Returns
    -------
    ndarray
        Independent, read-only float64 array matching the input shape.

    Raises
    ------
    TypeError
        If regularizer is unsupported.

    Notes
    -----
    Invalid shapes, values, ranks, or non-positive-definite results raise
    ValueError through covariance validation. Regularization does not guarantee
    positive definiteness for every input and configuration.
    """
    match regularizer:
        case DiagonalLoading(epsilon=epsilon):
            return _diagonal_loading(covariance, epsilon=epsilon)
        case IsotropicShrinkage(strength=strength):
            return _linear_shrinkage(covariance, strength=strength)
        case DiagonalShrinkage(strength=strength):
            return _diagonal_shrinkage(covariance, strength=strength)
        case EigenvalueClipping(min_eigenvalue=min_eigenvalue):
            return _eigenvalue_clipping(covariance, min_eigenvalue=min_eigenvalue)
        case LowRank(rank=rank, epsilon=epsilon):
            return _lowrank(covariance, rank=rank, epsilon=epsilon)
        case _:
            msg = f"regularizer must be a CovarianceRegularizer, got {type(regularizer).__name__}."
            raise TypeError(msg)

estimate_epsilon

estimate_epsilon(
    covariance: ArrayLike, /, *, heuristic: EpsilonHeuristic
) -> float | FloatArray

Estimate a diagonal-loading epsilon from covariance scale or spectrum.

Parameters:

  • covariance (array - like) –

    Covariance matrix with shape (n_features, n_features) or batch of shape (n_matrices, n_features, n_features). Dimensions must be nonempty and values finite. Symmetry is checked with NumPy's default allclose tolerance before averaging out roundoff asymmetry. Positive definiteness is not required.

  • heuristic (EpsilonHeuristic) –

    Explicit heuristic configuration used to estimate epsilon. ResidualVariance requires an explicit rank for this operation.

Returns:

  • float or array –

    Estimated epsilon value(s). If the input is a single covariance, a float is returned. If the input is a batch of covariances, an array of shape (n_matrices,) is returned with one epsilon per covariance.

Notes

Validation raises TypeError for an unsupported heuristic, and ValueError for invalid covariance values or shapes, missing residual rank, or a rank above the covariance dimension.

Source code in src/gmm_divergence/covariance/_epsilon.py
def estimate_epsilon(
    covariance: npt.ArrayLike, /, *, heuristic: EpsilonHeuristic
) -> float | FloatArray:
    """Estimate a diagonal-loading epsilon from covariance scale or spectrum.

    Parameters
    ----------
    covariance : array-like
        Covariance matrix with shape `(n_features, n_features)` or batch of shape
        `(n_matrices, n_features, n_features)`. Dimensions must be nonempty and
        values finite. Symmetry is
        checked with NumPy's default allclose tolerance before averaging out
        roundoff asymmetry. Positive definiteness is not required.
    heuristic : EpsilonHeuristic
        Explicit heuristic configuration used to estimate epsilon.
        ResidualVariance requires an explicit rank for this operation.

    Returns
    -------
    float or array
        Estimated epsilon value(s). If the input is a single covariance, a float
        is returned. If the input is a batch of covariances, an array of shape
        `(n_matrices,)` is returned with one epsilon per covariance.

    Notes
    -----
    Validation raises TypeError for an unsupported heuristic, and ValueError for
    invalid covariance values or shapes, missing residual rank, or a rank above
    the covariance dimension.
    """
    covariance_arr: FloatArray = np.asarray(covariance, dtype=np.float64)
    _ = validate_covariance_input(covariance_arr)
    covariance_arr = symmetrize(covariance_arr)
    return epsilon_from_covariance(covariance_arr, _as_epsilon_heuristic(heuristic))

Regularizers

DiagonalLoading dataclass

DiagonalLoading(*, epsilon: EpsilonSpec = 1e-06)

Diagonal loading regularization configuration.

Applies the regularizer

\[ \Sigma_{\mathrm{reg}} = \Sigma + \varepsilon I_d, \]

where \(\Sigma\) is the symmetric \(d\times d\) input covariance, \(I_d\) is the identity matrix, and \(\varepsilon\geq0\) is epsilon or its heuristic value.

Parameters:

  • epsilon (float or EpsilonHeuristic, default: 1e-6 ) –

    Finite, nonnegative loading amount, or a heuristic evaluated per matrix. Zero is allowed but does not repair a singular covariance.

epsilon class-attribute instance-attribute

epsilon: EpsilonSpec = 1e-06

Diagonal loading amount or epsilon heuristic.

IsotropicShrinkage dataclass

IsotropicShrinkage(*, strength: float = 0.01)

Linear shrinkage toward an isotropic covariance target.

Applies the shrinkage

\[ \Sigma_{\mathrm{reg}} = (1-\eta)\,\Sigma + \eta\,\tau I_d, \qquad \tau = \frac{\mathrm{tr}(\Sigma)}{d}, \]

where \(\Sigma\) is the symmetric \(d\times d\) input covariance, \(\eta\in[0,1]\) is strength, and \(I_d\) is the identity matrix. The target \(\tau I_d\) has the same average marginal variance as \(\Sigma\).

Parameters:

  • strength (float, default: 1e-2 ) –

    Finite interpolation weight in [0, 1]. Zero leaves the covariance unchanged; one replaces it with its isotropic trace-matched target.

strength class-attribute instance-attribute

strength: float = 0.01

Interpolation weight between the covariance and isotropic target.

DiagonalShrinkage dataclass

DiagonalShrinkage(*, strength: float = 0.01)

Shrinkage toward the covariance diagonal.

Applies the shrinkage

\[ \Sigma_{\mathrm{reg}} = (1-\eta)\,\Sigma + \eta\,\mathrm{diag}(\Sigma), \]

where \(\Sigma\) is the symmetric input covariance, \(\eta\in[0,1]\) is strength, and \(\mathrm{diag}(\Sigma)\) is the diagonal matrix containing its marginal variances.

Parameters:

  • strength (float, default: 1e-2 ) –

    Finite interpolation weight in [0, 1]. Zero leaves the covariance unchanged; one removes all off-diagonal covariance entries.

strength class-attribute instance-attribute

strength: float = 0.01

Interpolation weight between the covariance and diagonal target.

EigenvalueClipping dataclass

EigenvalueClipping(*, min_eigenvalue: float = 1e-06)

Eigenvalue-clipping regularization configuration.

Given an eigendecomposition

\[ \Sigma = U\,\mathrm{diag}(\lambda_1,\ldots,\lambda_d)\,U^\top, \]

this method returns

\[ \Sigma_{\mathrm{reg}} = U\,\mathrm{diag}\!\left( \max(\lambda_1,\lambda_{\mathrm{floor}}),\ldots, \max(\lambda_d,\lambda_{\mathrm{floor}})\right)\,U^\top, \]

where \(U\) contains orthonormal eigenvectors of the symmetric \(d\times d\) input covariance, \(\lambda_1\leq\cdots\leq\lambda_d\) are its eigenvalues, and \(\lambda_{\mathrm{floor}}>0\) is min_eigenvalue.

Parameters:

  • min_eigenvalue (float, default: 1e-6 ) –

    Finite, strictly positive eigenvalue floor.

min_eigenvalue class-attribute instance-attribute

min_eigenvalue: float = 1e-06

Smallest allowed eigenvalue after clipping.

LowRank dataclass

LowRank(*, rank: int = 1, epsilon: EpsilonSpec = 1e-06)

Low-rank covariance approximation with diagonal loading.

For an eigendecomposition

\[ \Sigma = U\,\mathrm{diag}(\lambda_1,\ldots,\lambda_d)\,U^\top, \]

with \(\lambda_1\leq\cdots\leq\lambda_d\), retain the \(r\) largest eigenpairs (\(r\) is rank) and return

\[ \Sigma_{\mathrm{reg}} = U_r\,\Lambda_r\,U_r^\top+\varepsilon I_d, \]

where \(U_r\) contains the retained eigenvectors, \(\Lambda_r=\mathrm{diag}(\lambda_{d-r+1},\ldots,\lambda_d)\) their eigenvalues, \(I_d\) is the \(d\times d\) identity, and \(\varepsilon\geq0\) is epsilon or its heuristic value. Eigenvectors and eigenvalues use the same order.

Parameters:

  • rank (int, default: 1 ) –

    Positive number of leading eigenpairs, at most the covariance dimension.

  • epsilon (float or EpsilonHeuristic, default: 1e-6 ) –

    Finite, nonnegative diagonal loading after truncation, or a heuristic evaluated on the input covariance. ResidualVariance inherits this rank when its rank is None; an explicit residual rank must match.

Notes

A truncated covariance needs sufficient positive loading to be positive definite. The public regularization operation rejects singular results.

epsilon class-attribute instance-attribute

epsilon: EpsilonSpec = 1e-06

Diagonal loading amount or epsilon heuristic.

rank class-attribute instance-attribute

rank: int = 1

Target rank for the approximation.

Epsilon Heuristics

RelativeToTrace dataclass

RelativeToTrace(*, scale: float = 1e-06)

Scale epsilon with the covariance trace.

Sets

\[ \varepsilon = s\,\max\!\left(\frac{\mathrm{tr}(\Sigma)}{d},0\right), \]

where \(\Sigma\) is a symmetric \(d\times d\) covariance input and \(s>0\) is scale. This clips a nonpositive average marginal variance to zero.

Parameters:

  • scale (float, default: 1e-6 ) –

    Finite, strictly positive multiplier of the average marginal variance. A nonpositive trace gives an epsilon of zero.

scale class-attribute instance-attribute

scale: float = 1e-06

Multiplier \(s>0\) of the nonnegative average marginal variance.

TargetConditionNumber dataclass

TargetConditionNumber(*, max_condition_number: float = 100000000.0)

Estimate loading from a requested covariance condition number.

For ordered eigenvalues \(\lambda_1\leq\cdots\leq\lambda_d\) of the symmetric input covariance \(\Sigma\), set

\[ \varepsilon=\max\!\left( \frac{\lambda_d-\kappa_{\max}\lambda_1}{\kappa_{\max}-1},0\right), \qquad \Sigma_{\mathrm{reg}}=\Sigma+\varepsilon I_d. \]

Here \(\kappa_{\max}>1\) is max_condition_number and \(I_d\) is the identity. When \(\Sigma_{\mathrm{reg}}\) is positive definite, this enforces the spectral condition number \(\kappa(\Sigma_{\mathrm{reg}})\leq\kappa_{\max}\). Degenerate inputs can yield a singular result, such as zero loading for an all-zero covariance; regularization still validates positive definiteness.

Parameters:

  • max_condition_number (float, default: 1e8 ) –

    Finite condition-number target greater than one. The heuristic uses the smallest and largest eigenvalues of the symmetric covariance.

max_condition_number class-attribute instance-attribute

max_condition_number: float = 100000000.0

Requested bound \(\kappa_{\max}>1\) on \(\kappa(\Sigma+\varepsilon I_d)\).

ResidualVariance dataclass

ResidualVariance(*, scale: float = 1.0, rank: int | None = None)

Scale epsilon from discarded low-rank variance.

For ordered covariance eigenvalues \(\lambda_1\leq\cdots\leq\lambda_d\), retained rank \(r\) (rank), and multiplier \(s>0\) (scale), set

\[ \varepsilon = \begin{cases} \displaystyle\frac{s}{d-r}\sum_{j=1}^{d-r}\max(\lambda_j,0), & 1\leq r<d,\\ 0, & r=d. \end{cases} \]

The smallest \(d-r\) eigenvalues are discarded. Negative discarded eigenvalues contribute zero; retaining full rank discards no variance.

Parameters:

  • scale (float, default: 1.0 ) –

    Finite, strictly positive multiplier of the average discarded variance.

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

    Number of leading eigenvalues retained, between one and the covariance dimension. Required by estimate_epsilon and DiagonalLoading; None inherits the enclosing LowRank.rank when used with that regularizer.

Notes

Negative discarded eigenvalues contribute zero. Retaining the full rank produces zero epsilon because no variance is discarded.

rank class-attribute instance-attribute

rank: int | None = None

Retained rank \(r\) defining the discarded covariance spectrum.

scale class-attribute instance-attribute

scale: float = 1.0

Multiplier \(s>0\) of the mean nonnegative discarded eigenvalue.

CovarianceRegularizer module-attribute

CovarianceRegularizer: TypeAlias = (
    DiagonalLoading
    | IsotropicShrinkage
    | DiagonalShrinkage
    | EigenvalueClipping
    | LowRank
)

EpsilonHeuristic module-attribute

EpsilonHeuristic: TypeAlias = (
    RelativeToTrace | TargetConditionNumber | ResidualVariance
)

EpsilonSpec module-attribute

EpsilonSpec: TypeAlias = float | EpsilonHeuristic