Last active
February 18, 2019 05:41
-
-
Save nagadomi/23cc73e6e8c7d8ede0662b509acbecbc to your computer and use it in GitHub Desktop.
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
import numpy as np | |
from timeit import timeit | |
from collections import deque | |
# online running meanstd. ref https://github.com/ajcr/rolling/tree/master/rolling | |
class TimeRunningMeanStd(object): | |
def __init__(self, shape, ttl): | |
self.ttl = ttl | |
self.mean = np.zeros(shape, dtype=np.float64) | |
self.std = np.ones(shape, dtype=np.float64) | |
self.sslm = np.zeros(shape, dtype=np.float64) | |
self._x = deque() | |
self._t = deque() | |
self.update_count = 0 | |
def _add_new(self, new, t): | |
self._x.append(new) | |
self._t.append(t) | |
delta = new - self.mean | |
self.mean += delta / len(self._t) | |
self.sslm += delta * (new - self.mean) | |
def _remove_old(self): | |
old = self._x.popleft() | |
self._t.popleft() | |
delta = old - self.mean | |
self.mean -= delta / (len(self._t)) | |
self.sslm -= delta * (old - self.mean) | |
def get_error(self): | |
mean_error = np.abs(self.mean - np.mean(self._x, axis=0)).sum() | |
std_error = np.abs(self.std - np.std(self._x, axis=0)).sum() | |
return mean_error, std_error | |
def update(self, x, timestamp): | |
self.update_count += 1 | |
if self.update_count > 100000000: | |
self.update_count = 0 | |
self._add_new(x, timestamp) | |
limit = self._t[-1] - self.ttl | |
while self._t[0] < limit: | |
self._remove_old() | |
if not self._t: | |
break | |
if self._t: | |
if self.update_count % 10000 == 0: | |
# fix cumulative error | |
self.mean = np.mean(self._x, axis=0, dtype=np.float64) | |
self.sslm = np.var(self._x, axis=0, dtype=np.float64) * len(self._t) | |
self.std = np.sqrt(self.sslm / len(self._t)) + 1e-13 | |
else: | |
self.mean.fill(0) | |
self.sslm.fill(0) | |
self.std.fill(1) | |
if __name__ == "__main__": | |
m = TimeRunningMeanStd(shape=(64,), ttl=60*15) | |
t = 0.0 | |
last_t = 0 | |
while t < 300*60: | |
x = np.zeros((64,)) | |
t += np.random.uniform(0.001, 0.1) | |
for i in range(64): | |
x[i] = np.random.normal(i, i) | |
m.update(x, t) | |
if t - last_t > 60: | |
last_t = t | |
me, se = m.get_error() | |
print(round(t/60.0), "mean_error", me, "std_error", se) |
Author
nagadomi
commented
Feb 8, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment