-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml_core.py
More file actions
403 lines (332 loc) · 16.1 KB
/
Copy pathml_core.py
File metadata and controls
403 lines (332 loc) · 16.1 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""
ml_core.py - Core ML functionality for keystroke biometrics experiments
"""
import pickle
import warnings
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Tuple, Any, Optional, Callable
from dataclasses import dataclass
import pandas as pd
import numpy as np
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from catboost import CatBoostClassifier, Pool
from sklearn.metrics import (
accuracy_score, classification_report, f1_score, precision_score,
recall_score, top_k_accuracy_score, confusion_matrix
)
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
import bob.measure
from ml_visualizer import Visualizer
from ml_utils import (
prepare_param_grid, perform_grid_search, check_gpu_availability
)
# Suppress warnings
warnings.filterwarnings('ignore', category=UserWarning)
warnings.filterwarnings('ignore', category=FutureWarning)
@dataclass
class ExperimentConfig:
"""Configuration for experiments."""
config_dict: Dict[str, Any]
def __getattr__(self, name):
return self.config_dict.get(name)
@property
def dataset_path(self):
return self.config_dict.get('dataset_path', '')
@property
def early_stopping(self):
return self.config_dict.get('early_stopping', False)
@property
def random_seeds(self):
return self.config_dict.get('seeds', [42])
@property
def output_affix(self):
return self.config_dict.get('output_affix', '')
@property
def show_class_distributions(self):
return self.config_dict.get('show_class_distributions', False)
@property
def draw_feature_importance(self):
return self.config_dict.get('draw_feature_importance', True)
@property
def debug_mode(self):
return self.config_dict.get('debug', False)
@property
def models_to_train(self):
return self.config_dict.get('models_to_train', [])
@property
def experiments(self):
return self.config_dict.get('experiments', [])
@property
def param_grids(self):
return self.config_dict.get('param_grids', {})
@property
def use_gpu(self):
return self.config_dict.get('use_gpu', True)
@dataclass
class ExperimentResult:
"""Container for experiment results."""
model_name: str
experiment_name: str
random_seed: int
train_metrics: Dict[str, float]
test_metrics: Dict[str, float]
model_path: str
hyperparameters: Dict[str, Any]
cross_validation_used: bool
class ModelTrainer:
"""Handles training and evaluation of ML models."""
def __init__(self, config: ExperimentConfig, output_dir: Path, timestamp: str):
self.config = config
self.output_dir = output_dir
self.timestamp = timestamp
self.label_encoder = LabelEncoder()
# GPU usage: enabled by default if available, unless config explicitly disables it
# Config use_gpu=True (default): use GPU if available
# Config use_gpu=False: force CPU mode (useful when GPU needed for other tasks)
if config.use_gpu:
self.use_gpu = check_gpu_availability()
if self.use_gpu:
print("🎮 GPU acceleration enabled")
else:
print("⚠️ GPU requested but not available, using CPU mode")
else:
self.use_gpu = False
print("💻 CPU mode (GPU disabled in config)")
def calculate_metrics(self, y_true: np.ndarray, y_pred: np.ndarray,
y_pred_proba: np.ndarray, prefix: str) -> Dict[str, float]:
"""Calculate comprehensive metrics."""
metrics = {
f'{prefix}_accuracy': accuracy_score(y_true, y_pred),
f'{prefix}_f1_weighted': f1_score(y_true, y_pred, average="weighted", zero_division=0),
f'{prefix}_f1_macro': f1_score(y_true, y_pred, average="macro", zero_division=0),
f'{prefix}_precision_weighted': precision_score(y_true, y_pred, average="weighted", zero_division=0),
f'{prefix}_precision_macro': precision_score(y_true, y_pred, average="macro", zero_division=0),
f'{prefix}_recall_weighted': recall_score(y_true, y_pred, average="weighted", zero_division=0),
f'{prefix}_recall_macro': recall_score(y_true, y_pred, average="macro", zero_division=0),
}
# Top-k accuracy
max_k = min(5, y_pred_proba.shape[1])
for k in range(1, max_k + 1):
try:
top_k_acc = top_k_accuracy_score(y_true, y_pred_proba, k=k)
metrics[f'{prefix}_top_{k}_accuracy'] = top_k_acc
except Exception:
metrics[f'{prefix}_top_{k}_accuracy'] = 0.0
# Recognition rate using bob.measure
try:
rr_scores = []
for i, true_label in enumerate(y_true):
if true_label < y_pred_proba.shape[1]:
pos_score = y_pred_proba[i, true_label]
neg_scores = np.delete(y_pred_proba[i], true_label)
rr_scores.append((neg_scores, [pos_score]))
if rr_scores:
recognition_rate = bob.measure.recognition_rate(rr_scores, rank=1)
metrics[f'{prefix}_recognition_rate'] = recognition_rate
else:
metrics[f'{prefix}_recognition_rate'] = 0.0
except Exception as e:
print(f"⚠️ Could not calculate recognition rate: {e}")
metrics[f'{prefix}_recognition_rate'] = 0.0
return metrics
def save_model(self, model: Any, model_name: str, experiment_name: str,
hyperparams: Dict, metrics: Dict, seed: int) -> str:
"""Save model with comprehensive metadata."""
clean_experiment_name = experiment_name.replace(f"_{model_name}", "").replace("_no_scaling", "")
filename = f"{model_name.lower()}_{clean_experiment_name}_{self.timestamp}_seed{seed}.pkl"
if self.config.early_stopping:
filename = filename.replace('.pkl', '_early_stop.pkl')
filepath = self.output_dir / filename
metadata = {
'model_name': model_name,
'experiment_name': experiment_name,
'clean_experiment_name': clean_experiment_name,
'timestamp': self.timestamp,
'random_seed': seed,
'early_stopping_used': self.config.early_stopping,
'debug_mode': self.config.debug_mode,
'hyperparameters': hyperparams,
'performance_metrics': metrics,
'task_type': 'user_identification',
'data_preprocessing': 'pre_normalized'
}
model_data = {
'model': model,
'metadata': metadata
}
with open(filepath, 'wb') as f:
pickle.dump(model_data, f)
print(f"💾 Model saved: {filename}")
return str(filepath)
def train_model_generic(self,
model_class: Any,
model_name: str,
X_train: np.ndarray,
X_test: np.ndarray,
y_train: np.ndarray,
y_test: np.ndarray,
experiment_name: str,
seed: int,
custom_fit_func: Optional[Callable] = None) -> ExperimentResult:
"""Generic model training function to reduce code duplication."""
print(f"🔍 Training {model_name} - {experiment_name}")
# Get parameter grid
param_grid = self.config.param_grids.get(model_name.lower(), {})
param_grid = prepare_param_grid(
param_grid,
self.config.early_stopping,
self.use_gpu,
model_name.lower()
)
# Initialize model with seed if applicable
model_init_params = {}
if model_name.lower() in ['randomforest', 'xgboost', 'svm', 'mlp', 'lightgbm', 'extratrees', 'gradientboosting', 'logisticregression']:
model_init_params['random_state'] = seed
if model_name.lower() == 'catboost':
# CatBoost uses random_seed, not random_state
model_init_params['random_seed'] = seed
model_init_params['verbose'] = False
model_init_params['thread_count'] = -1
if model_name.lower() in ['randomforest', 'extratrees']:
model_init_params['n_jobs'] = -1
if model_name.lower() == 'xgboost':
model_init_params['n_jobs'] = -1
if model_name.lower() == 'lightgbm':
model_init_params['n_jobs'] = -1
model_init_params['verbose'] = -1
if model_name.lower() == 'gradientboosting':
model_init_params['verbose'] = 0
if model_name.lower() == 'svm':
model_init_params['probability'] = True
if model_name.lower() == 'knn':
model_init_params['n_jobs'] = -1 # KNN supports parallel distance computation
if model_name.lower() == 'logisticregression':
model_init_params['n_jobs'] = -1 # LogisticRegression supports parallel computation
# Create model instance
try:
model_instance = model_class(**model_init_params)
except Exception as e:
print(f"⚠️ Error initializing {model_name}: {e}")
raise e
# Perform grid search or direct training
if param_grid and len(param_grid) > 0:
model, best_params, cv_used = perform_grid_search(
model_instance,
param_grid,
X_train,
y_train,
cv_folds=2,
random_seed=seed,
n_jobs=1 if model_name.lower() in ['catboost', 'svm'] else -1
)
else:
# Direct training without grid search
model = model_instance
if custom_fit_func:
custom_fit_func(model, X_train, y_train, X_test, y_test)
else:
model.fit(X_train, y_train)
best_params = model.get_params()
cv_used = False # No cross-validation used
# Handle early stopping for specific models
if self.config.early_stopping and model_name.lower() in ['xgboost', 'catboost']:
model = self._train_with_early_stopping(
model_class, model_name, best_params,
X_train, y_train, X_test, y_test, seed
)
# Predictions and metrics
train_pred = model.predict(X_train)
test_pred = model.predict(X_test)
train_proba = model.predict_proba(X_train)
test_proba = model.predict_proba(X_test)
train_metrics = self.calculate_metrics(y_train, train_pred, train_proba, "train")
test_metrics = self.calculate_metrics(y_test, test_pred, test_proba, "test")
all_metrics = {**train_metrics, **test_metrics}
# Create visualizations
clean_exp_name = experiment_name.replace("_no_scaling", "")
visualizer = Visualizer(self.config, self.output_dir, self.timestamp)
visualizer.create_confusion_matrices(y_test, test_proba,
f"{model_name} {clean_exp_name}",
f"{model_name.lower()}_{clean_exp_name}")
# Feature importance plot for tree-based models
if self.config.draw_feature_importance and model_name.lower() in ['randomforest', 'xgboost', 'catboost','extratrees', 'gradientboosting', 'lightgbm']:
visualizer.plot_feature_importance(model, model_name, experiment_name,
[f"feature_{i}" for i in range(X_train.shape[1])])
# Save model
model_path = self.save_model(model, model_name, experiment_name, best_params, all_metrics, seed)
return ExperimentResult(model_name, experiment_name, seed, train_metrics,
test_metrics, model_path, best_params, cv_used)
def _train_with_early_stopping(self, model_class: Any, model_name: str,
best_params: Dict, X_train: np.ndarray,
y_train: np.ndarray, X_test: np.ndarray,
y_test: np.ndarray, seed: int) -> Any:
"""Handle early stopping for XGBoost and CatBoost."""
if model_name.lower() == 'xgboost':
# Remove n_estimators from params to avoid conflict
early_stop_params = {k: v for k, v in best_params.items() if k != 'n_estimators'}
# Remove random_state from early_stop_params if it exists to avoid duplicate
early_stop_params.pop('random_state', None)
model = XGBClassifier(
**early_stop_params,
n_estimators=1000,
random_state=seed,
n_jobs=-1,
eval_metric='mlogloss',
early_stopping_rounds=50
)
model.fit(
X_train, y_train,
eval_set=[(X_test, y_test)],
verbose=False
)
elif model_name.lower() == 'catboost':
# Remove iterations from params to avoid conflict
early_stop_params = {k: v for k, v in best_params.items() if k != 'iterations'}
# Remove random_state from early_stop_params if it exists to avoid duplicate
early_stop_params.pop('random_state', None)
eval_set = Pool(X_test, y_test)
model = CatBoostClassifier(
**early_stop_params,
iterations=1000,
random_seed=seed,
verbose=False,
thread_count=-1,
early_stopping_rounds=50
)
model.fit(
X_train, y_train,
eval_set=eval_set,
use_best_model=True
)
return model
# Specific model training functions (simplified wrappers)
def train_naive_bayes(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(GaussianNB, "NaiveBayes", *args, **kwargs)
def train_random_forest(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(RandomForestClassifier, "RandomForest", *args, **kwargs)
def train_xgboost(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(XGBClassifier, "XGBoost", *args, **kwargs)
def train_catboost(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(CatBoostClassifier, "CatBoost", *args, **kwargs)
def train_mlp(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(MLPClassifier, "MLP", *args, **kwargs)
def train_svm(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(SVC, "SVM", *args, **kwargs)
def train_lightgbm(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(LGBMClassifier, "LightGBM", *args, **kwargs)
def train_extratrees(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(ExtraTreesClassifier, "ExtraTrees", *args, **kwargs)
def train_gradientboosting(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(GradientBoostingClassifier, "GradientBoosting", *args, **kwargs)
def train_knn(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(KNeighborsClassifier, "KNN", *args, **kwargs)
def train_logisticregression(self, *args, **kwargs) -> ExperimentResult:
return self.train_model_generic(LogisticRegression, "LogisticRegression", *args, **kwargs)