-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetector.py
More file actions
128 lines (102 loc) · 3.66 KB
/
detector.py
File metadata and controls
128 lines (102 loc) · 3.66 KB
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
import numpy as np
import json
import nanoid
from typing import List
from aiokafka import AIOKafkaConsumer, AIOKafkaProducer
from config.settings import Settings
from warnings import filterwarnings
filterwarnings("ignore")
class Detector():
def __init__(
self,
model,
scaler,
history_size: int,
threshold: int,
time_threshold: int,
mean: np.ndarray,
std: np.ndarray,
used_features: List[int],
settings: Settings,
consumer: AIOKafkaConsumer,
producer: AIOKafkaProducer
):
self.id = nanoid.generate(size=6)
self.model = model
self.scaler = scaler
self.mean = mean
self.std = std
self.used_features = used_features
self.history_size = history_size
self.threshold = threshold
self.time_threshold = time_threshold
self.consumer = consumer
self.producer = producer
self.data = []
self.prediction = None
self.timestamps = []
self.consecutive_counter = 0
self.observer = None
self.DETECTION_DATA_TOPIC = settings.KAFKA_DETECTION_TOPIC
def get_id(self):
return self.id
def get_model_id(self):
return self.model_id
def insert_data(self, new_data):
received_values = json.loads(new_data.decode('utf-8'))
filtered_values = [received_values[i] for i in self.used_features]
if (len(self.data) >= self.history_size):
self.data = self.data[1:]
self.data.append(filtered_values)
self.current_timestamp = received_values["timestamp"]
def scale_data(self, data):
return self.scaler.transform(data)
def process_data(self, data):
numpy_arr = np.array(data).astype(float)
return numpy_arr
def predict_future(self, data):
prediction = self.model.predict(np.expand_dims(data, axis=0), verbose=0).squeeze()
return prediction
def process_z_score(self, z_score):
prediction = "Normal"
column_max = np.argmax(z_score)
z_score_max = np.nanmax(z_score)
if z_score_max > self.threshold:
self.consecutive_counter += 1
prediction = "Anomaly"
else:
self.consecutive_counter = 0
if self.consecutive_counter > self.time_threshold:
prediction = "Attack"
ts_score = {
"timestamp": self.current_timestamp,
"z_score": float(z_score_max),
"column": int(column_max),
"prediction": prediction
}
return {
"detector_id": self.id,
"threshold": self.threshold,
"ts_score": ts_score
}
async def consume(self):
await self.producer.start()
await self.consumer.start()
try:
async for msg in self.consumer:
self.insert_data(msg.value)
if (len(self.data) >= self.history_size):
feature_data = self.process_data(self.data)
scaled_data = self.scale_data(feature_data)
if self.prediction is not None:
error = np.abs(self.prediction - scaled_data[-1])
z_score_all = np.abs(error-self.mean)/self.std
data = self.process_z_score(z_score_all)
await self.producer.send(self.DETECTION_DATA_TOPIC, data)
self.prediction = self.predict_future(scaled_data)
except Exception as e:
print(e)
raise e
finally:
await self.consumer.stop()
await self.producer.stop()