TrulyPPO/baselines/common/running_mean_std.py
2020-01-17 12:30:26 +08:00

72 lines
2.3 KiB
Python

import numpy as np
class RunningMeanStd(object):
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm
def __init__(self, epsilon=1e-4, shape=()):
self.mean = np.zeros(shape, 'float64')
self.var = np.ones(shape, 'float64')
self.count = epsilon
self.variables_name_save = [ 'mean','var','count', ]
# TODO: refer to the code of soft actor critic for more elegent writing.
def save(self ):
variables = []
for v in self.variables_name_save:
variables.append( getattr(self,v) )
return variables
def load(self, variables):
for i, v in enumerate( self.variables_name_save ):
setattr(self,v, variables[i] )
def update(self, x):
batch_mean = np.mean(x, axis=0)
batch_var = np.var(x, axis=0)
batch_count = x.shape[0]
self.update_from_moments(batch_mean, batch_var, batch_count)
def update_from_moments(self, batch_mean, batch_var, batch_count):
delta = batch_mean - self.mean
tot_count = self.count + batch_count
new_mean = self.mean + delta * batch_count / tot_count
m_a = self.var * (self.count)
m_b = batch_var * (batch_count)
M2 = m_a + m_b + np.square(delta) * self.count * batch_count / (self.count + batch_count)
new_var = M2 / (self.count + batch_count)
new_count = batch_count + self.count
self.mean = new_mean
self.var = new_var
self.count = new_count
# def test_loadsave():
# a = RunningMeanStd()
# vs = a.save()
# a.load(vs)
def test_runningmeanstd():
for (x1, x2, x3) in [
(np.random.randn(3), np.random.randn(4), np.random.randn(5)),
(np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
]:
rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])
x = np.concatenate([x1, x2, x3], axis=0)
ms1 = [x.mean(axis=0), x.var(axis=0)]
rms.update(x1)
rms.update(x2)
rms.update(x3)
ms2 = [rms.mean, rms.var]
assert np.allclose(ms1, ms2)
rms_new = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])
rms_new.load( rms.save() )
print('-'*10)
print( rms_new.save() , '\n', rms.save() )
assert rms_new.save() == rms.save()