tsadmetrics 0.1.16__py3-none-any.whl → 1.0.0__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.
Files changed (148) hide show
  1. docs/api_doc/conf.py +67 -0
  2. docs/{conf.py → full_doc/conf.py} +1 -1
  3. docs/manual_doc/conf.py +67 -0
  4. examples/example_direct_data.py +28 -0
  5. examples/example_direct_single_data.py +25 -0
  6. examples/example_file_reference.py +24 -0
  7. examples/example_global_config_file.py +13 -0
  8. examples/example_metric_config_file.py +19 -0
  9. examples/example_simple_metric.py +8 -0
  10. examples/specific_examples/AbsoluteDetectionDistance_example.py +24 -0
  11. examples/specific_examples/AffiliationbasedFScore_example.py +24 -0
  12. examples/specific_examples/AverageDetectionCount_example.py +24 -0
  13. examples/specific_examples/CompositeFScore_example.py +24 -0
  14. examples/specific_examples/DelayThresholdedPointadjustedFScore_example.py +24 -0
  15. examples/specific_examples/DetectionAccuracyInRange_example.py +24 -0
  16. examples/specific_examples/EnhancedTimeseriesAwareFScore_example.py +24 -0
  17. examples/specific_examples/LatencySparsityawareFScore_example.py +24 -0
  18. examples/specific_examples/MeanTimeToDetect_example.py +24 -0
  19. examples/specific_examples/NabScore_example.py +24 -0
  20. examples/specific_examples/PateFScore_example.py +24 -0
  21. examples/specific_examples/Pate_example.py +24 -0
  22. examples/specific_examples/PointadjustedAtKFScore_example.py +24 -0
  23. examples/specific_examples/PointadjustedAucPr_example.py +24 -0
  24. examples/specific_examples/PointadjustedAucRoc_example.py +24 -0
  25. examples/specific_examples/PointadjustedFScore_example.py +24 -0
  26. examples/specific_examples/RangebasedFScore_example.py +24 -0
  27. examples/specific_examples/SegmentwiseFScore_example.py +24 -0
  28. examples/specific_examples/TemporalDistance_example.py +24 -0
  29. examples/specific_examples/TimeTolerantFScore_example.py +24 -0
  30. examples/specific_examples/TimeseriesAwareFScore_example.py +24 -0
  31. examples/specific_examples/TotalDetectedInRange_example.py +24 -0
  32. examples/specific_examples/VusPr_example.py +24 -0
  33. examples/specific_examples/VusRoc_example.py +24 -0
  34. examples/specific_examples/WeightedDetectionDifference_example.py +24 -0
  35. tests/test_dpm.py +212 -0
  36. tests/test_ptdm.py +366 -0
  37. tests/test_registry.py +58 -0
  38. tests/test_runner.py +185 -0
  39. tests/test_spm.py +213 -0
  40. tests/test_tmem.py +198 -0
  41. tests/test_tpdm.py +369 -0
  42. tests/test_tstm.py +338 -0
  43. tsadmetrics/__init__.py +0 -21
  44. tsadmetrics/base/Metric.py +188 -0
  45. tsadmetrics/evaluation/Report.py +25 -0
  46. tsadmetrics/evaluation/Runner.py +253 -0
  47. tsadmetrics/metrics/Registry.py +141 -0
  48. tsadmetrics/metrics/__init__.py +2 -0
  49. tsadmetrics/metrics/spm/PointwiseAucPr.py +62 -0
  50. tsadmetrics/metrics/spm/PointwiseAucRoc.py +63 -0
  51. tsadmetrics/metrics/spm/PointwiseFScore.py +86 -0
  52. tsadmetrics/metrics/spm/PrecisionAtK.py +81 -0
  53. tsadmetrics/metrics/spm/__init__.py +9 -0
  54. tsadmetrics/metrics/tem/dpm/DelayThresholdedPointadjustedFScore.py +83 -0
  55. tsadmetrics/metrics/tem/dpm/LatencySparsityawareFScore.py +76 -0
  56. tsadmetrics/metrics/tem/dpm/MeanTimeToDetect.py +47 -0
  57. tsadmetrics/metrics/tem/dpm/NabScore.py +60 -0
  58. tsadmetrics/metrics/tem/dpm/__init__.py +11 -0
  59. tsadmetrics/metrics/tem/ptdm/AverageDetectionCount.py +53 -0
  60. tsadmetrics/metrics/tem/ptdm/DetectionAccuracyInRange.py +66 -0
  61. tsadmetrics/metrics/tem/ptdm/PointadjustedAtKFScore.py +80 -0
  62. tsadmetrics/metrics/tem/ptdm/TimeseriesAwareFScore.py +248 -0
  63. tsadmetrics/metrics/tem/ptdm/TotalDetectedInRange.py +65 -0
  64. tsadmetrics/metrics/tem/ptdm/WeightedDetectionDifference.py +97 -0
  65. tsadmetrics/metrics/tem/ptdm/__init__.py +12 -0
  66. tsadmetrics/metrics/tem/tmem/AbsoluteDetectionDistance.py +48 -0
  67. tsadmetrics/metrics/tem/tmem/EnhancedTimeseriesAwareFScore.py +252 -0
  68. tsadmetrics/metrics/tem/tmem/TemporalDistance.py +68 -0
  69. tsadmetrics/metrics/tem/tmem/__init__.py +9 -0
  70. tsadmetrics/metrics/tem/tpdm/CompositeFScore.py +104 -0
  71. tsadmetrics/metrics/tem/tpdm/PointadjustedAucPr.py +123 -0
  72. tsadmetrics/metrics/tem/tpdm/PointadjustedAucRoc.py +119 -0
  73. tsadmetrics/metrics/tem/tpdm/PointadjustedFScore.py +96 -0
  74. tsadmetrics/metrics/tem/tpdm/RangebasedFScore.py +236 -0
  75. tsadmetrics/metrics/tem/tpdm/SegmentwiseFScore.py +73 -0
  76. tsadmetrics/metrics/tem/tpdm/__init__.py +12 -0
  77. tsadmetrics/metrics/tem/tstm/AffiliationbasedFScore.py +68 -0
  78. tsadmetrics/metrics/tem/tstm/Pate.py +62 -0
  79. tsadmetrics/metrics/tem/tstm/PateFScore.py +61 -0
  80. tsadmetrics/metrics/tem/tstm/TimeTolerantFScore.py +85 -0
  81. tsadmetrics/metrics/tem/tstm/VusPr.py +51 -0
  82. tsadmetrics/metrics/tem/tstm/VusRoc.py +55 -0
  83. tsadmetrics/metrics/tem/tstm/__init__.py +15 -0
  84. tsadmetrics/{_tsadeval/affiliation/_integral_interval.py → utils/functions_affiliation.py} +377 -9
  85. tsadmetrics/utils/functions_auc.py +393 -0
  86. tsadmetrics/utils/functions_conversion.py +63 -0
  87. tsadmetrics/utils/functions_counting_metrics.py +26 -0
  88. tsadmetrics/{_tsadeval/latency_sparsity_aware.py → utils/functions_latency_sparsity_aware.py} +1 -1
  89. tsadmetrics/{_tsadeval/nabscore.py → utils/functions_nabscore.py} +15 -1
  90. tsadmetrics-1.0.0.dist-info/METADATA +69 -0
  91. tsadmetrics-1.0.0.dist-info/RECORD +99 -0
  92. {tsadmetrics-0.1.16.dist-info → tsadmetrics-1.0.0.dist-info}/top_level.txt +1 -1
  93. entorno/bin/activate_this.py +0 -32
  94. entorno/bin/rst2html.py +0 -23
  95. entorno/bin/rst2html4.py +0 -26
  96. entorno/bin/rst2html5.py +0 -33
  97. entorno/bin/rst2latex.py +0 -26
  98. entorno/bin/rst2man.py +0 -27
  99. entorno/bin/rst2odt.py +0 -28
  100. entorno/bin/rst2odt_prepstyles.py +0 -20
  101. entorno/bin/rst2pseudoxml.py +0 -23
  102. entorno/bin/rst2s5.py +0 -24
  103. entorno/bin/rst2xetex.py +0 -27
  104. entorno/bin/rst2xml.py +0 -23
  105. entorno/bin/rstpep2html.py +0 -25
  106. tests/test_binary.py +0 -946
  107. tests/test_non_binary.py +0 -420
  108. tests/test_utils.py +0 -49
  109. tsadmetrics/_tsadeval/affiliation/_affiliation_zone.py +0 -86
  110. tsadmetrics/_tsadeval/affiliation/_single_ground_truth_event.py +0 -68
  111. tsadmetrics/_tsadeval/affiliation/generics.py +0 -135
  112. tsadmetrics/_tsadeval/affiliation/metrics.py +0 -114
  113. tsadmetrics/_tsadeval/auc_roc_pr_plot.py +0 -295
  114. tsadmetrics/_tsadeval/discontinuity_graph.py +0 -109
  115. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/File_IO.py +0 -175
  116. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Range.py +0 -50
  117. tsadmetrics/_tsadeval/eTaPR_pkg/DataManage/Time_Plot.py +0 -184
  118. tsadmetrics/_tsadeval/eTaPR_pkg/__init__.py +0 -0
  119. tsadmetrics/_tsadeval/eTaPR_pkg/etapr.py +0 -386
  120. tsadmetrics/_tsadeval/eTaPR_pkg/tapr.py +0 -362
  121. tsadmetrics/_tsadeval/metrics.py +0 -698
  122. tsadmetrics/_tsadeval/prts/__init__.py +0 -0
  123. tsadmetrics/_tsadeval/prts/base/__init__.py +0 -0
  124. tsadmetrics/_tsadeval/prts/base/time_series_metrics.py +0 -165
  125. tsadmetrics/_tsadeval/prts/basic_metrics_ts.py +0 -121
  126. tsadmetrics/_tsadeval/prts/time_series_metrics/__init__.py +0 -0
  127. tsadmetrics/_tsadeval/prts/time_series_metrics/fscore.py +0 -61
  128. tsadmetrics/_tsadeval/prts/time_series_metrics/precision.py +0 -86
  129. tsadmetrics/_tsadeval/prts/time_series_metrics/precision_recall.py +0 -21
  130. tsadmetrics/_tsadeval/prts/time_series_metrics/recall.py +0 -85
  131. tsadmetrics/_tsadeval/tests.py +0 -376
  132. tsadmetrics/_tsadeval/threshold_plt.py +0 -30
  133. tsadmetrics/_tsadeval/time_tolerant.py +0 -33
  134. tsadmetrics/binary_metrics.py +0 -1652
  135. tsadmetrics/metric_utils.py +0 -98
  136. tsadmetrics/non_binary_metrics.py +0 -398
  137. tsadmetrics/scripts/__init__.py +0 -0
  138. tsadmetrics/scripts/compute_metrics.py +0 -42
  139. tsadmetrics/utils.py +0 -122
  140. tsadmetrics/validation.py +0 -35
  141. tsadmetrics-0.1.16.dist-info/METADATA +0 -23
  142. tsadmetrics-0.1.16.dist-info/RECORD +0 -64
  143. tsadmetrics-0.1.16.dist-info/entry_points.txt +0 -2
  144. /tsadmetrics/{_tsadeval → base}/__init__.py +0 -0
  145. /tsadmetrics/{_tsadeval/affiliation → evaluation}/__init__.py +0 -0
  146. /tsadmetrics/{_tsadeval/eTaPR_pkg/DataManage → metrics/tem}/__init__.py +0 -0
  147. /tsadmetrics/{_tsadeval/vus_utils.py → utils/functions_vus.py} +0 -0
  148. {tsadmetrics-0.1.16.dist-info → tsadmetrics-1.0.0.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)
@@ -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