Created
July 16, 2015 22:05
-
-
Save kcarnold/49e2750868a862f2e47b to your computer and use it in GitHub Desktop.
Incremental Moments
This file contains hidden or 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
import numpy as np | |
class IncrementalMoments(object): | |
'''Knuth's incremental mean and variance computation, applied elementwise.''' | |
def __init__(self, shape, initial_items=[]): | |
self.n = 0 | |
self.mean = np.zeros(shape) | |
self.m2 = np.zeros(shape) | |
self.update_seq(initial_items) | |
def update(self, x): | |
self.n += 1 | |
delta = x - self.mean | |
self.mean += delta / self.n | |
self.m2 += delta * (x - self.mean) | |
def update_seq(self, items): | |
for item in items: | |
self.update(item) | |
@property | |
def variance(self): | |
return self.m2 / (self.n - 1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment