tsadmetrics 0.1.17__py3-none-any.whl → 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {docs_api → docs/add_docs/api_doc}/conf.py +3 -26
- {docs_manual → docs/add_docs/full_doc}/conf.py +2 -25
- docs/add_docs/manual_doc/conf.py +67 -0
- docs/conf.py +1 -1
- examples/example_direct_data.py +28 -0
- examples/example_direct_single_data.py +25 -0
- examples/example_file_reference.py +24 -0
- examples/example_global_config_file.py +13 -0
- examples/example_metric_config_file.py +19 -0
- examples/example_simple_metric.py +8 -0
- examples/specific_examples/AbsoluteDetectionDistance_example.py +24 -0
- examples/specific_examples/AffiliationbasedFScore_example.py +24 -0
- examples/specific_examples/AverageDetectionCount_example.py +24 -0
- examples/specific_examples/CompositeFScore_example.py +24 -0
- examples/specific_examples/DelayThresholdedPointadjustedFScore_example.py +24 -0
- examples/specific_examples/DetectionAccuracyInRange_example.py +24 -0
- examples/specific_examples/EnhancedTimeseriesAwareFScore_example.py +24 -0
- examples/specific_examples/LatencySparsityawareFScore_example.py +24 -0
- examples/specific_examples/MeanTimeToDetect_example.py +24 -0
- examples/specific_examples/NabScore_example.py +24 -0
- examples/specific_examples/PateFScore_example.py +24 -0
- examples/specific_examples/Pate_example.py +24 -0
- examples/specific_examples/PointadjustedAtKFScore_example.py +24 -0
- examples/specific_examples/PointadjustedAucPr_example.py +24 -0
- examples/specific_examples/PointadjustedAucRoc_example.py +24 -0
- examples/specific_examples/PointadjustedFScore_example.py +24 -0
- examples/specific_examples/RangebasedFScore_example.py +24 -0
- examples/specific_examples/SegmentwiseFScore_example.py +24 -0
- examples/specific_examples/TemporalDistance_example.py +24 -0
- examples/specific_examples/TimeTolerantFScore_example.py +24 -0
- examples/specific_examples/TimeseriesAwareFScore_example.py +24 -0
- examples/specific_examples/TotalDetectedInRange_example.py +24 -0
- examples/specific_examples/VusPr_example.py +24 -0
- examples/specific_examples/VusRoc_example.py +24 -0
- examples/specific_examples/WeightedDetectionDifference_example.py +24 -0
- tsadmetrics/__init__.py +0 -21
- tsadmetrics/base/Metric.py +188 -0
- tsadmetrics/evaluation/Report.py +25 -0
- tsadmetrics/evaluation/Runner.py +253 -0
- tsadmetrics/metrics/Registry.py +141 -0
- tsadmetrics/metrics/__init__.py +2 -0
- tsadmetrics/metrics/spm/PointwiseAucPr.py +62 -0
- tsadmetrics/metrics/spm/PointwiseAucRoc.py +63 -0
- tsadmetrics/metrics/spm/PointwiseFScore.py +86 -0
- tsadmetrics/metrics/spm/PrecisionAtK.py +81 -0
- tsadmetrics/metrics/spm/__init__.py +9 -0
- tsadmetrics/metrics/tem/dpm/DelayThresholdedPointadjustedFScore.py +83 -0
- tsadmetrics/metrics/tem/dpm/LatencySparsityawareFScore.py +76 -0
- tsadmetrics/metrics/tem/dpm/MeanTimeToDetect.py +47 -0
- tsadmetrics/metrics/tem/dpm/NabScore.py +60 -0
- tsadmetrics/metrics/tem/dpm/__init__.py +11 -0
- tsadmetrics/metrics/tem/ptdm/AverageDetectionCount.py +53 -0
- tsadmetrics/metrics/tem/ptdm/DetectionAccuracyInRange.py +66 -0
- tsadmetrics/metrics/tem/ptdm/PointadjustedAtKFScore.py +80 -0
- tsadmetrics/metrics/tem/ptdm/TimeseriesAwareFScore.py +248 -0
- tsadmetrics/metrics/tem/ptdm/TotalDetectedInRange.py +65 -0
- tsadmetrics/metrics/tem/ptdm/WeightedDetectionDifference.py +97 -0
- tsadmetrics/metrics/tem/ptdm/__init__.py +12 -0
- tsadmetrics/metrics/tem/tmem/AbsoluteDetectionDistance.py +48 -0
- tsadmetrics/metrics/tem/tmem/EnhancedTimeseriesAwareFScore.py +252 -0
- tsadmetrics/metrics/tem/tmem/TemporalDistance.py +68 -0
- tsadmetrics/metrics/tem/tmem/__init__.py +9 -0
- tsadmetrics/metrics/tem/tpdm/CompositeFScore.py +104 -0
- tsadmetrics/metrics/tem/tpdm/PointadjustedAucPr.py +123 -0
- tsadmetrics/metrics/tem/tpdm/PointadjustedAucRoc.py +119 -0
- tsadmetrics/metrics/tem/tpdm/PointadjustedFScore.py +96 -0
- tsadmetrics/metrics/tem/tpdm/RangebasedFScore.py +236 -0
- tsadmetrics/metrics/tem/tpdm/SegmentwiseFScore.py +73 -0
- tsadmetrics/metrics/tem/tpdm/__init__.py +12 -0
- tsadmetrics/metrics/tem/tstm/AffiliationbasedFScore.py +68 -0
- tsadmetrics/metrics/tem/tstm/Pate.py +62 -0
- tsadmetrics/metrics/tem/tstm/PateFScore.py +61 -0
- tsadmetrics/metrics/tem/tstm/TimeTolerantFScore.py +85 -0
- tsadmetrics/metrics/tem/tstm/VusPr.py +51 -0
- tsadmetrics/metrics/tem/tstm/VusRoc.py +55 -0
- tsadmetrics/metrics/tem/tstm/__init__.py +15 -0
- tsadmetrics/{_tsadeval/affiliation/_integral_interval.py → utils/functions_affiliation.py} +377 -9
- tsadmetrics/utils/functions_auc.py +393 -0
- tsadmetrics/utils/functions_conversion.py +63 -0
- tsadmetrics/utils/functions_counting_metrics.py +26 -0
- tsadmetrics/{_tsadeval/latency_sparsity_aware.py → utils/functions_latency_sparsity_aware.py} +1 -1
- tsadmetrics/{_tsadeval/nabscore.py → utils/functions_nabscore.py} +15 -1
- tsadmetrics-1.0.1.dist-info/METADATA +83 -0
- tsadmetrics-1.0.1.dist-info/RECORD +91 -0
- tsadmetrics-1.0.1.dist-info/top_level.txt +3 -0
- entorno/bin/activate_this.py +0 -32
- entorno/bin/rst2html.py +0 -23
- entorno/bin/rst2html4.py +0 -26
- entorno/bin/rst2html5.py +0 -33
- entorno/bin/rst2latex.py +0 -26
- entorno/bin/rst2man.py +0 -27
- entorno/bin/rst2odt.py +0 -28
- entorno/bin/rst2odt_prepstyles.py +0 -20
- entorno/bin/rst2pseudoxml.py +0 -23
- entorno/bin/rst2s5.py +0 -24
- entorno/bin/rst2xetex.py +0 -27
- entorno/bin/rst2xml.py +0 -23
- entorno/bin/rstpep2html.py +0 -25
- tests/test_binary.py +0 -946
- tests/test_non_binary.py +0 -450
- tests/test_utils.py +0 -49
- tsadmetrics/_tsadeval/affiliation/_affiliation_zone.py +0 -86
- tsadmetrics/_tsadeval/affiliation/_single_ground_truth_event.py +0 -68
- tsadmetrics/_tsadeval/affiliation/generics.py +0 -135
- tsadmetrics/_tsadeval/affiliation/metrics.py +0 -114
- tsadmetrics/_tsadeval/auc_roc_pr_plot.py +0 -295
- tsadmetrics/_tsadeval/discontinuity_graph.py +0 -109
- tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/File_IO.py +0 -175
- tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Range.py +0 -50
- tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Time_Plot.py +0 -184
- tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/__init__.py +0 -0
- tsadmetrics/_tsadeval/eTaPR_pkg/__init__.py +0 -0
- tsadmetrics/_tsadeval/eTaPR_pkg/etapr.py +0 -386
- tsadmetrics/_tsadeval/eTaPR_pkg/tapr.py +0 -362
- tsadmetrics/_tsadeval/metrics.py +0 -698
- tsadmetrics/_tsadeval/prts/__init__.py +0 -0
- tsadmetrics/_tsadeval/prts/base/__init__.py +0 -0
- tsadmetrics/_tsadeval/prts/base/time_series_metrics.py +0 -165
- tsadmetrics/_tsadeval/prts/basic_metrics_ts.py +0 -121
- tsadmetrics/_tsadeval/prts/time_series_metrics/__init__.py +0 -0
- tsadmetrics/_tsadeval/prts/time_series_metrics/fscore.py +0 -61
- tsadmetrics/_tsadeval/prts/time_series_metrics/precision.py +0 -86
- tsadmetrics/_tsadeval/prts/time_series_metrics/precision_recall.py +0 -21
- tsadmetrics/_tsadeval/prts/time_series_metrics/recall.py +0 -85
- tsadmetrics/_tsadeval/tests.py +0 -376
- tsadmetrics/_tsadeval/threshold_plt.py +0 -30
- tsadmetrics/_tsadeval/time_tolerant.py +0 -33
- tsadmetrics/binary_metrics.py +0 -1652
- tsadmetrics/metric_utils.py +0 -98
- tsadmetrics/non_binary_metrics.py +0 -372
- tsadmetrics/scripts/__init__.py +0 -0
- tsadmetrics/scripts/compute_metrics.py +0 -42
- tsadmetrics/utils.py +0 -124
- tsadmetrics/validation.py +0 -35
- tsadmetrics-0.1.17.dist-info/METADATA +0 -54
- tsadmetrics-0.1.17.dist-info/RECORD +0 -66
- tsadmetrics-0.1.17.dist-info/entry_points.txt +0 -2
- tsadmetrics-0.1.17.dist-info/top_level.txt +0 -6
- {tests → tsadmetrics/base}/__init__.py +0 -0
- /tsadmetrics/{_tsadeval → evaluation}/__init__.py +0 -0
- /tsadmetrics/{_tsadeval/affiliation → metrics/tem}/__init__.py +0 -0
- /tsadmetrics/{_tsadeval/vus_utils.py → utils/functions_vus.py} +0 -0
- {tsadmetrics-0.1.17.dist-info → tsadmetrics-1.0.1.dist-info}/WHEEL +0 -0
@@ -1,165 +0,0 @@
|
|
1
|
-
from typing import Any
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
|
5
|
-
|
6
|
-
class BaseTimeSeriesMetrics:
|
7
|
-
"""Base class for time series metrics """
|
8
|
-
|
9
|
-
def score(self, real: np.ndarray, pred: np.ndarray) -> Any:
|
10
|
-
"""
|
11
|
-
|
12
|
-
Args:
|
13
|
-
real:
|
14
|
-
pred:
|
15
|
-
|
16
|
-
Returns:
|
17
|
-
|
18
|
-
"""
|
19
|
-
...
|
20
|
-
|
21
|
-
def _udf_gamma(self):
|
22
|
-
"""The function of the user-defined gamma.
|
23
|
-
|
24
|
-
Returns:
|
25
|
-
float: the value of the user-defined gamma
|
26
|
-
"""
|
27
|
-
|
28
|
-
return 1.0
|
29
|
-
|
30
|
-
def _gamma_select(self, gamma: str, overlap: int) -> float:
|
31
|
-
"""The function of selecting the gamma value according to the parameters.
|
32
|
-
|
33
|
-
Args:
|
34
|
-
gamma: str
|
35
|
-
- 'one': the value 1
|
36
|
-
- 'reciprocal';: a reciprocal of the overlap
|
37
|
-
- 'udf_gamma': user defined gamma
|
38
|
-
overlap: int
|
39
|
-
overlap between real and pred
|
40
|
-
|
41
|
-
Returns:
|
42
|
-
float: the selected gamma value
|
43
|
-
"""
|
44
|
-
assert type(overlap) == int, TypeError("")
|
45
|
-
|
46
|
-
if gamma == "one":
|
47
|
-
return 1.0
|
48
|
-
elif gamma == "reciprocal":
|
49
|
-
if overlap > 1:
|
50
|
-
return 1.0 / overlap
|
51
|
-
else:
|
52
|
-
return 1.0
|
53
|
-
elif gamma == "udf_gamma":
|
54
|
-
if overlap > 1:
|
55
|
-
return 1.0 / self._udf_gamma()
|
56
|
-
else:
|
57
|
-
return 1.0
|
58
|
-
else:
|
59
|
-
raise ValueError(f"Expected one of one, reciprocal, udf_gamma. gamma type string: {gamma}")
|
60
|
-
|
61
|
-
def _gamma_function(self, overlap_count):
|
62
|
-
overlap = overlap_count[0]
|
63
|
-
return self._gamma_select(self.cardinality, overlap)
|
64
|
-
|
65
|
-
def _compute_omega_reward(self, r1, r2, overlap_count):
|
66
|
-
if r1[1] < r2[0] or r1[0] > r2[1]:
|
67
|
-
return 0
|
68
|
-
else:
|
69
|
-
overlap_count[0] += 1
|
70
|
-
overlap = np.zeros(r1.shape)
|
71
|
-
overlap[0] = max(r1[0], r2[0])
|
72
|
-
overlap[1] = min(r1[1], r2[1])
|
73
|
-
return self._omega_function(r1, overlap)
|
74
|
-
|
75
|
-
def _omega_function(self, rrange, overlap):
|
76
|
-
anomaly_length = rrange[1] - rrange[0] + 1
|
77
|
-
my_positional_bias = 0
|
78
|
-
max_positional_bias = 0
|
79
|
-
temp_bias = 0
|
80
|
-
for i in range(1, anomaly_length + 1):
|
81
|
-
temp_bias = self._delta_function(i, anomaly_length)
|
82
|
-
max_positional_bias += temp_bias
|
83
|
-
j = rrange[0] + i - 1
|
84
|
-
if j >= overlap[0] and j <= overlap[1]:
|
85
|
-
my_positional_bias += temp_bias
|
86
|
-
if max_positional_bias > 0:
|
87
|
-
res = my_positional_bias / max_positional_bias
|
88
|
-
return res
|
89
|
-
else:
|
90
|
-
return 0
|
91
|
-
|
92
|
-
def _delta_function(self, t, anomaly_length):
|
93
|
-
return self._delta_select(self.bias, t, anomaly_length)
|
94
|
-
|
95
|
-
def _delta_select(self, delta, t, anomaly_length):
|
96
|
-
if delta == "flat":
|
97
|
-
return 1.0
|
98
|
-
elif delta == "front":
|
99
|
-
return float(anomaly_length - t + 1.0)
|
100
|
-
elif delta == "middle":
|
101
|
-
if t <= anomaly_length / 2.0:
|
102
|
-
return float(t)
|
103
|
-
else:
|
104
|
-
return float(anomaly_length - t + 1.0)
|
105
|
-
elif delta == "back":
|
106
|
-
return float(t)
|
107
|
-
elif delta == "udf_delta":
|
108
|
-
return self._udf_delta(t, anomaly_length)
|
109
|
-
else:
|
110
|
-
raise Exception("Invalid positional bias value")
|
111
|
-
|
112
|
-
def _udf_delta(self):
|
113
|
-
"""
|
114
|
-
user defined delta function
|
115
|
-
"""
|
116
|
-
|
117
|
-
return 1.0
|
118
|
-
|
119
|
-
def _shift(self, arr, num, fill_value=np.nan):
|
120
|
-
arr = np.roll(arr, num)
|
121
|
-
if num < 0:
|
122
|
-
arr[num:] = fill_value
|
123
|
-
elif num > 0:
|
124
|
-
arr[:num] = fill_value
|
125
|
-
return arr
|
126
|
-
|
127
|
-
def _prepare_data(self, values_real, values_pred):
|
128
|
-
|
129
|
-
assert len(values_real) == len(values_pred)
|
130
|
-
assert np.allclose(np.unique(values_real), np.array([0, 1])) or np.allclose(
|
131
|
-
np.unique(values_real), np.array([1])
|
132
|
-
)
|
133
|
-
assert np.allclose(np.unique(values_pred), np.array([0, 1])) or np.allclose(
|
134
|
-
np.unique(values_pred), np.array([1])
|
135
|
-
)
|
136
|
-
|
137
|
-
predicted_anomalies_ = np.argwhere(values_pred == 1).ravel()
|
138
|
-
predicted_anomalies_shift_forward = self._shift(predicted_anomalies_, 1, fill_value=predicted_anomalies_[0])
|
139
|
-
predicted_anomalies_shift_backward = self._shift(predicted_anomalies_, -1, fill_value=predicted_anomalies_[-1])
|
140
|
-
predicted_anomalies_start = np.argwhere(
|
141
|
-
(predicted_anomalies_shift_forward - predicted_anomalies_) != -1
|
142
|
-
).ravel()
|
143
|
-
predicted_anomalies_finish = np.argwhere(
|
144
|
-
(predicted_anomalies_ - predicted_anomalies_shift_backward) != -1
|
145
|
-
).ravel()
|
146
|
-
predicted_anomalies = np.hstack(
|
147
|
-
[
|
148
|
-
predicted_anomalies_[predicted_anomalies_start].reshape(-1, 1),
|
149
|
-
predicted_anomalies_[predicted_anomalies_finish].reshape(-1, 1),
|
150
|
-
]
|
151
|
-
)
|
152
|
-
|
153
|
-
real_anomalies_ = np.argwhere(values_real == 1).ravel()
|
154
|
-
real_anomalies_shift_forward = self._shift(real_anomalies_, 1, fill_value=real_anomalies_[0])
|
155
|
-
real_anomalies_shift_backward = self._shift(real_anomalies_, -1, fill_value=real_anomalies_[-1])
|
156
|
-
real_anomalies_start = np.argwhere((real_anomalies_shift_forward - real_anomalies_) != -1).ravel()
|
157
|
-
real_anomalies_finish = np.argwhere((real_anomalies_ - real_anomalies_shift_backward) != -1).ravel()
|
158
|
-
real_anomalies = np.hstack(
|
159
|
-
[
|
160
|
-
real_anomalies_[real_anomalies_start].reshape(-1, 1),
|
161
|
-
real_anomalies_[real_anomalies_finish].reshape(-1, 1),
|
162
|
-
]
|
163
|
-
)
|
164
|
-
|
165
|
-
return real_anomalies, predicted_anomalies
|
@@ -1,121 +0,0 @@
|
|
1
|
-
from .time_series_metrics.fscore import TimeSeriesFScore
|
2
|
-
from .time_series_metrics.precision import TimeSeriesPrecision
|
3
|
-
from .time_series_metrics.recall import TimeSeriesRecall
|
4
|
-
|
5
|
-
|
6
|
-
def ts_precision(real, pred, alpha=0.0, cardinality="one", bias="flat"):
|
7
|
-
"""Compute the range based precision.
|
8
|
-
|
9
|
-
The range based precision is the average of "Precision_Ti", where "Precision_Ti" is
|
10
|
-
the precision score of each predicted anomaly range.
|
11
|
-
"Precision_Ti" for a single predicted anomaly range is calculated by the following formula.
|
12
|
-
Precision_Ti = α x ExistenceReward + (1 - α) x OverlapReward , where 0 ≤ α ≤ 1
|
13
|
-
α represents the relative importance of rewarding existence, whereas
|
14
|
-
(1 − α) represents the relative importance of rewarding size, position, and cardinality.
|
15
|
-
|
16
|
-
"ExistenceReward" is 1 if a real anomaly range has overlap with even a single point of
|
17
|
-
the predicted anomaly range, 0 otherwise.
|
18
|
-
Note: For prediction, there is no need for an existence reward, since precision by definition
|
19
|
-
emphasizes prediction quality, and existence by itself is too low a bar for judging
|
20
|
-
the quality of a prediction (i.e., α = 0).
|
21
|
-
|
22
|
-
"OverlapReward" is calculated by the following formula.
|
23
|
-
OverlapReward = CardinalityFactor x Sum of ω
|
24
|
-
"CardinalityFactor" is 1 if the predicted anomaly range overlaps with only one real anomaly range.
|
25
|
-
Otherwise it receives 0 ≤ γ() ≤ 1 defined by the application.
|
26
|
-
"CardinalityFactor" serves as a scaling factor for the rewards "ω"s, which is earned from overlap
|
27
|
-
size and position.
|
28
|
-
In determing "ω", we consider the size of the correctly predicted portion of an predicted anomaly
|
29
|
-
range and the relative position of the correctly predicted portion of an predicted anomaly range.
|
30
|
-
|
31
|
-
Args:
|
32
|
-
real: np.ndarray
|
33
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
34
|
-
pred: np.ndarray
|
35
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
36
|
-
alpha: float, default=0.0
|
37
|
-
Relative importance of existence reward. 0 ≤ alpha ≤ 1.
|
38
|
-
cardinality: string, default="one"
|
39
|
-
Cardinality type. This should be "one", "reciprocal" or "udf_gamma".
|
40
|
-
bias: string, default="flat"
|
41
|
-
Positional bias. This should be "flat", "front", "middle", or "back"
|
42
|
-
|
43
|
-
Returns:
|
44
|
-
float: precision.score
|
45
|
-
"""
|
46
|
-
precision = TimeSeriesPrecision(alpha, cardinality, bias)
|
47
|
-
return precision.score(real, pred)
|
48
|
-
|
49
|
-
|
50
|
-
def ts_recall(real, pred, alpha=0.0, cardinality="one", bias="flat"):
|
51
|
-
"""Compute the range based recall.
|
52
|
-
|
53
|
-
The range based recall is the average of "Recall_Ti", where "Recall_Ti" is
|
54
|
-
the recall score of each real anomaly range.
|
55
|
-
"Recall_Ti" for a single real anomaly range is calculated by the following formula.
|
56
|
-
Recall_Ti = α x ExistenceReward + (1 - α) x OverlapReward , where 0 ≤ α ≤ 1
|
57
|
-
α represents the relative importance of rewarding existence, whereas
|
58
|
-
(1 − α) represents the relative importance of rewarding size, position, and cardinality.
|
59
|
-
|
60
|
-
"ExistenceReward" is 1 if a prediction captures even a single point of the real anomaly range, 0 otherwise.
|
61
|
-
|
62
|
-
"OverlapReward" is calculated by the following formula.
|
63
|
-
OverlapReward = CardinalityFactor x Sum of ω
|
64
|
-
"CardinalityFactor" is 1 if the real anomaly range overlaps with only one predicted anomaly range.
|
65
|
-
Otherwise it receives 0 ≤ γ() ≤ 1 defined by the application.
|
66
|
-
"CardinalityFactor" serves as a scaling factor for the rewards "ω"s, which is earned from overlap
|
67
|
-
size and position.
|
68
|
-
In determing "ω", we consider the size of the correctly predicted portion of the real anomaly range
|
69
|
-
and the relative
|
70
|
-
position of the correctly predicted portion of the real anomaly range.
|
71
|
-
|
72
|
-
Args:
|
73
|
-
real: np.ndarray
|
74
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
75
|
-
pred: np.ndarray
|
76
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
77
|
-
alpha: float, default=0.0
|
78
|
-
Relative importance of existence reward. 0 ≤ alpha ≤ 1.
|
79
|
-
cardinality: string, default="one"
|
80
|
-
Cardinality type. This should be "one", "reciprocal" or "udf_gamma".
|
81
|
-
bias: string, default="flat"
|
82
|
-
Positional bias. This should be "flat", "front", "middle", or "back"
|
83
|
-
|
84
|
-
Returns:
|
85
|
-
float: recall.score
|
86
|
-
"""
|
87
|
-
recall = TimeSeriesRecall(alpha, cardinality, bias)
|
88
|
-
return recall.score(real, pred)
|
89
|
-
|
90
|
-
|
91
|
-
def ts_fscore(real, pred, beta=1.0, p_alpha=0.0, r_alpha=0.0, cardinality="one", p_bias="flat", r_bias="flat"):
|
92
|
-
"""Compute the range based f-score
|
93
|
-
|
94
|
-
The F-beta score is the weighted harmonic mean of precision and recall,
|
95
|
-
reaching its optimal value at 1 and its worst value at 0.
|
96
|
-
The beta parameter determines the weight of recall in the combined score.
|
97
|
-
beta < 1 lends more weight to precision, while beta > 1 favors recall
|
98
|
-
(beta -> 0 considers only precision, beta -> +inf only recall).
|
99
|
-
|
100
|
-
Args:
|
101
|
-
real: np.ndarray
|
102
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
103
|
-
pred: np.ndarray
|
104
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
105
|
-
p_alpha: float, default=0.0
|
106
|
-
Relative importance of existence reward for precision. 0 ≤ alpha ≤ 1.
|
107
|
-
r_alpha: float, default=0.0
|
108
|
-
Relative importance of existence reward for recall. 0 ≤ alpha ≤ 1.
|
109
|
-
cardinality: string, default="one"
|
110
|
-
Cardinality type. This should be "one", "reciprocal" or "udf_gamma".
|
111
|
-
p_bias: string, default="flat"
|
112
|
-
Positional bias for precision. This should be "flat", "front", "middle", or "back"
|
113
|
-
r_bias: string, default="flat"
|
114
|
-
Positional bias for recall. This should be "flat", "front", "middle", or "back"
|
115
|
-
|
116
|
-
Returns:
|
117
|
-
float: f.score
|
118
|
-
"""
|
119
|
-
|
120
|
-
fscore = TimeSeriesFScore(beta, p_alpha, r_alpha, cardinality, p_bias, r_bias)
|
121
|
-
return fscore.score(real, pred)
|
File without changes
|
@@ -1,61 +0,0 @@
|
|
1
|
-
import numpy as np
|
2
|
-
|
3
|
-
from ..base.time_series_metrics import BaseTimeSeriesMetrics
|
4
|
-
from .precision import TimeSeriesPrecision
|
5
|
-
from .recall import TimeSeriesRecall
|
6
|
-
|
7
|
-
|
8
|
-
class TimeSeriesFScore(BaseTimeSeriesMetrics):
|
9
|
-
""" This class calculates f-score for time series"""
|
10
|
-
|
11
|
-
def __init__(self, beta=1.0, p_alpha=0.0, r_alpha=0.0, cardinality="one", p_bias="flat", r_bias="flat"):
|
12
|
-
"""Constructor
|
13
|
-
|
14
|
-
Args:
|
15
|
-
beta (float, optional): determines the weight of recall in the combined score.. Defaults to 1.0.
|
16
|
-
p_alpha (float, optional): alpha of precision, 0<=alpha_p<=1. Defaults to 0.0.
|
17
|
-
r_alpha (float, optional): alpha of recall, 0<=alpha<=1. Defaults to 0.0.
|
18
|
-
cardinality (str, optional): ["one", "reciprocal", "udf_gamma"]. Defaults to "one".
|
19
|
-
p_bias (str, optional): bias of precision, ["flat", "front", "middle", "back"]. Defaults to "flat".
|
20
|
-
r_bias (str, optional): bias of recall, ["flat", "front", "middle", "back"]. Defaults to "flat".
|
21
|
-
"""
|
22
|
-
|
23
|
-
assert beta >= 0
|
24
|
-
|
25
|
-
self.beta = beta
|
26
|
-
self.p_alpha = p_alpha
|
27
|
-
self.r_alpha = r_alpha
|
28
|
-
self.cardinality = cardinality
|
29
|
-
self.p_bias = p_bias
|
30
|
-
self.r_bias = r_bias
|
31
|
-
|
32
|
-
def score(self, real: np.ndarray, pred: np.ndarray) -> float:
|
33
|
-
"""Computing fbeta score
|
34
|
-
|
35
|
-
Args:
|
36
|
-
real (np.ndarray):
|
37
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
38
|
-
pred (np.ndarray):
|
39
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
40
|
-
|
41
|
-
Returns:
|
42
|
-
float: fbeta
|
43
|
-
"""
|
44
|
-
|
45
|
-
assert isinstance(real, np.ndarray) or isinstance(real, list)
|
46
|
-
assert isinstance(pred, np.ndarray) or isinstance(pred, list)
|
47
|
-
|
48
|
-
if not isinstance(real, np.ndarray):
|
49
|
-
real = np.array(real)
|
50
|
-
if not isinstance(pred, np.ndarray):
|
51
|
-
pred = np.array(pred)
|
52
|
-
|
53
|
-
precision = TimeSeriesPrecision(self.p_alpha, self.cardinality, self.p_bias).score(real, pred)
|
54
|
-
recall = TimeSeriesRecall(self.r_alpha, self.cardinality, self.r_bias).score(real, pred)
|
55
|
-
|
56
|
-
if precision + recall != 0:
|
57
|
-
f_beta = (1 + self.beta ** 2) * precision * recall / (self.beta ** 2 * precision + recall)
|
58
|
-
else:
|
59
|
-
f_beta = 0
|
60
|
-
|
61
|
-
return f_beta
|
@@ -1,86 +0,0 @@
|
|
1
|
-
from typing import Union
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
|
5
|
-
from ..base.time_series_metrics import BaseTimeSeriesMetrics
|
6
|
-
|
7
|
-
|
8
|
-
class TimeSeriesPrecision(BaseTimeSeriesMetrics):
|
9
|
-
""" This class calculates precision for time series"""
|
10
|
-
|
11
|
-
def __init__(self, alpha=0.0, cardinality="one", bias="flat"):
|
12
|
-
"""Constructor
|
13
|
-
|
14
|
-
Args:
|
15
|
-
alpha (float, optional): 0 <= alpha <= 1. Defaults to 0.0.
|
16
|
-
cardinality (str, optional): ["one", "reciprocal", "udf_gamma"]. Defaults to "one".
|
17
|
-
bias (str, optional): ["flat", "front", "middle", "back"]. Defaults to "flat".
|
18
|
-
"""
|
19
|
-
|
20
|
-
assert (alpha >= 0) & (alpha <= 1)
|
21
|
-
assert cardinality in ["one", "reciprocal", "udf_gamma"]
|
22
|
-
assert bias in ["flat", "front", "middle", "back"]
|
23
|
-
|
24
|
-
self.alpha = alpha
|
25
|
-
self.cardinality = cardinality
|
26
|
-
self.bias = bias
|
27
|
-
|
28
|
-
def score(self, real: Union[np.ndarray, list], pred: Union[np.ndarray, list]) -> float:
|
29
|
-
"""Computing precision score
|
30
|
-
|
31
|
-
Args:
|
32
|
-
real (np.ndarray or list):
|
33
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
34
|
-
pred (np.ndarray or list):
|
35
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
36
|
-
|
37
|
-
Returns:
|
38
|
-
float: precision
|
39
|
-
"""
|
40
|
-
|
41
|
-
assert isinstance(real, np.ndarray) or isinstance(real, list)
|
42
|
-
assert isinstance(pred, np.ndarray) or isinstance(pred, list)
|
43
|
-
|
44
|
-
if not isinstance(real, np.ndarray):
|
45
|
-
real = np.array(real)
|
46
|
-
if not isinstance(pred, np.ndarray):
|
47
|
-
pred = np.array(pred)
|
48
|
-
|
49
|
-
real_anomalies, predicted_anomalies = self._prepare_data(real, pred)
|
50
|
-
precision = self._update_precision(real_anomalies, predicted_anomalies)
|
51
|
-
|
52
|
-
return precision
|
53
|
-
|
54
|
-
def _update_precision(self, real_anomalies: np.ndarray, predicted_anomalies: np.ndarray) -> float:
|
55
|
-
"""Update precision
|
56
|
-
|
57
|
-
Args:
|
58
|
-
real_anomalies (np.ndarray):
|
59
|
-
2-dimensional array of the first and last indexes of each real anomaly range.
|
60
|
-
e.g. np.array([[1933, 1953],[1958, 2000], ...])
|
61
|
-
predicted_anomalies (np.ndarray):
|
62
|
-
2-dimensional array of the first and last indexes of each predicted anomaly range.
|
63
|
-
e.g. np.array([[1933, 1953],[1958, 2000], ...])
|
64
|
-
|
65
|
-
Returns:
|
66
|
-
float: precision
|
67
|
-
"""
|
68
|
-
precision = 0
|
69
|
-
if len(predicted_anomalies) == 0:
|
70
|
-
return 0
|
71
|
-
for i in range(len(predicted_anomalies)):
|
72
|
-
range_p = predicted_anomalies[i, :]
|
73
|
-
omega_reward = 0
|
74
|
-
overlap_count = [0]
|
75
|
-
for j in range(len(real_anomalies)):
|
76
|
-
range_r = real_anomalies[j, :]
|
77
|
-
omega_reward += self._compute_omega_reward(range_p, range_r, overlap_count)
|
78
|
-
overlap_reward = self._gamma_function(overlap_count) * omega_reward
|
79
|
-
if overlap_count[0] > 0:
|
80
|
-
existence_reward = 1
|
81
|
-
else:
|
82
|
-
existence_reward = 0
|
83
|
-
|
84
|
-
precision += self.alpha * existence_reward + (1 - self.alpha) * overlap_reward
|
85
|
-
precision /= len(predicted_anomalies)
|
86
|
-
return precision
|
@@ -1,21 +0,0 @@
|
|
1
|
-
from typing import Any
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
|
5
|
-
from prts.base.time_series_metrics import BaseTimeSeriesMetrics
|
6
|
-
|
7
|
-
|
8
|
-
class TimeSeriesPrecisionRecall(BaseTimeSeriesMetrics):
|
9
|
-
""" This class calculates precision and recall for time series """
|
10
|
-
|
11
|
-
def score(self, real: np.ndarray, pred: np.ndarray) -> Any:
|
12
|
-
"""
|
13
|
-
|
14
|
-
Args:
|
15
|
-
real:
|
16
|
-
pred:
|
17
|
-
|
18
|
-
Returns:
|
19
|
-
|
20
|
-
"""
|
21
|
-
# TODO: impl
|
@@ -1,85 +0,0 @@
|
|
1
|
-
from typing import Union
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
|
5
|
-
from ..base.time_series_metrics import BaseTimeSeriesMetrics
|
6
|
-
|
7
|
-
|
8
|
-
class TimeSeriesRecall(BaseTimeSeriesMetrics):
|
9
|
-
""" This class calculates recall for time series """
|
10
|
-
|
11
|
-
def __init__(self, alpha=0.0, cardinality="one", bias="flat"):
|
12
|
-
"""Constructor
|
13
|
-
|
14
|
-
Args:
|
15
|
-
alpha (float, optional): 0 <= alpha <= 1. Defaults to 0.0.
|
16
|
-
cardinality (str, optional): ["one", "reciprocal", "udf_gamma"]. Defaults to "one".
|
17
|
-
bias (str, optional): ["flat", "front", "middle", "back"]. Defaults to "flat".
|
18
|
-
"""
|
19
|
-
|
20
|
-
assert (alpha >= 0) & (alpha <= 1)
|
21
|
-
assert cardinality in ["one", "reciprocal", "udf_gamma"]
|
22
|
-
assert bias in ["flat", "front", "middle", "back"]
|
23
|
-
|
24
|
-
self.alpha = alpha
|
25
|
-
self.cardinality = cardinality
|
26
|
-
self.bias = bias
|
27
|
-
|
28
|
-
def score(self, real: Union[np.ndarray, list], pred: Union[np.ndarray, list]) -> float:
|
29
|
-
"""Computing recall score
|
30
|
-
|
31
|
-
Args:
|
32
|
-
real (np.ndarray or list):
|
33
|
-
One-dimensional array of correct answers with values of 1 or 0.
|
34
|
-
pred (np.ndarray or list):
|
35
|
-
One-dimensional array of predicted answers with values of 1 or 0.
|
36
|
-
Returns:
|
37
|
-
float: recall
|
38
|
-
"""
|
39
|
-
|
40
|
-
assert isinstance(real, np.ndarray) or isinstance(real, list)
|
41
|
-
assert isinstance(pred, np.ndarray) or isinstance(pred, list)
|
42
|
-
|
43
|
-
if not isinstance(real, np.ndarray):
|
44
|
-
real = np.array(real)
|
45
|
-
if not isinstance(pred, np.ndarray):
|
46
|
-
pred = np.array(pred)
|
47
|
-
|
48
|
-
real_anomalies, predicted_anomalies = self._prepare_data(real, pred)
|
49
|
-
recall = self._update_recall(real_anomalies, predicted_anomalies)
|
50
|
-
|
51
|
-
return recall
|
52
|
-
|
53
|
-
def _update_recall(self, real_anomalies: np.ndarray, predicted_anomalies: np.ndarray) -> float:
|
54
|
-
"""Update recall
|
55
|
-
Args:
|
56
|
-
real_anomalies (np.ndarray):
|
57
|
-
2-dimensional array of the first and last indexes of each real anomaly range.
|
58
|
-
e.g. np.array([[1933, 1953],[1958, 2000], ...])
|
59
|
-
predicted_anomalies (np.ndarray):
|
60
|
-
2-dimensional array of the first and last indexes of each predicted anomaly range.
|
61
|
-
e.g. np.array([[1933, 1953],[1958, 2000], ...])
|
62
|
-
Returns:
|
63
|
-
float: recall
|
64
|
-
"""
|
65
|
-
|
66
|
-
recall = 0
|
67
|
-
if len(real_anomalies) == 0:
|
68
|
-
return 0
|
69
|
-
for i in range(len(real_anomalies)):
|
70
|
-
omega_reward = 0
|
71
|
-
overlap_count = [0]
|
72
|
-
range_r = real_anomalies[i, :]
|
73
|
-
for j in range(len(predicted_anomalies)):
|
74
|
-
range_p = predicted_anomalies[j, :]
|
75
|
-
omega_reward += self._compute_omega_reward(range_r, range_p, overlap_count)
|
76
|
-
overlap_reward = self._gamma_function(overlap_count) * omega_reward
|
77
|
-
|
78
|
-
if overlap_count[0] > 0:
|
79
|
-
existence_reward = 1
|
80
|
-
else:
|
81
|
-
existence_reward = 0
|
82
|
-
|
83
|
-
recall += self.alpha * existence_reward + (1 - self.alpha) * overlap_reward
|
84
|
-
recall /= len(real_anomalies)
|
85
|
-
return recall
|