-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodel.py
More file actions
100 lines (78 loc) · 2.2 KB
/
Copy pathmodel.py
File metadata and controls
100 lines (78 loc) · 2.2 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
import numpy as np
import json
import os
# -------------------------------
# Load baseline from file
# -------------------------------
BASELINE_PATH = os.path.join(os.path.dirname(__file__), "baseline.json")
with open(BASELINE_PATH, "r") as f:
data = json.load(f)
baseline = data["mean"]
std_dev = data["std"]
# -------------------------------
# Features used
# -------------------------------
FEATURES = [
"mean_pps",
"mean_bps",
"total_packets",
"total_bytes",
"var_pps"
]
# -------------------------------
# Compute Risk (Z-score based)
# -------------------------------
def compute_risk(window):
z_scores = {}
for f in FEATURES:
value = window.get(f, 0)
mean = baseline[f]
std = max(std_dev[f], 1) # prevent division by zero
z = abs((value - mean) / std)
if z > 2:
z *= 2
if z > 5:
z *= 2
z_scores[f] = z
# Average deviation
anomaly_score = np.mean(list(z_scores.values()))
# Scale to 0-100
risk = min(100, anomaly_score * 10)
return risk, z_scores
# -------------------------------
# Status Classification
# -------------------------------
def get_status(risk):
if risk > 70:
return "High Risk"
elif risk > 40:
return "Suspicious"
else:
return "Normal"
# -------------------------------
# Explanation Generator
# -------------------------------
def generate_explanation(z_scores, window):
sorted_features = sorted(z_scores.items(), key=lambda x: x[1], reverse=True)
explanations = []
for f, z in sorted_features[:2]:
base = baseline[f] + 1e-6
val = window[f]
factor = val / base
if factor > 1:
explanations.append(f"{f} increased {factor:.2f}x")
else:
explanations.append(f"{f} decreased to {factor:.2f}x")
return explanations
# -------------------------------
# Main Predict Function
# -------------------------------
def predict(window):
risk, z_scores = compute_risk(window)
status = get_status(risk)
explanation = generate_explanation(z_scores, window)
return {
"risk": round(risk, 2),
"status": status,
"explanation": explanation
}