|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import Any, Dict, List |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import pandas as pd |
| 7 | +from sklearn.linear_model import LogisticRegression |
| 8 | +from sklearn.pipeline import Pipeline |
| 9 | +from sklearn.preprocessing import StandardScaler |
| 10 | + |
| 11 | +FEATURE_COLUMNS = [ |
| 12 | + "event_count", |
| 13 | + "unique_event_types", |
| 14 | + "total_duration", |
| 15 | + "avg_confidence", |
| 16 | + "high_risk_actions", |
| 17 | +] |
| 18 | + |
| 19 | + |
| 20 | +class RiskModel: |
| 21 | + version = "0.1.0" |
| 22 | + |
| 23 | + def __init__(self) -> None: |
| 24 | + self.pipeline = Pipeline( |
| 25 | + [ |
| 26 | + ("scaler", StandardScaler()), |
| 27 | + ("clf", LogisticRegression(random_state=42, max_iter=500)), |
| 28 | + ] |
| 29 | + ) |
| 30 | + X_train, y_train = self._generate_training_data() |
| 31 | + self.pipeline.fit(X_train, y_train) |
| 32 | + |
| 33 | + def predict(self, df: pd.DataFrame) -> Dict[str, Any]: |
| 34 | + vector = self._extract_feature_vector(df) |
| 35 | + score = float(self.pipeline.predict_proba([vector])[0, 1]) |
| 36 | + return { |
| 37 | + "user_id": df.attrs.get("user_id", "unknown"), |
| 38 | + "session_id": df.attrs.get("session_id"), |
| 39 | + "risk_score": score, |
| 40 | + "risk_level": self._to_risk_level(score), |
| 41 | + "model_version": self.version, |
| 42 | + "explanation": self._explain(vector, score), |
| 43 | + } |
| 44 | + |
| 45 | + def _generate_training_data(self) -> tuple[np.ndarray, np.ndarray]: |
| 46 | + rng = np.random.default_rng(42) |
| 47 | + rows: List[List[float]] = [] |
| 48 | + labels: List[int] = [] |
| 49 | + |
| 50 | + for _ in range(500): |
| 51 | + event_count = float(rng.integers(1, 24)) |
| 52 | + unique_event_types = float(rng.integers(1, min(5, int(event_count)))) |
| 53 | + total_duration = float(rng.integers(0, 1200)) |
| 54 | + avg_confidence = float(rng.uniform(0.2, 0.98)) |
| 55 | + high_risk_actions = float(rng.integers(0, 5)) |
| 56 | + |
| 57 | + risk = 1 if (event_count > 10 and high_risk_actions >= 2) or total_duration > 600 else 0 |
| 58 | + rows.append([event_count, unique_event_types, total_duration, avg_confidence, high_risk_actions]) |
| 59 | + labels.append(risk) |
| 60 | + |
| 61 | + return np.array(rows), np.array(labels) |
| 62 | + |
| 63 | + def _extract_feature_vector(self, df: pd.DataFrame) -> List[float]: |
| 64 | + event_count = float(len(df)) |
| 65 | + unique_event_types = float(df["event_type"].nunique()) if not df.empty else 0.0 |
| 66 | + |
| 67 | + total_duration = 0.0 |
| 68 | + confidences: List[float] = [] |
| 69 | + high_risk_actions = 0.0 |
| 70 | + |
| 71 | + for metadata in df["metadata"]: |
| 72 | + if isinstance(metadata, dict): |
| 73 | + total_duration += float(metadata.get("duration", 0.0) or 0.0) |
| 74 | + confidence = metadata.get("confidence") |
| 75 | + if isinstance(confidence, (int, float)): |
| 76 | + confidences.append(float(confidence)) |
| 77 | + if metadata.get("high_risk_action"): |
| 78 | + high_risk_actions += 1.0 |
| 79 | + |
| 80 | + avg_confidence = float(np.mean(confidences)) if confidences else 0.0 |
| 81 | + return [event_count, unique_event_types, total_duration, avg_confidence, high_risk_actions] |
| 82 | + |
| 83 | + def _to_risk_level(self, score: float) -> str: |
| 84 | + if score >= 0.65: |
| 85 | + return "high" |
| 86 | + if score >= 0.35: |
| 87 | + return "medium" |
| 88 | + return "low" |
| 89 | + |
| 90 | + def _explain(self, vector: List[float], score: float) -> Dict[str, Any]: |
| 91 | + return { |
| 92 | + "features": dict(zip(FEATURE_COLUMNS, vector)), |
| 93 | + "thresholds": {"low": 0.35, "high": 0.65}, |
| 94 | + "prediction_probability": score, |
| 95 | + } |
0 commit comments