tsadmetrics 0.1.1__py3-none-any.whl → 0.1.3__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.
@@ -0,0 +1,294 @@
1
+ # BSD License
2
+ #
3
+ # Copyright (c) 2021, eBay Inc
4
+ # All rights reserved.
5
+ #
6
+ # Redistribution and use in source and binary forms, with or without modification,
7
+ # are permitted provided that the following conditions are met:
8
+ #
9
+ # * Redistributions of source code must retain the above copyright notice, this
10
+ # list of conditions and the following disclaimer.
11
+ #
12
+ # * Redistributions in binary form must reproduce the above copyright notice, this
13
+ # list of conditions and the following disclaimer in the documentation and/or
14
+ # other materials provided with the distribution.
15
+ #
16
+ # * Neither the name of the copyright holder nor the names of its
17
+ # contributors may be used to endorse or promote products derived from this
18
+ # software without specific prior written permission.
19
+ #
20
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23
+ # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
24
+ # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
27
+ # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
28
+ # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
29
+ # OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+
32
+
33
+ # -*- coding: utf-8 -*-
34
+ import numpy as np
35
+
36
+
37
+ def calc_point2point(predict, actual):
38
+ """
39
+ calculate f1 score by predict and actual.
40
+
41
+ Args:
42
+ predict (np.ndarray): the predict label
43
+ actual (np.ndarray): np.ndarray
44
+ """
45
+ TP = np.sum(predict * actual)
46
+ TN = np.sum((1 - predict) * (1 - actual))
47
+ FP = np.sum(predict * (1 - actual))
48
+ FN = np.sum((1 - predict) * actual)
49
+ precision = TP / (TP + FP + 0.00001)
50
+ recall = TP / (TP + FN + 0.00001)
51
+ f1 = 2 * precision * recall / (precision + recall + 0.00001)
52
+ FPR = FP / (FP + TN + 0.00001)
53
+ return f1, precision, recall, FPR, TP, TN, FP, FN
54
+
55
+
56
+ def adjust_predicts(score, label,
57
+ threshold=None,
58
+ pred=None,
59
+ calc_latency=False):
60
+ """
61
+ Calculate adjusted predict labels using given `score`, `threshold` (or given `pred`) and `label`.
62
+
63
+ Args:
64
+ score (np.ndarray): The anomaly score
65
+ label (np.ndarray): The ground-truth label
66
+ threshold (float): The threshold of anomaly score.
67
+ A point is labeled as "anomaly" if its score is lower than the threshold.
68
+ pred (np.ndarray or None): if not None, adjust `pred` and ignore `score` and `threshold`,
69
+ calc_latency (bool):
70
+
71
+ Returns:
72
+ np.ndarray: predict labels
73
+ """
74
+ if len(score) != len(label):
75
+ raise ValueError("score and label must have the same length")
76
+ score = np.asarray(score)
77
+ label = np.asarray(label)
78
+ latency = 0
79
+ if pred is None:
80
+ predict = score < threshold
81
+ else:
82
+ predict = pred
83
+ actual = label > 0.1
84
+ anomaly_state = False
85
+ anomaly_count = 0
86
+ for i in range(len(score)):
87
+ if actual[i] and predict[i] and not anomaly_state:
88
+ anomaly_state = True
89
+ anomaly_count += 1
90
+ for j in range(i, 0, -1):
91
+ if not actual[j]:
92
+ break
93
+ else:
94
+ if not predict[j]:
95
+ predict[j] = True
96
+ latency += 1
97
+ elif not actual[i]:
98
+ anomaly_state = False
99
+ if anomaly_state:
100
+ predict[i] = True
101
+ if calc_latency:
102
+ return predict, latency / (anomaly_count + 1e-4)
103
+ else:
104
+ return predict
105
+
106
+
107
+ def calc_seq(score, label, threshold, pred=None, calc_latency=False):
108
+ """
109
+ Calculate f1 score for a score sequence
110
+ """
111
+ if calc_latency:
112
+ predict, latency = adjust_predicts(score, label, threshold, pred=pred, calc_latency=calc_latency)
113
+ t = list(calc_point2point(predict, label))
114
+ t.append(latency)
115
+ return t
116
+ else:
117
+ predict = adjust_predicts(score, label, threshold, pred=pred, calc_latency=calc_latency)
118
+ return calc_point2point(predict, label)
119
+
120
+
121
+ def bf_search(score, label, start, end=None, step_num=1, display_freq=1, verbose=True, direction='>'):
122
+ """
123
+ Find the best-f1 score by searching best `threshold` in [`start`, `end`).
124
+
125
+
126
+ Returns:
127
+ list: list for results
128
+ float: the `threshold` for best-f1
129
+ """
130
+ if step_num is None or end is None:
131
+ end = start
132
+ step_num = 1
133
+ search_step, search_range, search_lower_bound = step_num, end - start, start
134
+ if verbose:
135
+ print("search range: ", search_lower_bound, search_lower_bound + search_range)
136
+ threshold = search_lower_bound
137
+ m = (-1., -1., -1.)
138
+ m_t = 0.0
139
+ m_90 = (-1., -1., -1.)
140
+ m_t_90 = 0.0
141
+ for i in range(search_step):
142
+ threshold += search_range / float(search_step)
143
+ pred = eval('score{}threshold'.format(direction))
144
+ target = calc_seq(score, label, threshold, pred=pred, calc_latency=True)
145
+ if target[0] > m[0]:
146
+ m_t = threshold
147
+ m = target
148
+ if target[3] <= 0.1 and target[0] > m_90[0]:
149
+ m_t_90 = threshold
150
+ m_90 = target
151
+ if verbose and i % display_freq == 0:
152
+ print("cur thr: ", threshold, target, m, m_t, m_90, m_t_90)
153
+ print(m, m_t, m_90, m_t_90)
154
+ return m, m_t
155
+
156
+ #...............................................................................................................................
157
+ def blind_bf_search(
158
+ score, label, val, start, end=None, step_num=1, guess=None, display_freq=1, verbose=True, tw=15, normal=0, direction='>'
159
+ ):
160
+ """
161
+ Find the best-f1 score by searching best `threshold` in [`start`, `end`] for an potion of the test set, then evaluate on a
162
+ hold-out (i.e. blind) set.
163
+
164
+ Params:
165
+ score: The anomaly detection results
166
+ label: The target labels (ground truth)
167
+ val: tuple or list of the results and labels to be used for threshold tuning
168
+ start: the minimum threshold
169
+ end: the maximum threshold
170
+ step_num: the number of steps to search between start and end
171
+ guess: The default threshold to use if no labels were present and no false positives obtained
172
+ display_freq: frequency of printing out current iteration summary
173
+ verbose: whether to print out summary
174
+ tw: The resampling frequency for avoiding overcounting TP & FP or undercounting FN & TN (i.e. batch_size)
175
+ normal: the value of normal behavior
176
+ direction: directuib of the anomaly from the threshold (< for OMNI)
177
+
178
+ Returns:
179
+ list: list for results
180
+ float: the `threshold` for best-f1
181
+ """
182
+ score_val, label_val = val
183
+ if step_num is None or end is None:
184
+ end = start
185
+ step_num = 1
186
+ search_step, search_range, search_lower_bound = step_num, end - start, start
187
+ if verbose:
188
+ print("search range: ", search_lower_bound, search_lower_bound + search_range)
189
+ if guess is None:
190
+ guess = (start + end) / 2 # automatically select guess as the midpoint if not provided
191
+ threshold = search_lower_bound
192
+ m = (-1., -1., -1.)
193
+ m_t = 0.0
194
+ for i in range(search_step):
195
+ threshold += search_range / float(search_step)
196
+ pred = eval('score_val{}threshold'.format(direction))
197
+ if np.abs(label_val - normal).max() or pred.max():
198
+ target = calc_twseq(score_val, label_val, normal, threshold, tw, pred=pred)
199
+ if target[0] > m[0]:
200
+ m_t = threshold
201
+ m = target
202
+ if verbose and i % display_freq == 0:
203
+ print("cur in-sample thr: ", threshold, target, m, m_t)
204
+ else:
205
+ continue
206
+ threshold = m_t # this is the best threhsold found
207
+ if threshold == 0.0:
208
+ threshold = guess
209
+ if verbose:
210
+ print("No true labels or false detections to tune threshold, using a guessed threshold instead...")
211
+ blind_target = calc_twseq(score, label, normal, threshold, tw, pred=eval('score{}threshold'.format(direction)))
212
+ m, m_t = blind_target, threshold
213
+ print('\nOut-of-sample score:')
214
+ print(m, m_t)
215
+ return m, m_t
216
+
217
+ def calc_twseq(score, label, normal, threshold, tw, pred=None):
218
+ """
219
+ Calculate f1 score for a score sequence, resampled at non-rolling time-window
220
+ """
221
+ predict, pred_batch, label_batch = adjust_predicts_tw(score, label, normal, threshold, tw, pred=pred)
222
+ return calc_point2point(pred_batch, label_batch)
223
+
224
+ def adjust_predicts_tw(score, label, normal, threshold, tw, pred=None):
225
+ """
226
+ Calculate adjusted predict labels using given `score`, `threshold` (or given `pred`) and `label`, where a non-rolling time
227
+ window (i.e. batch)is used as the basis for adjusting the score. As for adjusting score, only intervals after the first
228
+ true positive detection are adjusted, wheras late detections are not rewarded.
229
+
230
+ Args:
231
+ score (np.ndarray): The anomaly score
232
+ label (np.ndarray): The ground-truth label
233
+ normal (float): The value of a normal label (not anomaly)
234
+ threshold (float): The threshold of anomaly score.
235
+ A point is labeled as "anomaly" if its score is higher than the threshold.
236
+ tw (int): the nonrolling interval for adjusting the score
237
+ pred (np.ndarray or None): if not None, adjust `pred` and ignore `score` and `threshold`,
238
+
239
+ Returns:
240
+ predict (np.ndarray): adjusted predict labels
241
+ pred_batch (np.ndarray): downsampled (in batches) adjusted predict labels
242
+ score_batch (np.ndarray): downsampled true labels
243
+ """
244
+ if len(score) != len(label):
245
+ raise ValueError("score and label must have the same length")
246
+ score = np.asarray(score)
247
+ label = np.asarray(label)
248
+ batched_shape = (int(np.ceil(score.shape[0]/tw)), 1)
249
+ label_batch, pred_batch = np.zeros(batched_shape), np.zeros(batched_shape)
250
+ if pred is None:
251
+ predict = score > threshold
252
+ else:
253
+ predict = pred
254
+ actual = label != normal
255
+ detect_state = False # triggered when a True anomaly is detected by model
256
+ anomaly_batch_count = 0
257
+ i, i_tw = 0, 0
258
+ step = tw
259
+ while i < len(score):
260
+ j = min(i+step, len(score)) # end of tw (batch) starting at i
261
+
262
+ # Adjust step size if needed
263
+ if step > 2 and actual[i:j].sum() > 1:
264
+ if np.diff(np.where(actual[i:j])).max() > 1: # if it finds an interruption in the true label continuity
265
+ step = min(int((j-i)/2), 2) # reduce step size
266
+ label_batch, pred_batch = np.append(label_batch, 0), np.append(pred_batch, 0) # increase size
267
+ j = i + step
268
+ else:
269
+ step = tw
270
+ else:
271
+ step = tw
272
+
273
+ # start rolling window scoring
274
+ if actual[i:j].max(): # If label = T
275
+ if not actual[i]: # if first value is normal
276
+ detect_state = False
277
+ s = actual[i:j].argmax() # this is the index of the first occurance
278
+ if detect_state: # if anomaly was previously detected by model
279
+ anomaly_batch_count += 1
280
+ pred_batch[i_tw], label_batch[i_tw], predict[i+s:j] = 1, 1, 1
281
+ elif predict[i:j].max(): # if alert was detected with T
282
+ detect_state = True # turn on detection state
283
+ anomaly_batch_count += 1
284
+ pred_batch[i_tw], label_batch[i_tw], predict[i+s:j] = 1, 1, 1
285
+ else:
286
+ detect_state = False
287
+ label_batch[i_tw] = 1
288
+ else:
289
+ detect_state = False
290
+ if predict[i:j].max(): # if False positive
291
+ pred_batch[i_tw] = 1
292
+ i += step
293
+ i_tw += 1
294
+ return predict, pred_batch, label_batch