dschandra commited on
Commit
b5e6606
·
verified ·
1 Parent(s): 12162f6

Update model/anomaly_detector.py

Browse files
Files changed (1) hide show
  1. model/anomaly_detector.py +25 -27
model/anomaly_detector.py CHANGED
@@ -2,41 +2,39 @@ import numpy as np
2
  from sklearn.ensemble import IsolationForest
3
  from utils.preprocessing import extract_features
4
 
5
- # A placeholder Isolation Forest model
6
- # In production, load a pre-trained model using joblib or pickle
7
  model = IsolationForest(contamination=0.2, random_state=42)
8
-
9
- # Example training data (you should replace with real preprocessed dataset)
10
  example_training_data = np.array([
11
- [5, 0, 30, 0],
12
- [10, 1, 50, 1],
13
- [2, 4, 10, 3],
14
- [8, 0, 45, 0],
15
- [3, 5, 12, 2]
16
  ])
17
  model.fit(example_training_data)
18
 
19
  def detect_anomaly(agent_data):
20
  features = extract_features(agent_data)
21
- prediction = model.predict([features])[0] # -1 for anomaly
22
  flagged = prediction == -1
23
 
24
- reason = ""
25
- if flagged:
26
- if agent_data["missed_visits"] >= 5:
27
- reason = "Missed appointments spike"
28
- elif agent_data["weekly_calls"] < 4:
29
- reason = "Low call frequency"
30
- elif agent_data["lead_drop_rate"] > 0.6:
31
- reason = "High lead drop rate"
32
- else:
33
- reason = "Unusual activity pattern"
34
 
35
- return {
36
- "agent_id": str(agent_data.get("agent_id", "unknown")),
37
- "weekly_calls": int(agent_data["weekly_calls"]),
38
- "missed_visits": int(agent_data["missed_visits"]),
39
- "flagged": bool(flagged),
40
- "reason": str(reason if flagged else "Normal behavior")
41
- }
42
 
 
 
 
 
 
 
 
 
 
 
 
2
  from sklearn.ensemble import IsolationForest
3
  from utils.preprocessing import extract_features
4
 
5
+ # Dummy model with placeholder training
 
6
  model = IsolationForest(contamination=0.2, random_state=42)
 
 
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.fit(example_training_data)
15
 
16
  def detect_anomaly(agent_data):
17
  features = extract_features(agent_data)
18
+ prediction = model.predict([features])[0] # -1 = anomaly
19
  flagged = prediction == -1
20
 
21
+ # Override logic: manually flagging on rules
22
+ reasons = []
 
 
 
 
 
 
 
 
23
 
24
+ if agent_data["missed_visits"] >= 5:
25
+ reasons.append("Missed appointments spike")
26
+ if agent_data["weekly_calls"] < 3:
27
+ reasons.append("Low call frequency")
28
+ if agent_data["lead_drop_rate"] > 0.6:
29
+ reasons.append("High lead drop rate")
 
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
+ }