Skip to content

Instantly share code, notes, and snippets.

@GongXinyuu
Created October 19, 2019 03:16
Show Gist options
  • Select an option

  • Save GongXinyuu/cc5d2e491104265942894bd0371c920a to your computer and use it in GitHub Desktop.

Select an option

Save GongXinyuu/cc5d2e491104265942894bd0371c920a to your computer and use it in GitHub Desktop.
RunningStats
import collections
class RunningStats:
def __init__(self, WIN_SIZE):
self.mean = 0
self.run_var = 0
self.WIN_SIZE = WIN_SIZE
self.window = collections.deque(maxlen=WIN_SIZE)
def clear(self):
self.window.clear()
self.mean = 0
self.run_var = 0
def is_full(self):
return len(self.window) == self.WIN_SIZE
def push(self, x):
if len(self.window) == self.WIN_SIZE:
# Adjusting variance
x_removed = self.window.popleft()
self.window.append(x)
old_m = self.mean
self.mean += (x - x_removed) / self.WIN_SIZE
self.run_var += (x + x_removed - old_m - self.mean) * (x - x_removed)
else:
# Calculating first variance
self.window.append(x)
delta = x - self.mean
self.mean += delta / len(self.window)
self.run_var += delta * (x - self.mean)
def get_mean(self):
return self.mean if len(self.window) else 0.0
def get_var(self):
return self.run_var / len(self.window) if len(self.window) > 1 else 0.0
def get_std(self):
return math.sqrt(self.get_var())
def get_all(self):
return list(self.window)
def __str__(self):
return "Current window values: {}".format(list(self.window))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment