spawn_access_control/
ml_analyzer.rs

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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use smartcore::linalg::basic::matrix::DenseMatrix;
use smartcore::ensemble::random_forest_classifier::RandomForestClassifier;
use smartcore::model_selection::train_test_split;
use crate::behavioral::AccessEvent;
use chrono::{DateTime, Utc, Timelike, Datelike};
use serde::Serialize;
use crate::ml_metrics::{ModelMetrics, ConfusionMatrix};
use std::time::Instant;
use std::collections::HashMap;

#[derive(Debug, Serialize)]
pub struct MLPrediction {
    pub is_anomaly: bool,
    pub confidence: f64,
    pub features: Vec<String>,
    pub timestamp: DateTime<Utc>,
}

pub struct MLAnalyzer {
    model: Option<RandomForestClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>>,
    feature_names: Vec<String>,
}

impl MLAnalyzer {
    pub fn new() -> Self {
        Self {
            model: None,
            feature_names: vec![
                "hour_of_day".to_string(),
                "day_of_week".to_string(),
                "duration_seconds".to_string(),
                "resource_frequency".to_string(),
                "success_rate".to_string(),
            ],
        }
    }

    pub fn train(&mut self, events: &[AccessEvent], anomalies: &[AccessEvent]) {
        let (features, labels) = self.prepare_training_data(events, anomalies);
        
        if features.is_empty() {
            return;
        }

        let x = DenseMatrix::from_2d_vec(&features);
        let y = labels.iter().map(|&x| x as i32).collect::<Vec<_>>();

        // Train-test split
        let (x_train, _x_test, y_train, _y_test) = train_test_split(
            &x, 
            &y, 
            0.2, 
            true,
            Some(42)
        );

        // Train model
        let model = RandomForestClassifier::fit(
            &x_train, 
            &y_train,
            Default::default()
        ).unwrap();

        self.model = Some(model);
    }

    pub fn predict(&self, event: &AccessEvent) -> Option<MLPrediction> {
        let model = self.model.as_ref()?;
        
        let features = self.extract_features(event);
        let x = DenseMatrix::from_2d_vec(&vec![features]);
        
        let prediction = model.predict(&x).ok()?;
        
        // Basit bir güven skoru hesapla
        let confidence = if prediction[0] == 1 { 0.8 } else { 0.2 };

        Some(MLPrediction {
            is_anomaly: prediction[0] == 1,
            confidence,
            features: self.feature_names.clone(),
            timestamp: Utc::now(),
        })
    }

    fn extract_features(&self, event: &AccessEvent) -> Vec<f64> {
        vec![
            event.timestamp.hour() as f64,
            event.timestamp.weekday().num_days_from_monday() as f64,
            event.duration.as_secs_f64(),
            1.0, // Resource frequency (placeholder)
            if event.success { 1.0 } else { 0.0 },
        ]
    }

    fn prepare_training_data(&self, events: &[AccessEvent], anomalies: &[AccessEvent]) 
        -> (Vec<Vec<f64>>, Vec<f64>) 
    {
        let mut features = Vec::new();
        let mut labels = Vec::new();

        for event in events {
            features.push(self.extract_features(event));
            
            // Eğer event bir anomaliye denk geliyorsa label'ı 1, değilse 0
            let is_anomaly = anomalies.iter().any(|a| {
                (event.timestamp - a.timestamp).num_minutes().abs() < 1
            });
            
            labels.push(if is_anomaly { 1.0 } else { 0.0 });
        }

        (features, labels)
    }

    pub fn evaluate_model(&self, test_events: &[AccessEvent], test_anomalies: &[AccessEvent]) -> Option<ModelMetrics> {
        let model = self.model.as_ref()?;
        let start_time = Instant::now();
        
        let (features, actual_labels) = self.prepare_training_data(test_events, test_anomalies);
        if features.is_empty() {
            return None;
        }

        let x = DenseMatrix::from_2d_vec(&features);
        let predictions = model.predict(&x).ok()?;
        
        // Confusion matrix hesapla
        let mut confusion_matrix = ConfusionMatrix::new();
        for (pred, actual) in predictions.iter().zip(actual_labels.iter()) {
            confusion_matrix.update(
                (*pred as i32) == 1,
                (*actual as i32) == 1
            );
        }

        // Feature importance hesapla
        let feature_importance = self.calculate_feature_importance();

        Some(ModelMetrics {
            model_id: format!("rf_model_{}", Utc::now().timestamp()),
            timestamp: Utc::now(),
            accuracy: confusion_matrix.accuracy(),
            precision: confusion_matrix.precision(),
            recall: confusion_matrix.recall(),
            f1_score: confusion_matrix.f1_score(),
            confusion_matrix,
            feature_importance,
            training_duration: start_time.elapsed(),
        })
    }

    fn calculate_feature_importance(&self) -> HashMap<String, f64> {
        let mut importance = HashMap::new();
        
        // Her özellik için basit bir önem skoru hesapla
        for (idx, name) in self.feature_names.iter().enumerate() {
            let score = 1.0 / (idx + 1) as f64; // Basit bir skor hesaplama
            importance.insert(name.clone(), score);
        }

        // Skorları normalize et
        let total: f64 = importance.values().sum();
        for score in importance.values_mut() {
            *score /= total;
        }

        importance
    }

    pub fn predict_with_threshold(&self, event: &AccessEvent, threshold: f64) -> Option<MLPrediction> {
        let prediction = self.predict(event)?;
        
        // Eğer güven skoru threshold'un altındaysa anomali olarak işaretle
        let is_anomaly = prediction.confidence > threshold;
        
        Some(MLPrediction {
            is_anomaly,
            ..prediction
        })
    }

    pub fn update_model(&mut self, new_events: &[AccessEvent], new_anomalies: &[AccessEvent]) -> Option<ModelMetrics> {
        // Modeli yeni verilerle güncelle
        self.train(new_events, new_anomalies);
        
        // Model performansını değerlendir
        self.evaluate_model(new_events, new_anomalies)
    }
}