Spaces:
Sleeping
Sleeping
File size: 2,065 Bytes
c9875bd | 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 | """
Base classes for anomaly detectors
"""
from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional
from collections import defaultdict
from telecom_anomaly.core.models import AnomalyResult, TelecomConfig
class BaseDetector(ABC):
"""Base class for all anomaly detectors"""
def __init__(self, config: TelecomConfig):
self.config = config
self.name = self.__class__.__name__
@abstractmethod
def detect(self, data: List[Dict], **kwargs) -> List[AnomalyResult]:
"""Detect anomalies in the data"""
pass
def _create_anomaly(self,
row_index: int,
column_name: str,
value: Any,
method: str,
score: float,
threshold: float,
confidence: float,
msisdn: str = "",
metadata: Optional[Dict] = None) -> AnomalyResult:
"""Helper method to create an anomaly result"""
return AnomalyResult(
row_index=row_index,
column_name=column_name,
value=value,
detection_method=method,
score=score,
threshold=threshold,
confidence=confidence,
msisdn=msisdn,
metadata=metadata or {}
)
class SubscriberBasedDetector(BaseDetector):
"""Base class for detectors that operate on subscriber data"""
def __init__(self, config: TelecomConfig):
super().__init__(config)
self.subscriber_data: Dict[str, List[Dict]] = defaultdict(list)
def prepare_data(self, data: List[Dict]):
"""Prepare data by grouping by subscriber"""
self.subscriber_data.clear()
for row in data:
msisdn = row.get('msisdn')
if msisdn:
self.subscriber_data[msisdn].append(row)
@abstractmethod
def detect(self, data: List[Dict], **kwargs) -> List[AnomalyResult]:
pass |