Skip to main content

Welford

Python (Pytorch) implementation calculating Standard Deviation, Variance, Covariance Matrix, and Whitening Matrix online and in parallel. This makes it more memory efficient than computing in the standard way.

This implementation uses Welford's algorithm for variance, and standard deviation. Online Covariance calculation uses a generalization shown on Wikipedia.

The algorithm is described in the followings,

Welford's method is more numerically stable than the standard method. The theoretical background of Welford's method is mentioned in detail on the following blog articles. Please refer them if you are interested in.

This library is a fork of the welford library implemented in Numpy ( https://github.com/a-mitani/welford ).

I later added the covariance calculation inspired by the implementation by Carsten Schelp ( https://carstenschelp.github.io/2019/05/12/Online_Covariance_Algorithm_002.html ). The OnlineCovariance class has feature parity with the normal Welford class, but takes more memory and compute.

Install

Download package via PyPI repository

$ pip install welford-torch

Example (OnlineCovariance)

Example showing how to use OnlineCovariance to compute the covariance and other quantities. If only computing mean, standard deviation and variance, use the Welford class as it is faster and uses less memory. Otherwise, both classes have the same functionality (i.e: .add(), .add_all() and .merge(). See below for examples).

import torch
from welford_torch import OnlineCovariance

# Initialize Welford object, and add samples
w = OnlineCovariance()

dataset = torch.tensor([[-1, 90], [0, 100], [1, 110], [-1, 100], [1, 100]])
for datapoint in dataset:
    w.add(datapoint)

# output
print(w.mean)   # Mean --> [  0., 100.]
print(w.var_s)  # Sample variance --> [ 1., 50.]
print(w.var_p)  # Population variance --> [ 0.8000, 40.0000]
print(w.cov)      # Covariance matrix --> [[ 0.8000,  4.0000], [ 4.0000, 40.0000]]
print(w.corrcoef) # Pearson correlation coefficient --> [[1.0, 0.7071], [0.7071, 1.0000]]
print(w.eig_val)  # Eigenvalues (ascending) --> [ 0.3960, 40.4040]
print(w.eig_vec)  # Eigenvectors --> [[-0.9949,  0.1005], [ 0.1005,  0.9949]]
print(w.whit)     # Whitening Matrix --> [[ 1.5746, -0.1431], [-0.1431,  0.1718]]
print(w.whit_inv) # Whitening Matrix Inverse --> [[0.6871, 0.5726], [0.5726, 6.2986]]

# Whitened dataset
print( (dataset.to(torch.float32) - w.mean) @ w.whit.T )
# --> [[-0.1431, -1.5746],
#      [ 0.0000,  0.0000],
#      [ 0.1431,  1.5746],
#      [-1.5746,  0.1431],
#      [ 1.5746, -0.1431]]

Example (Welford)

For Online Calculation

import numpy as torch
from welford_torch import Welford

# Initialize Welford object
w = Welford()

# Input data samples sequentialy
w.add(torch.tensor([0, 100]))
w.add(torch.tensor([1, 110]))
w.add(torch.tensor([2, 120]))

# output
print(w.mean)  # mean --> [  1. 110.]
print(w.var_s)  # sample variance --> [1, 100]
print(w.var_p)  # population variance --> [ 0.6666 66.66]

# You can add other samples after calculating variances.
w.add(torch.tensor([3, 130]))
w.add(torch.tensor([4, 140]))

# output with added samples
print(w.mean)  # mean --> [  2. 120.]
print(w.var_s)  # sample variance --> [  2.5 250. ]
print(w.var_p)  # population variance --> [  2. 200.]

Welford object supports initialization with data samples and batch addition of samples.

# Initialize Welford object with samples
ini = torch.tensor([[0, 100],
                [1, 110],
                [2, 120]])
w = Welford(ini)

# output
print(w.mean)  # mean --> [  1. 110.]
print(w.var_s)  # sample variance --> [1, 100]
print(w.var_p)  # population variance --> [ 0.66666667 66.66666667]

# add other samples through batch method
other_samples = torch.tensor([[3, 130],
                          [4, 140]])
w.add_all(other_samples)

# output with added samples
print(w.mean)  # mean --> [  2. 120.]
print(w.var_s)  # sample variance --> [  2.5 250. ]
print(w.var_p)  # population variance --> [  2. 200.]

For Parallel Calculation

Welford also offers parallel calculation method for variance.

import numpy as torch
from welford_torch import Welford

# Initialize two Welford objects
w_1 = Welford()
w_2 = Welford()

# Each object will calculate variance of each samples in parallel.
# On w_1
w_1.add(torch.tensor([0, 100]))
w_1.add(torch.tensor([1, 110]))
w_1.add(torch.tensor([2, 120]))
print(w_1.var_s)  # sample variance -->[  1. 100.]
print(w_1.var_p)  # population variance -->[ 0.66666667 66.66666667]

# On w_2
w_2.add(torch.tensor([3, 130]))
w_2.add(torch.tensor([4, 140]))
print(w_2.var_s)  # sample variance -->[ 0.5 50. ]
print(w_2.var_p)  # sample variance -->[ 0.25 25.  ]

# You can Merge objects to get variance of WHOLE samples
w_1.merge(w_2)
print(w.var_s)  # sample variance --> [  2.5 250. ]
print(w_1.var_p)  # sample variance -->[  2. 200.]

Metadata

Release files for welford-torch 0.2.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for welford-torch 0.2.5
File Size Uploaded
welford_torch-0.2.5.tar.gz 13.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for welford-torch 0.2.5
File Interpreter ABI Platform
welford_torch-0.2.5-py3-none-any.whl Python 3 none any Details

Total release size: 27.2 kB

Release files / welford_torch-0.2.5.tar.gz

Download URL welford_torch-0.2.5.tar.gz
Size 13.3 kB
Tags Source
SHA-256 checksum
How to use checksums
228f970aaaf7dcd595747a43db6eb7358cf0bb86873b1a9f7975e0b81902e761
BLAKE2b-256 checksum
How to use checksums
320f3d7dcc3f08b8d3914624c1ea76811d34c85267415f71b2b497b132bdfd39
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Release files / welford_torch-0.2.5-py3-none-any.whl

Download URL welford_torch-0.2.5-py3-none-any.whl
Size 14.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0b5966701c5b37ad2cb4658e379be201b7f9252a5f8aac3accedeeee6a5f6f2c
BLAKE2b-256 checksum
How to use checksums
1bf53cd8bac1f78b3c5cbf9bfaa17b07b4d66cc733d595a69aaa6cff57a6bdba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.12

Release history Release notifications | RSS feed

This release

0.2.5 This release

2 release files

0.2.4

2 release files

0.2.3

2 release files

0.2.2

2 release files

0.2.1

1 release file

0.2.0

1 release file

0.1.2

1 release file

0.1.1

1 release file

0.1.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page