Tianshou/tianshou/utils/moving_average.py

36 lines
855 B
Python
Raw Normal View History

2020-03-14 21:48:31 +08:00
import torch
2020-03-12 22:20:33 +08:00
import numpy as np
class MovAvg(object):
def __init__(self, size=100):
super().__init__()
self.size = size
self.cache = []
def add(self, x):
2020-03-14 21:48:31 +08:00
if isinstance(x, torch.Tensor):
2020-03-12 22:20:33 +08:00
x = x.detach().cpu().numpy()
2020-03-17 11:37:31 +08:00
if isinstance(x, list):
for _ in x:
if _ != np.inf:
self.cache.append(_)
elif x != np.inf:
2020-03-12 22:20:33 +08:00
self.cache.append(x)
if self.size > 0 and len(self.cache) > self.size:
self.cache = self.cache[-self.size:]
return self.get()
def get(self):
if len(self.cache) == 0:
return 0
return np.mean(self.cache)
2020-03-15 17:41:00 +08:00
def mean(self):
return self.get()
def std(self):
if len(self.cache) == 0:
return 0
return np.std(self.cache)