forked from microsoft/StemGNN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath_utils.py
74 lines (64 loc) · 2.46 KB
/
math_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import numpy as np
def masked_MAPE(v, v_, axis=None):
'''
Mean absolute percentage error.
:param v: np.ndarray or int, ground truth.
:param v_: np.ndarray or int, prediction.
:param axis: axis to do calculation.
:return: int, MAPE averages on all elements of input.
'''
mask = (v == 0)
percentage = np.abs(v_ - v) / np.abs(v)
if np.any(mask):
masked_array = np.ma.masked_array(percentage, mask=mask) # mask the dividing-zero as invalid
result = masked_array.mean(axis=axis)
if isinstance(result, np.ma.MaskedArray):
return result.filled(np.nan)
else:
return result
return np.mean(percentage, axis).astype(np.float64)
def MAPE(v, v_, axis=None):
'''
Mean absolute percentage error.
:param v: np.ndarray or int, ground truth.
:param v_: np.ndarray or int, prediction.
:param axis: axis to do calculation.
:return: int, MAPE averages on all elements of input.
'''
mape = (np.abs(v_ - v) / np.abs(v)+1e-5).astype(np.float64)
mape = np.where(mape > 5, 5, mape)
return np.mean(mape, axis)
def RMSE(v, v_, axis=None):
'''
Mean squared error.
:param v: np.ndarray or int, ground truth.
:param v_: np.ndarray or int, prediction.
:param axis: axis to do calculation.
:return: int, RMSE averages on all elements of input.
'''
return np.sqrt(np.mean((v_ - v) ** 2, axis)).astype(np.float64)
def MAE(v, v_, axis=None):
'''
Mean absolute error.
:param v: np.ndarray or int, ground truth.
:param v_: np.ndarray or int, prediction.
:param axis: axis to do calculation.
:return: int, MAE averages on all elements of input.
'''
return np.mean(np.abs(v_ - v), axis).astype(np.float64)
def evaluate(y, y_hat, by_step=False, by_node=False):
'''
:param y: array in shape of [count, time_step, node].
:param y_hat: in same shape with y.
:param by_step: evaluate by time_step dim.
:param by_node: evaluate by node dim.
:return: array of mape, mae and rmse.
'''
if not by_step and not by_node:
return MAPE(y, y_hat), MAE(y, y_hat), RMSE(y, y_hat)
if by_step and by_node:
return MAPE(y, y_hat, axis=0), MAE(y, y_hat, axis=0), RMSE(y, y_hat, axis=0)
if by_step:
return MAPE(y, y_hat, axis=(0, 2)), MAE(y, y_hat, axis=(0, 2)), RMSE(y, y_hat, axis=(0, 2))
if by_node:
return MAPE(y, y_hat, axis=(0, 1)), MAE(y, y_hat, axis=(0, 1)), RMSE(y, y_hat, axis=(0, 1))