Created
September 12, 2019 13:59
-
-
Save Swarchal/65355bd74fd333dbddd8f65681593534 to your computer and use it in GitHub Desktop.
Welford's online/incremental variance calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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