File size: 11,339 Bytes
0162f5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""
ML Model Trainer for Schedule Optimization
Handles model training and retraining with multiple models and ensemble
"""
import os
import pickle
import json
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, Tuple
import numpy as np

from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import xgboost as xgb
import catboost as cb
import lightgbm as lgb

from .config import CONFIG
from .data_store import ScheduleDataStore
from .feature_extractor import FeatureExtractor


class ModelTrainer:
    """Train and manage ML models for schedule optimization"""
    
    def __init__(self, model_dir: Optional[str] = None):
        self.model_dir = Path(model_dir or CONFIG.MODEL_DIR)
        self.model_dir.mkdir(parents=True, exist_ok=True)
        
        self.data_store = ScheduleDataStore()
        self.feature_extractor = FeatureExtractor()
        
        self.models = {}  # Dictionary of trained models
        self.model_scores = {}  # Performance scores for each model
        self.ensemble_weights = {}  # Weights for ensemble
        self.best_model_name = None
        self.last_trained = None
        self.training_history = []
    
    def _get_model(self, model_name: str):
        """Get model instance by name"""
        if model_name == "gradient_boosting":
            return GradientBoostingRegressor(
                n_estimators=CONFIG.EPOCHS,
                learning_rate=CONFIG.LEARNING_RATE,
                random_state=42
            )
        
        elif model_name == "random_forest":
            return RandomForestRegressor(
                n_estimators=CONFIG.EPOCHS,
                random_state=42,
                n_jobs=-1
            )
        
        elif model_name == "xgboost":
            return xgb.XGBRegressor(
                n_estimators=CONFIG.EPOCHS,
                learning_rate=CONFIG.LEARNING_RATE,
                random_state=42,
                verbosity=0
            )
        
        elif model_name == "lightgbm":
            return lgb.LGBMRegressor(
                n_estimators=CONFIG.EPOCHS,
                learning_rate=CONFIG.LEARNING_RATE,
                random_state=42,
                verbose=-1
            )
        
        elif model_name == "catboost":
            return cb.CatBoostRegressor(
                iterations=CONFIG.EPOCHS,
                learning_rate=CONFIG.LEARNING_RATE,
                random_state=42,
                verbose=False
            )
        
        return None
    
    def should_retrain(self) -> bool:
        """Check if model should be retrained"""
        if not self.last_trained:
            # Never trained
            return True
        
        # Check time since last training
        hours_since_training = (
            datetime.now() - self.last_trained
        ).total_seconds() / 3600
        
        if hours_since_training >= CONFIG.RETRAIN_INTERVAL_HOURS:
            # Check if enough new data
            new_schedules = self.data_store.get_schedules_since(self.last_trained)
            if len(new_schedules) >= CONFIG.MIN_SCHEDULES_FOR_RETRAIN:
                return True
        
        return False
    
    def train(self, force: bool = False) -> Dict:
        """Train or retrain all models"""
        
        if not force and not self.should_retrain():
            return {
                "success": False,
                "reason": "Retraining not needed yet"
            }
        
        # Load data
        schedules = self.data_store.load_schedules()
        
        if len(schedules) < CONFIG.MIN_SCHEDULES_FOR_TRAINING:
            return {
                "success": False,
                "reason": f"Not enough data. Need {CONFIG.MIN_SCHEDULES_FOR_TRAINING}, have {len(schedules)}"
            }
        
        # Prepare dataset
        X, y = self.feature_extractor.prepare_dataset(schedules)
        
        if len(X) == 0:
            return {
                "success": False,
                "error": "No valid features extracted"
            }
        
        # Split data
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=CONFIG.TRAIN_TEST_SPLIT, random_state=42
        )
        
        # Train all models
        self.models = {}
        self.model_scores = {}
        all_metrics = {}
        
        for model_name in CONFIG.MODEL_TYPES:
            print(f"Training {model_name}...")
            model = self._get_model(model_name)
            
            if model is None:
                print(f"Skipping {model_name} - not available")
                continue
            
            # Train model
            model.fit(X_train, y_train)
            
            # Evaluate
            train_pred = model.predict(X_train)
            test_pred = model.predict(X_test)

            train_r2 = r2_score(y_train, train_pred) # type: ignore
            test_r2 = r2_score(y_test, test_pred)   # type: ignore
            test_rmse = np.sqrt(mean_squared_error(y_test, test_pred))  # type: ignore
            
            self.models[model_name] = model
            self.model_scores[model_name] = test_r2
            
            all_metrics[model_name] = {
                "train_r2": train_r2,
                "test_r2": test_r2,
                "train_rmse": np.sqrt(mean_squared_error(y_train, train_pred)), # type: ignore
                "test_rmse": test_rmse
            }
            
            print(f"  {model_name}: R² = {test_r2:.4f}, RMSE = {test_rmse:.4f}")
        
        # Compute ensemble weights based on performance
        if CONFIG.USE_ENSEMBLE and len(self.models) > 1:
            total_score = sum(self.model_scores.values())
            self.ensemble_weights = {
                name: score / total_score 
                for name, score in self.model_scores.items()
            }
        else:
            self.ensemble_weights = {}
        
        # Find best model
        if self.model_scores:
            self.best_model_name = max(self.model_scores.items(), key=lambda x: x[1])[0]
        
        # Save model
        self.last_trained = datetime.now()
        self.save_model()
        
        # Record training history
        history_entry = {
            "timestamp": self.last_trained.isoformat(),
            "metrics": all_metrics,
            "best_model": self.best_model_name,
            "ensemble_weights": self.ensemble_weights,
            "config": {
                "models_trained": list(self.models.keys()),
                "version": CONFIG.MODEL_VERSION
            }
        }
        self.training_history.append(history_entry)
        self._save_history()
        
        return {
            "success": True,
            "models_trained": list(self.models.keys()),
            "best_model": self.best_model_name,
            "metrics": all_metrics,
            "ensemble_weights": self.ensemble_weights,
            "samples_used": len(X),
            "timestamp": self.last_trained.isoformat()
        }
    
    def predict(self, features: Dict[str, float], use_ensemble: bool = True) -> Tuple[float, float]:
        """Predict schedule quality and confidence"""
        if not self.models:
            self.load_model()
        
        if not self.models:
            return 0.0, 0.0
        
        # Convert features to vector
        feature_vector = np.array([
            [features.get(f, 0.0) for f in CONFIG.FEATURES]
        ])
        
        if use_ensemble and CONFIG.USE_ENSEMBLE and self.ensemble_weights:
            # Ensemble prediction
            prediction = 0.0
            for model_name, weight in self.ensemble_weights.items():
                if model_name in self.models:
                    pred = self.models[model_name].predict(feature_vector)[0]
                    prediction += weight * pred
            
            # Confidence based on ensemble agreement
            predictions = [
                self.models[name].predict(feature_vector)[0]
                for name in self.models.keys()
            ]
            std_dev = np.std(predictions)
            confidence = max(0.5, min(1.0, 1.0 - (std_dev / 50)))  # Higher agreement = higher confidence
        else:
            # Use best single model
            best_model = self.models.get(self.best_model_name)
            if best_model is None:
                best_model = list(self.models.values())[0]
            
            prediction = best_model.predict(feature_vector)[0]
            confidence = min(1.0, 0.8 + (prediction / 100) * 0.2)
        
        return float(prediction), float(confidence)
    
    def save_model(self):
        """Save all models to disk"""
        if not self.models:
            return
        
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        model_path = self.model_dir / f"models_{timestamp}.pkl"
        latest_path = self.model_dir / "models_latest.pkl"
        
        model_data = {
            "models": self.models,
            "ensemble_weights": self.ensemble_weights,
            "best_model_name": self.best_model_name,
            "last_trained": self.last_trained,
            "config": {
                "version": CONFIG.MODEL_VERSION,
                "features": CONFIG.FEATURES,
                "models_trained": list(self.models.keys())
            }
        }
        
        with open(model_path, 'wb') as f:
            pickle.dump(model_data, f)
        
        with open(latest_path, 'wb') as f:
            pickle.dump(model_data, f)
    
    def load_model(self) -> bool:
        """Load models from disk"""
        latest_path = self.model_dir / "models_latest.pkl"
        
        if not latest_path.exists():
            return False
        
        try:
            with open(latest_path, 'rb') as f:
                model_data = pickle.load(f)
            
            self.models = model_data["models"]
            self.ensemble_weights = model_data.get("ensemble_weights", {})
            self.best_model_name = model_data.get("best_model_name")
            self.last_trained = model_data.get("last_trained")
            return True
        except Exception as e:
            print(f"Error loading models: {e}")
            return False
    
    def _save_history(self):
        """Save training history"""
        history_path = self.model_dir / "training_history.json"
        with open(history_path, 'w') as f:
            json.dump(self.training_history, f, indent=2, default=str)
    
    def get_model_info(self) -> Dict:
        """Get information about current models"""
        if not self.models:
            self.load_model()
        
        return {
            "models_loaded": list(self.models.keys()) if self.models else [],
            "best_model": self.best_model_name,
            "ensemble_enabled": CONFIG.USE_ENSEMBLE,
            "ensemble_weights": self.ensemble_weights,
            "last_trained": self.last_trained.isoformat() if self.last_trained else None,
            "should_retrain": self.should_retrain(),
            "schedules_available": self.data_store.count_schedules(),
            "training_runs": len(self.training_history)
        }