|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright (c) 2023, 2024 Oracle and/or its affiliates. |
| 4 | +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ |
| 5 | + |
| 6 | +import importlib |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import pandas as pd |
| 10 | +from merlion.post_process.threshold import AggregateAlarms |
| 11 | +from merlion.utils import TimeSeries |
| 12 | + |
| 13 | +from ads.common.decorator.runtime_dependency import runtime_dependency |
| 14 | +from ads.opctl.operator.lowcode.anomaly.const import ( |
| 15 | + MERLIONAD_IMPORT_MODEL_MAP, |
| 16 | + MERLIONAD_MODEL_MAP, |
| 17 | + OutputColumns, |
| 18 | + SupportedModels, |
| 19 | +) |
| 20 | + |
| 21 | +from .anomaly_dataset import AnomalyOutput |
| 22 | +from .base_model import AnomalyOperatorBaseModel |
| 23 | + |
| 24 | + |
| 25 | +class AnomalyMerlionOperatorModel(AnomalyOperatorBaseModel): |
| 26 | + """Class representing Merlion Anomaly Detection operator model.""" |
| 27 | + |
| 28 | + @runtime_dependency( |
| 29 | + module="merlion", |
| 30 | + err_msg=( |
| 31 | + "Please run `pip3 install salesforce-merlion[all]` to " |
| 32 | + "install the required packages." |
| 33 | + ), |
| 34 | + ) |
| 35 | + def _get_config_model(self, model_name): |
| 36 | + """ |
| 37 | + Returns a dictionary with model names as keys and a list of model config and model object as values. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + model_name : str |
| 42 | + model name from the Merlion model list. |
| 43 | +
|
| 44 | + Returns |
| 45 | + ------- |
| 46 | + dict |
| 47 | + A dictionary with model names as keys and a list of model config and model object as values. |
| 48 | + """ |
| 49 | + model_config_map = {} |
| 50 | + model_module = importlib.import_module( |
| 51 | + name=MERLIONAD_IMPORT_MODEL_MAP.get(model_name), |
| 52 | + package="merlion.models.anomaly", |
| 53 | + ) |
| 54 | + model_config = getattr( |
| 55 | + model_module, MERLIONAD_MODEL_MAP.get(model_name) + "Config" |
| 56 | + ) |
| 57 | + model = getattr(model_module, MERLIONAD_MODEL_MAP.get(model_name)) |
| 58 | + model_config_map[model_name] = [model_config, model] |
| 59 | + return model_config_map |
| 60 | + |
| 61 | + def _build_model(self) -> AnomalyOutput: |
| 62 | + """ |
| 63 | + Builds a Merlion anomaly detection model and trains it using the given data. |
| 64 | +
|
| 65 | + Parameters |
| 66 | + ---------- |
| 67 | + None |
| 68 | +
|
| 69 | + Returns |
| 70 | + ------- |
| 71 | + AnomalyOutput |
| 72 | + An AnomalyOutput object containing the anomaly detection results. |
| 73 | + """ |
| 74 | + model_kwargs = self.spec.model_kwargs |
| 75 | + anomaly_output = AnomalyOutput(date_column="index") |
| 76 | + anomaly_threshold = model_kwargs.get("anomaly_threshold", 95) |
| 77 | + model_config_map = {} |
| 78 | + model_config_map = self._get_config_model(self.spec.model) |
| 79 | + |
| 80 | + date_column = self.spec.datetime_column.name |
| 81 | + |
| 82 | + anomaly_output = AnomalyOutput(date_column=date_column) |
| 83 | + # model_objects = defaultdict(list) |
| 84 | + for target, df in self.datasets.full_data_dict.items(): |
| 85 | + data = df.set_index(date_column) |
| 86 | + data = TimeSeries.from_pd(data) |
| 87 | + for model_name, (model_config, model) in model_config_map.items(): |
| 88 | + if self.spec.model == SupportedModels.BOCPD: |
| 89 | + model_config = model_config(**self.spec.model_kwargs) |
| 90 | + else: |
| 91 | + model_config = model_config( |
| 92 | + **{ |
| 93 | + **self.spec.model_kwargs, |
| 94 | + "threshold": AggregateAlarms( |
| 95 | + alm_threshold=model_kwargs.get("alm_threshold") |
| 96 | + if model_kwargs.get("alm_threshold") |
| 97 | + else None |
| 98 | + ), |
| 99 | + } |
| 100 | + ) |
| 101 | + if hasattr(model_config, "target_seq_index"): |
| 102 | + model_config.target_seq_index = df.columns.get_loc( |
| 103 | + self.spec.target_column |
| 104 | + ) |
| 105 | + model = model(model_config) |
| 106 | + |
| 107 | + scores = model.train(train_data=data, anomaly_labels=None) |
| 108 | + scores = scores.to_pd().reset_index() |
| 109 | + scores["anom_score"] = ( |
| 110 | + scores["anom_score"] - scores["anom_score"].min() |
| 111 | + ) / (scores["anom_score"].max() - scores["anom_score"].min()) |
| 112 | + |
| 113 | + try: |
| 114 | + y_pred = model.get_anomaly_label(data) |
| 115 | + y_pred = (y_pred.to_pd().reset_index()["anom_score"] > 0).astype( |
| 116 | + int |
| 117 | + ) |
| 118 | + except Exception as e: |
| 119 | + y_pred = ( |
| 120 | + scores["anom_score"] |
| 121 | + > np.percentile( |
| 122 | + scores["anom_score"], |
| 123 | + anomaly_threshold, |
| 124 | + ) |
| 125 | + ).astype(int) |
| 126 | + |
| 127 | + index_col = df.columns[0] |
| 128 | + |
| 129 | + anomaly = pd.DataFrame( |
| 130 | + {index_col: df[index_col], OutputColumns.ANOMALY_COL: y_pred} |
| 131 | + ).reset_index(drop=True) |
| 132 | + score = pd.DataFrame( |
| 133 | + { |
| 134 | + index_col: df[index_col], |
| 135 | + OutputColumns.SCORE_COL: scores["anom_score"], |
| 136 | + } |
| 137 | + ).reset_index(drop=True) |
| 138 | + # model_objects[model_name].append(model) |
| 139 | + |
| 140 | + anomaly_output.add_output(target, anomaly, score) |
| 141 | + return anomaly_output |
| 142 | + |
| 143 | + def _generate_report(self): |
| 144 | + """Genreates a report for the model.""" |
| 145 | + import report_creator as rc |
| 146 | + |
| 147 | + other_sections = [ |
| 148 | + rc.Heading("Selected Models Overview", level=2), |
| 149 | + rc.Text( |
| 150 | + "The following tables provide information regarding the chosen model." |
| 151 | + ), |
| 152 | + ] |
| 153 | + |
| 154 | + model_description = rc.Text( |
| 155 | + "The Merlion anomaly detection model is a full-stack automated machine learning system for anomaly detection." |
| 156 | + ) |
| 157 | + |
| 158 | + return ( |
| 159 | + model_description, |
| 160 | + other_sections, |
| 161 | + ) |
0 commit comments