Stats Cov#
cov
#
| CLASS | DESCRIPTION |
|---|---|
RunningCovariance |
Numerically stable running covariance matrix computation. |
Classes#
RunningCovariance(state: dict | None = None)
#
Bases: Stats
Numerically stable running covariance matrix computation.
Computes mean, covariance, correlation, variance, and standard deviation incrementally using the Chan-Golub-LeVeque algorithm. Maintains full covariance matrix between all feature dimensions.
The covariance is computed using incremental updates:
\(\mu_{new} = \mu_{old} + \frac{\sum_i (x_i - \mu_{old})}{n_{total}}\), \(C_{new} = C_{old} + \delta^\top \delta'\)
where:
- \(\delta = x_i - \mu_{old}\) (deviation from old mean)
- \(\delta' = x_i - \mu_{new}\) (deviation from new mean)
- \(C\) is the second central moment matrix
The covariance matrix is then:
\(\Sigma = \frac{C}{n - 1} \quad \text{(unbiased)}\)
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Previous state to restore from.
TYPE:
|
Properties
count : int Total number of samples processed.
data_shape : tuple | None Original shape of feature dimensions.
mean : torch.Tensor | None Current mean estimate (n_features,).
cmom2 : torch.Tensor | None Second central moment matrix (n_features, n_features).
weight_sum : float Cumulative sum of weights (for weighted samples).
Examples:
Basic usage:
>>> from spectre.stats import RunningCovariance
>>> import torch
>>>
>>> stat = RunningCovariance()
>>> for _ in range(10):
... batch = torch.randn(100, 5)
... stat.add(batch)
>>>
>>> mean = stat.mean()
>>> cov = stat.covariance()
>>> corr = stat.correlation()
Extract variance from covariance diagonal:
| METHOD | DESCRIPTION |
|---|---|
add |
Add batch of samples to running covariance computation. |
to |
Move internal tensors to specified device. |
mean |
Get current mean estimate. |
covariance |
Get current covariance matrix estimate. |
correlation |
Get correlation matrix from covariance. |
variance |
Get variance (diagonal of covariance matrix). |
stdev |
Get standard deviation (square root of variance). |
state_dict |
Save state to dictionary. |
load_state_dict |
Load state from dictionary. |
| ATTRIBUTE | DESCRIPTION |
|---|---|
count |
Get total number of samples processed.
TYPE:
|
data_shape |
Get original shape of feature dimensions.
TYPE:
|
weight_sum |
Get total weight of samples processed.
TYPE:
|
Source code in spectre/stats/cov.py
Attributes#
count: int
property
writable
#
Get total number of samples processed.
data_shape: tuple | None
property
writable
#
Get original shape of feature dimensions.
weight_sum: float
property
writable
#
Get total weight of samples processed.
Functions#
add(X: torch.Tensor, weights: torch.Tensor | None = None, *args, **kwargs) -> None
#
Add batch of samples to running covariance computation.
Updates both mean and covariance matrix incrementally using numerically stable Chan algorithm. Supports weighted samples for robust statistics.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Batch of data with shape (n_samples, n_features, ...).
TYPE:
|
weights
|
Sample weights with shape (n_samples,). If None, all samples have equal weight (equivalent to weights=1).
TYPE:
|
Source code in spectre/stats/cov.py
to(device: str = 'cpu') -> None
#
Move internal tensors to specified device.
| PARAMETER | DESCRIPTION |
|---|---|
device
|
Target device ("cpu", "cuda", "cuda:0", etc.).
TYPE:
|
Source code in spectre/stats/cov.py
mean() -> torch.Tensor
#
Get current mean estimate.
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Mean with original feature shape. |
covariance(unbiased: bool = True) -> torch.Tensor
#
Get current covariance matrix estimate.
Computes covariance from the second central moment matrix. For weighted data, uses reliability weights correction when unbiased=True.
| PARAMETER | DESCRIPTION |
|---|---|
unbiased
|
If True, use Bessel's correction for unweighted or reliability weights correction for weighted data. If False, use biased estimate (divide by weight_sum).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Covariance matrix with shape (n_features, n_features). |
Notes
Unbiased weighted covariance uses reliability weights correction: \(\Sigma = C / (W - W^2/W)\) where \(W\) is sum of weights. For equal weights this reduces to Bessel's correction (n-1).
Biased covariance: \(\Sigma = C / W\)
Source code in spectre/stats/cov.py
correlation(unbiased: bool = True) -> torch.Tensor
#
Get correlation matrix from covariance.
Computes Pearson correlation coefficients by normalizing covariance by standard deviations. Properly handles weighted data.
| PARAMETER | DESCRIPTION |
|---|---|
unbiased
|
If True, use unbiased covariance for computation.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Correlation matrix with shape (n_features, n_features). Values range from -1 to 1. |
Notes
Correlation is computed as: \(\rho_{ij} = \frac{\Sigma_{ij}}{\sqrt{\Sigma_{ii} \Sigma_{jj}}}\)
Source code in spectre/stats/cov.py
variance(unbiased: bool = True) -> torch.Tensor | None
#
Get variance (diagonal of covariance matrix).
More efficient than computing full covariance when only variance is needed. Properly handles weighted data.
| PARAMETER | DESCRIPTION |
|---|---|
unbiased
|
If True, use Bessel's correction for unweighted or reliability weights correction for weighted data. If False, use biased estimate (divide by weight_sum).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor | None
|
Variance for each feature with original shape. |
Source code in spectre/stats/cov.py
stdev(unbiased: bool = True) -> torch.Tensor | None
#
Get standard deviation (square root of variance).
| PARAMETER | DESCRIPTION |
|---|---|
unbiased
|
If True, use Bessel's correction (divide by n-1). If False, use biased estimate (divide by n).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor | None
|
Standard deviation for each feature with original shape. |
Source code in spectre/stats/cov.py
state_dict() -> dict
#
Save state to dictionary.
| RETURNS | DESCRIPTION |
|---|---|
dict
|
State dictionary containing count, weight_sum, mean, second moment matrix, and shape info. |
Source code in spectre/stats/cov.py
load_state_dict(state: dict) -> None
#
Load state from dictionary.
Restores the running covariance computation from a saved state.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
State dictionary from
TYPE:
|