Spaces:
Sleeping
Sleeping
Update model/anomaly_detector.py
Browse files- model/anomaly_detector.py +22 -23
model/anomaly_detector.py
CHANGED
|
@@ -2,39 +2,38 @@ import numpy as np
|
|
| 2 |
from sklearn.ensemble import IsolationForest
|
| 3 |
from utils.preprocessing import extract_features
|
| 4 |
|
| 5 |
-
# Dummy
|
| 6 |
-
|
| 7 |
-
example_training_data = np.array([
|
| 8 |
[5, 0, 30, 0.1],
|
| 9 |
[10, 1, 50, 0.2],
|
| 10 |
[2, 2, 10, 0.3],
|
| 11 |
[8, 0, 45, 0.05],
|
| 12 |
[3, 1, 12, 0.4]
|
| 13 |
])
|
| 14 |
-
model.
|
|
|
|
| 15 |
|
| 16 |
-
def
|
| 17 |
features = extract_features(agent_data)
|
| 18 |
-
prediction = model.predict([features])[0] # -1
|
| 19 |
flagged = prediction == -1
|
| 20 |
|
| 21 |
-
# Override logic: manually flagging on rules
|
| 22 |
reasons = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
if reasons:
|
| 32 |
-
flagged = True
|
| 33 |
|
| 34 |
-
return
|
| 35 |
-
"agent_id": str(agent_data.get("agent_id", "unknown")),
|
| 36 |
-
"weekly_calls": int(agent_data["weekly_calls"]),
|
| 37 |
-
"missed_visits": int(agent_data["missed_visits"]),
|
| 38 |
-
"flagged": bool(flagged),
|
| 39 |
-
"reason": ", ".join(reasons) if flagged else "Normal behavior"
|
| 40 |
-
}
|
|
|
|
| 2 |
from sklearn.ensemble import IsolationForest
|
| 3 |
from utils.preprocessing import extract_features
|
| 4 |
|
| 5 |
+
# Dummy training data (should be replaced with real labeled data)
|
| 6 |
+
train_data = np.array([
|
|
|
|
| 7 |
[5, 0, 30, 0.1],
|
| 8 |
[10, 1, 50, 0.2],
|
| 9 |
[2, 2, 10, 0.3],
|
| 10 |
[8, 0, 45, 0.05],
|
| 11 |
[3, 1, 12, 0.4]
|
| 12 |
])
|
| 13 |
+
model = IsolationForest(contamination=0.2, random_state=42)
|
| 14 |
+
model.fit(train_data)
|
| 15 |
|
| 16 |
+
def detect_anomaly_plain_text(agent_data):
|
| 17 |
features = extract_features(agent_data)
|
| 18 |
+
prediction = model.predict([features])[0] # -1 is anomaly
|
| 19 |
flagged = prediction == -1
|
| 20 |
|
|
|
|
| 21 |
reasons = []
|
| 22 |
+
if flagged:
|
| 23 |
+
if agent_data["missed_visits"] >= 5:
|
| 24 |
+
reasons.append("a spike in missed visits")
|
| 25 |
+
if agent_data["weekly_calls"] <= 3:
|
| 26 |
+
reasons.append("low call frequency")
|
| 27 |
+
if agent_data["lead_drop_rate"] > 0.6:
|
| 28 |
+
reasons.append("a high lead drop rate")
|
| 29 |
+
if agent_data["travel_distance"] < 10:
|
| 30 |
+
reasons.append("unusual travel distance")
|
| 31 |
|
| 32 |
+
reason_text = (
|
| 33 |
+
f"Agent {agent_data['agent_id']} has been flagged for anomalous behavior due to "
|
| 34 |
+
+ ", ".join(reasons) + "."
|
| 35 |
+
if flagged else
|
| 36 |
+
f"Agent {agent_data['agent_id']} shows normal behavior based on current data."
|
| 37 |
+
)
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
return reason_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|