|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | +# contributor license agreements. See the NOTICE file distributed with |
| 4 | +# this work for additional information regarding copyright ownership. |
| 5 | +# The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | +# (the "License"); you may not use this file except in compliance with |
| 7 | +# the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# |
| 17 | + |
| 18 | +import math |
| 19 | +from typing import Optional |
| 20 | + |
| 21 | +import apache_beam as beam |
| 22 | +from apache_beam.ml.anomaly.base import AnomalyDetector |
| 23 | +from apache_beam.ml.anomaly.specifiable import specifiable |
| 24 | +from apache_beam.ml.anomaly.thresholds import FixedThreshold |
| 25 | +from apache_beam.ml.anomaly.univariate.base import EPSILON |
| 26 | +from apache_beam.ml.anomaly.univariate.quantile import BufferedSlidingQuantileTracker # pylint: disable=line-too-long |
| 27 | +from apache_beam.ml.anomaly.univariate.quantile import QuantileTracker |
| 28 | +from apache_beam.ml.anomaly.univariate.quantile import SecondaryBufferedQuantileTracker # pylint: disable=line-too-long |
| 29 | + |
| 30 | +DEFAULT_WINDOW_SIZE = 1000 |
| 31 | + |
| 32 | + |
| 33 | +@specifiable |
| 34 | +class IQR(AnomalyDetector): |
| 35 | + """Interquartile Range (IQR) anomaly detector. |
| 36 | +
|
| 37 | + This class implements an anomaly detection algorithm based on the |
| 38 | + Interquartile Range (IQR) [#]_ . It calculates the IQR using quantile trackers |
| 39 | + for Q1 (25th percentile) and Q3 (75th percentile) and scores data points based |
| 40 | + on their deviation from these quartiles. |
| 41 | +
|
| 42 | + The score is calculated as follows: |
| 43 | +
|
| 44 | + * If a data point is above Q3, the score is (value - Q3) / IQR. |
| 45 | + * If a data point is below Q1, the score is (Q1 - value) / IQR. |
| 46 | + * If a data point is within the IQR (Q1 <= value <= Q3), the score is 0. |
| 47 | + Initializes the IQR anomaly detector. |
| 48 | +
|
| 49 | + Args: |
| 50 | + q1_tracker: Optional QuantileTracker for Q1 (25th percentile). If None, a |
| 51 | + BufferedSlidingQuantileTracker with a default window size is used. |
| 52 | + q3_tracker: Optional QuantileTracker for Q3 (75th percentile). If None, a |
| 53 | + SecondaryBufferedQuantileTracker based on q1_tracker is used. |
| 54 | + threshold_criterion: Optional ThresholdFn to apply on the score. Defaults |
| 55 | + to `FixedThreshold(1.5)` since outliers are commonly defined as data |
| 56 | + points that fall below Q1 - 1.5 IQR or above Q3 + 1.5 IQR. |
| 57 | + **kwargs: Additional keyword arguments. |
| 58 | +
|
| 59 | + .. [#] https://en.wikipedia.org/wiki/Interquartile_range |
| 60 | + """ |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + q1_tracker: Optional[QuantileTracker] = None, |
| 64 | + q3_tracker: Optional[QuantileTracker] = None, |
| 65 | + **kwargs): |
| 66 | + if "threshold_criterion" not in kwargs: |
| 67 | + kwargs["threshold_criterion"] = FixedThreshold(1.5) |
| 68 | + super().__init__(**kwargs) |
| 69 | + |
| 70 | + self._q1_tracker = q1_tracker or \ |
| 71 | + BufferedSlidingQuantileTracker(DEFAULT_WINDOW_SIZE, 0.25) |
| 72 | + assert self._q1_tracker._q == 0.25, \ |
| 73 | + "q1_tracker must be initialized with q = 0.25" |
| 74 | + |
| 75 | + self._q3_tracker = q3_tracker or \ |
| 76 | + SecondaryBufferedQuantileTracker(self._q1_tracker, 0.75) |
| 77 | + assert self._q3_tracker._q == 0.75, \ |
| 78 | + "q3_tracker must be initialized with q = 0.75" |
| 79 | + |
| 80 | + def learn_one(self, x: beam.Row) -> None: |
| 81 | + """Updates the quantile trackers with a new data point. |
| 82 | +
|
| 83 | + Args: |
| 84 | + x: A `beam.Row` containing a single numerical value. |
| 85 | + """ |
| 86 | + if len(x.__dict__) != 1: |
| 87 | + raise ValueError( |
| 88 | + "IQR.learn_one expected univariate input, but got %s", str(x)) |
| 89 | + |
| 90 | + v = next(iter(x)) |
| 91 | + self._q1_tracker.push(v) |
| 92 | + self._q3_tracker.push(v) |
| 93 | + |
| 94 | + def score_one(self, x: beam.Row) -> Optional[float]: |
| 95 | + """Scores a data point based on its deviation from the IQR. |
| 96 | +
|
| 97 | + Args: |
| 98 | + x: A `beam.Row` containing a single numerical value. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + float | None: The anomaly score. |
| 102 | + """ |
| 103 | + if len(x.__dict__) != 1: |
| 104 | + raise ValueError( |
| 105 | + "IQR.score_one expected univariate input, but got %s", str(x)) |
| 106 | + |
| 107 | + v = next(iter(x)) |
| 108 | + if v is None or math.isnan(v): |
| 109 | + return None |
| 110 | + |
| 111 | + q1 = self._q1_tracker.get() |
| 112 | + q3 = self._q3_tracker.get() |
| 113 | + |
| 114 | + # not enough data points to compute median or median absolute deviation |
| 115 | + if math.isnan(q1) or math.isnan(q3): |
| 116 | + return float('NaN') |
| 117 | + |
| 118 | + iqr = q3 - q1 |
| 119 | + if abs(iqr) < EPSILON: |
| 120 | + return 0.0 |
| 121 | + |
| 122 | + if v > q3: |
| 123 | + return (v - q3) / iqr |
| 124 | + |
| 125 | + if v < q1: |
| 126 | + return (q1 - v) / iqr |
| 127 | + |
| 128 | + # q1 <= v <= q3, normal points |
| 129 | + return 0 |
0 commit comments