Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Created September 12, 2019 13:59
Show Gist options
  • Save Swarchal/65355bd74fd333dbddd8f65681593534 to your computer and use it in GitHub Desktop.
Save Swarchal/65355bd74fd333dbddd8f65681593534 to your computer and use it in GitHub Desktop.
Welford's online/incremental variance calculation
class OnlineVariance:
"""Welfords online variance calculation"""
def __init__(self, arr):
self.arr = arr # np.array
self.mean = arr
self.count = 1
self._M2 = 0
def update(self, arr):
self.count += 1
delta = arr - self.mean
self.mean += delta / self.count
delta_prime = arr - self.mean
self._M2 += delta * delta_prime
self.variance = self._M2 / self.count
self.sample_variance = self._M2 / (self.count - 1)
def __call__(self, x):
self.update(x)
def __repr__(self):
return "count = {}\nvariance =\n{}\nmean =\n{}".format(
self.count, self.variance, self.mean
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment