-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmetrics.py
102 lines (77 loc) · 2.74 KB
/
metrics.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import numpy as np
#np.array
def r_squared(y_true, y_pred, time_axis=0):
""" Computes the R-square index.
The R-squared index is computed separately on each channel.
Parameters
----------
y_true : np.array
Array of true values. If must be at least 2D.
y_pred : np.array
Array of predicted values. If must be compatible with y_true'
time_axis : int
Time axis. All other axes define separate channels.
Returns
-------
r_squared_val : np.array
Array of r_squared value.
"""
SSE = np.sum((y_pred - y_true)**2, axis=time_axis)
y_mean = np.mean(y_true, axis=time_axis)
SST = np.sum((y_true - y_mean)**2, axis=time_axis)
return 1.0 - SSE/SST
def error_rmse(y_true, y_pred, time_axis=0):
""" Computes the Root Mean Square Error (RMSE).
The RMSE index is computed separately on each channel.
Parameters
----------
y_true : np.array
Array of true values. If must be at least 2D.
y_pred : np.array
Array of predicted values. If must be compatible with y_true'
time_axis : int
Time axis. All other axes define separate channels.
Returns
-------
RMSE : np.array
Array of r_squared value.
"""
SSE = np.mean((y_pred - y_true)**2, axis=time_axis)
RMSE = np.sqrt(SSE)
return RMSE
def fit_index(y_true, y_pred, time_axis=0):
""" Computes the per-channel fit index.
The fit index is commonly used in System Identification. See the definitionin the System Identification Toolbox
or in the paper 'Nonlinear System Identification: A User-Oriented Road Map',
https://arxiv.org/abs/1902.00683, page 31.
The fit index is computed separately on each channel.
Parameters
----------
y_true : np.array
Array of true values. If must be at least 2D.
y_pred : np.array
Array of predicted values. If must be compatible with y_true'
time_axis : int
Time axis. All other axes define separate channels.
Returns
-------
fit_val : np.array
Array of r_squared value.
"""
err_norm = np.linalg.norm(y_true - y_pred, axis=time_axis, ord=2) # || y - y_pred ||
y_mean = np.mean(y_true, axis=time_axis)
err_mean_norm = np.linalg.norm(y_true - y_mean, ord=2) # || y - y_mean ||
fit_val = 100*(1 - err_norm/err_mean_norm)
return fit_val
if __name__ == '__main__':
N = 20
ny = 2
SNR = 10
y_true = SNR*np.random.randn(N, 2)
y_pred = np.copy(y_true) + np.random.randn(N, 2)
err_rmse_val = error_rmse(y_pred, y_true)
r_squared_val = r_squared(y_true, y_pred)
fit_val = fit_index(y_true, y_pred)
print(f"RMSE: {err_rmse_val}")
print(f"R-squared: {r_squared_val}")
print(f"fit index: {fit_val}")