-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathtransforms_test.py
610 lines (544 loc) · 20.3 KB
/
transforms_test.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging
import math
import os
import pickle
import shutil
import tempfile
import unittest
from typing import Any
from typing import Dict
from typing import Iterable
from typing import Optional
from typing import Sequence
from typing import SupportsFloat
from typing import Tuple
import mock
import numpy
from sklearn.base import BaseEstimator
import apache_beam as beam
from apache_beam.ml.anomaly.aggregations import AnyVote
from apache_beam.ml.anomaly.base import AnomalyPrediction
from apache_beam.ml.anomaly.base import AnomalyResult
from apache_beam.ml.anomaly.base import EnsembleAnomalyDetector
from apache_beam.ml.anomaly.detectors.offline import OfflineDetector
from apache_beam.ml.anomaly.detectors.zscore import ZScore
from apache_beam.ml.anomaly.specifiable import Spec
from apache_beam.ml.anomaly.specifiable import Specifiable
from apache_beam.ml.anomaly.specifiable import _spec_type_to_subspace
from apache_beam.ml.anomaly.specifiable import specifiable
from apache_beam.ml.anomaly.thresholds import FixedThreshold
from apache_beam.ml.anomaly.thresholds import QuantileThreshold
from apache_beam.ml.anomaly.transforms import AnomalyDetection
from apache_beam.ml.anomaly.transforms import _StatefulThresholdDoFn
from apache_beam.ml.anomaly.transforms import _StatelessThresholdDoFn
from apache_beam.ml.inference.base import KeyedModelHandler
from apache_beam.ml.inference.base import PredictionResult
from apache_beam.ml.inference.base import RunInference
from apache_beam.ml.inference.base import _PostProcessingModelHandler
from apache_beam.ml.inference.base import _PreProcessingModelHandler
from apache_beam.ml.inference.sklearn_inference import SklearnModelHandlerNumpy
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
def _prediction_iterable_is_equal_to(
a: Iterable[AnomalyPrediction], b: Iterable[AnomalyPrediction]):
a_list = list(a)
b_list = list(b)
if len(a_list) != len(b_list):
return False
return any(
map(lambda x: _prediction_is_equal_to(x[0], x[1]), zip(a_list, b_list)))
def _prediction_is_equal_to(a: AnomalyPrediction, b: AnomalyPrediction):
if a.model_id != b.model_id:
return False
if a.threshold != b.threshold:
return False
if a.score != b.score:
if not (a.score is not None and b.score is not None and
math.isnan(a.score) and math.isnan(b.score)):
return False
if a.label != b.label:
return False
if a.info != b.info:
return False
if a.source_predictions is None and b.source_predictions is None:
return True
if a.source_predictions is not None and b.source_predictions is not None:
return _prediction_iterable_is_equal_to(
a.source_predictions, b.source_predictions)
return False
def _keyed_result_is_equal_to(
a: tuple[int, AnomalyResult], b: tuple[int, AnomalyResult]):
if a[0] != b[0]:
return False
if a[1].example != b[1].example:
return False
return _prediction_iterable_is_equal_to(a[1].predictions, b[1].predictions)
class TestAnomalyDetection(unittest.TestCase):
def setUp(self):
self._input = [
(1, beam.Row(x1=1, x2=4)),
(2, beam.Row(x1=100, x2=5)), # an row with a different key (key=2)
(1, beam.Row(x1=2, x2=4)),
(1, beam.Row(x1=3, x2=5)),
(1, beam.Row(x1=10, x2=4)), # outlier in key=1, with respect to x1
(1, beam.Row(x1=2, x2=10)), # outlier in key=1, with respect to x2
(1, beam.Row(x1=3, x2=4)),
]
def test_one_detector(self):
zscore_x1_expected = [
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=2.1213203435596424,
label=0,
threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=8.0, label=1, threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=0.4898979485566356,
label=0,
threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=0.16452254913212455,
label=0,
threshold=3),
]
detector = ZScore(features=["x1"], model_id="zscore_x1")
with TestPipeline() as p:
result = (
p | beam.Create(self._input)
# TODO: get rid of this conversion between BeamSchema to beam.Row.
| beam.Map(lambda t: (t[0], beam.Row(**t[1]._asdict())))
| AnomalyDetection(detector))
assert_that(
result,
equal_to([(
input[0], AnomalyResult(example=input[1], predictions=[decision]))
for input,
decision in zip(self._input, zscore_x1_expected)],
_keyed_result_is_equal_to))
def test_multiple_detectors_without_aggregation(self):
zscore_x1_expected = [
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=float('NaN'), label=-2, threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=2.1213203435596424,
label=0,
threshold=3),
AnomalyPrediction(
model_id='zscore_x1', score=8.0, label=1, threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=0.4898979485566356,
label=0,
threshold=3),
AnomalyPrediction(
model_id='zscore_x1',
score=0.16452254913212455,
label=0,
threshold=3),
]
zscore_x2_expected = [
AnomalyPrediction(
model_id='zscore_x2', score=float('NaN'), label=-2, threshold=2),
AnomalyPrediction(
model_id='zscore_x2', score=float('NaN'), label=-2, threshold=2),
AnomalyPrediction(
model_id='zscore_x2', score=float('NaN'), label=-2, threshold=2),
AnomalyPrediction(model_id='zscore_x2', score=0, label=0, threshold=2),
AnomalyPrediction(
model_id='zscore_x2',
score=0.5773502691896252,
label=0,
threshold=2),
AnomalyPrediction(
model_id='zscore_x2', score=11.5, label=1, threshold=2),
AnomalyPrediction(
model_id='zscore_x2',
score=0.5368754921931594,
label=0,
threshold=2),
]
sub_detectors = []
sub_detectors.append(ZScore(features=["x1"], model_id="zscore_x1"))
sub_detectors.append(
ZScore(
features=["x2"],
threshold_criterion=FixedThreshold(2),
model_id="zscore_x2"))
with beam.Pipeline() as p:
result = (
p | beam.Create(self._input)
# TODO: get rid of this conversion between BeamSchema to beam.Row.
| beam.Map(lambda t: (t[0], beam.Row(**t[1]._asdict())))
| AnomalyDetection(EnsembleAnomalyDetector(sub_detectors)))
assert_that(
result,
equal_to([(
input[0],
AnomalyResult(
example=input[1], predictions=[decision1, decision2]))
for input,
decision1,
decision2 in zip(
self._input, zscore_x1_expected, zscore_x2_expected)],
_keyed_result_is_equal_to))
def test_multiple_sub_detectors_with_aggregation(self):
aggregated = [
AnomalyPrediction(model_id="custom", label=-2),
AnomalyPrediction(model_id="custom", label=-2),
AnomalyPrediction(model_id="custom", label=-2),
AnomalyPrediction(model_id="custom", label=0),
AnomalyPrediction(model_id="custom", label=1),
AnomalyPrediction(model_id="custom", label=1),
AnomalyPrediction(model_id="custom", label=0),
]
sub_detectors = []
sub_detectors.append(ZScore(features=["x1"], model_id="zscore_x1"))
sub_detectors.append(
ZScore(
features=["x2"],
threshold_criterion=FixedThreshold(2),
model_id="zscore_x2"))
with beam.Pipeline() as p:
result = (
p | beam.Create(self._input)
# TODO: get rid of this conversion between BeamSchema to beam.Row.
| beam.Map(lambda t: (t[0], beam.Row(**t[1]._asdict())))
| AnomalyDetection(
EnsembleAnomalyDetector(
sub_detectors, aggregation_strategy=AnyVote())))
assert_that(
result,
equal_to([(
input[0],
AnomalyResult(example=input[1], predictions=[prediction]))
for input,
prediction in zip(self._input, aggregated)]))
class FakeNumpyModel():
def __init__(self):
self.total_predict_calls = 0
def predict(self, input_vector: numpy.ndarray):
self.total_predict_calls += 1
return [input_vector[0][0] * 10 - input_vector[0][1]]
def alternate_numpy_inference_fn(
model: BaseEstimator,
batch: Sequence[numpy.ndarray],
inference_args: Optional[Dict[str, Any]] = None) -> Any:
return [0]
def _to_keyed_numpy_array(t: Tuple[Any, beam.Row]):
"""Converts an Apache Beam Row to a NumPy array."""
return t[0], numpy.array(list(t[1]))
def _from_keyed_numpy_array(t: Tuple[Any, PredictionResult]):
assert isinstance(t[1].inference, SupportsFloat)
return t[0], float(t[1].inference)
class TestOfflineDetector(unittest.TestCase):
def setUp(self):
global SklearnModelHandlerNumpy, KeyedModelHandler
global _PreProcessingModelHandler, _PostProcessingModelHandler
# Make model handlers into Specifiable
SklearnModelHandlerNumpy = specifiable(SklearnModelHandlerNumpy)
KeyedModelHandler = specifiable(KeyedModelHandler)
_PreProcessingModelHandler = specifiable(_PreProcessingModelHandler)
_PostProcessingModelHandler = specifiable(_PostProcessingModelHandler)
self.tmpdir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.tmpdir)
# Make the model handlers back to normal
SklearnModelHandlerNumpy.unspecifiable()
KeyedModelHandler.unspecifiable()
_PreProcessingModelHandler.unspecifiable()
_PostProcessingModelHandler.unspecifiable()
def test_default_inference_fn(self):
temp_file_name = self.tmpdir + os.sep + 'pickled_file'
with open(temp_file_name, 'wb') as file:
pickle.dump(FakeNumpyModel(), file)
keyed_model_handler = KeyedModelHandler(
SklearnModelHandlerNumpy(model_uri=temp_file_name)).with_preprocess_fn(
_to_keyed_numpy_array).with_postprocess_fn(_from_keyed_numpy_array)
detector = OfflineDetector(keyed_model_handler=keyed_model_handler)
detector_spec = detector.to_spec()
expected_spec = Spec(
type='OfflineDetector',
config={
'keyed_model_handler': Spec(
type='_PostProcessingModelHandler',
config={
'base': Spec(
type='_PreProcessingModelHandler',
config={
'base': Spec(
type='KeyedModelHandler',
config={
'unkeyed': Spec(
type='SklearnModelHandlerNumpy',
config={'model_uri': temp_file_name})
}),
'preprocess_fn': Spec(
type='_to_keyed_numpy_array', config=None)
}),
'postprocess_fn': Spec(
type='_from_keyed_numpy_array', config=None)
})
})
self.assertEqual(detector_spec, expected_spec)
self.assertEqual(_spec_type_to_subspace('SklearnModelHandlerNumpy'), '*')
self.assertEqual(_spec_type_to_subspace('_PreProcessingModelHandler'), '*')
self.assertEqual(_spec_type_to_subspace('_PostProcessingModelHandler'), '*')
self.assertEqual(_spec_type_to_subspace('_to_keyed_numpy_array'), '*')
self.assertEqual(_spec_type_to_subspace('_from_keyed_numpy_array'), '*')
# Make sure the spec from the detector can be used to reconstruct the same
# detector
detector_new = Specifiable.from_spec(detector_spec)
input = [
(1, beam.Row(x=1, y=2)),
(1, beam.Row(x=2, y=4)),
(1, beam.Row(x=3, y=6)),
]
expected_predictions = [
AnomalyPrediction(
model_id='OfflineDetector',
score=8.0,
label=None,
threshold=None,
info='',
source_predictions=None),
AnomalyPrediction(
model_id='OfflineDetector',
score=16.0,
label=None,
threshold=None,
info='',
source_predictions=None),
AnomalyPrediction(
model_id='OfflineDetector',
score=24.0,
label=None,
threshold=None,
info='',
source_predictions=None),
]
with TestPipeline() as p:
result = (
p | beam.Create(input)
# TODO: get rid of this conversion between BeamSchema to beam.Row.
| beam.Map(lambda t: (t[0], beam.Row(**t[1]._asdict())))
| AnomalyDetection(detector_new))
assert_that(
result,
equal_to([(
input[0],
AnomalyResult(example=input[1], predictions=[prediction]))
for input,
prediction in zip(input, expected_predictions)]))
def test_run_inference_args(self):
model_handler = SklearnModelHandlerNumpy(model_uri="unused")
detector = OfflineDetector(
keyed_model_handler=model_handler,
run_inference_args={"inference_args": {
"multiplier": 10
}})
p = TestPipeline()
input = [
(1, beam.Row(x=1, y=2)),
(1, beam.Row(x=2, y=4)),
(1, beam.Row(x=3, y=6)),
]
# patch the RunInference in "apache_beam.ml.anomaly.transforms" where
# it is imported and call
with mock.patch('apache_beam.ml.anomaly.transforms.RunInference') as mock_run_inference: # pylint: disable=line-too-long
# make the actual RunInference as the sideeffect, so we record the call
# information but also create the true RunInference instance.
mock_run_inference.side_effect = RunInference
try:
p = TestPipeline()
_ = (p | beam.Create(input) | AnomalyDetection(detector))
except: # pylint: disable=bare-except
pass
call_args = mock_run_inference.call_args[1]
self.assertEqual(
call_args,
{
'inference_args': {
'multiplier': 10
},
'model_identifier': 'OfflineDetector'
})
R = beam.Row(x=10, y=20)
class TestStatelessThresholdDoFn(unittest.TestCase):
def test_dofn_on_single_prediction(self):
input = [
(1, (2, AnomalyResult(R, [AnomalyPrediction(score=1)]))),
(1, (3, AnomalyResult(R, [AnomalyPrediction(score=2)]))),
(1, (4, AnomalyResult(R, [AnomalyPrediction(score=3)]))),
]
expected = [
(
1,
(
2,
AnomalyResult(
R, [AnomalyPrediction(score=1, label=0, threshold=2)]))),
(
1,
(
3,
AnomalyResult(
R, [AnomalyPrediction(score=2, label=1, threshold=2)]))),
(
1,
(
4,
AnomalyResult(
R, [AnomalyPrediction(score=3, label=1, threshold=2)]))),
]
with TestPipeline() as p:
result = (
p
| beam.Create(input)
| beam.ParDo(
_StatelessThresholdDoFn(
FixedThreshold(2, normal_label=0,
outlier_label=1).to_spec())))
assert_that(result, equal_to(expected))
def test_dofn_on_multiple_predictions(self):
input = [
(
1,
(
2,
AnomalyResult(
R,
[AnomalyPrediction(score=1), AnomalyPrediction(score=4)]))),
(
1,
(
3,
AnomalyResult(
R,
[AnomalyPrediction(score=2), AnomalyPrediction(score=0.5)
]))),
]
expected = [
(
1,
(
2,
AnomalyResult(
R,
[
AnomalyPrediction(score=1, label=0, threshold=2),
AnomalyPrediction(score=4, label=1, threshold=2)
]))),
(
1,
(
3,
AnomalyResult(
R,
[
AnomalyPrediction(score=2, label=1, threshold=2),
AnomalyPrediction(score=0.5, label=0, threshold=2)
]))),
]
with TestPipeline() as p:
result = (
p
| beam.Create(input)
| beam.ParDo(
_StatelessThresholdDoFn(
FixedThreshold(2, normal_label=0,
outlier_label=1).to_spec())))
assert_that(result, equal_to(expected))
class TestStatefulThresholdDoFn(unittest.TestCase):
def test_dofn_on_single_prediction(self):
# use the input data with two keys to test stateful threshold function
input = [
(1, (2, AnomalyResult(R, [AnomalyPrediction(score=1)]))),
(1, (3, AnomalyResult(R, [AnomalyPrediction(score=2)]))),
(1, (4, AnomalyResult(R, [AnomalyPrediction(score=3)]))),
(2, (2, AnomalyResult(R, [AnomalyPrediction(score=10)]))),
(2, (3, AnomalyResult(R, [AnomalyPrediction(score=20)]))),
(2, (4, AnomalyResult(R, [AnomalyPrediction(score=30)]))),
]
expected = [
(
1,
(
2,
AnomalyResult(
R, [AnomalyPrediction(score=1, label=1, threshold=1)]))),
(
1,
(
3,
AnomalyResult(
R, [AnomalyPrediction(score=2, label=1, threshold=1.5)]))),
(
2,
(
2,
AnomalyResult(
R, [AnomalyPrediction(score=10, label=1, threshold=10)]))),
(
2,
(
3,
AnomalyResult(
R, [AnomalyPrediction(score=20, label=1, threshold=15)]))),
(
1,
(
4,
AnomalyResult(
R, [AnomalyPrediction(score=3, label=1, threshold=2)]))),
(
2,
(
4,
AnomalyResult(
R, [AnomalyPrediction(score=30, label=1, threshold=20)]))),
]
with TestPipeline() as p:
result = (
p
| beam.Create(input)
# use median just for test convenience
| beam.ParDo(
_StatefulThresholdDoFn(
QuantileThreshold(
quantile=0.5, normal_label=0,
outlier_label=1).to_spec())))
assert_that(result, equal_to(expected))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.WARNING)
unittest.main()