Spaces:
Sleeping

money-rain commited on
Commit
086f168
·
verified ·
1 Parent(s): 82782ac

Delete ml_factory.py

Browse files
Files changed (1) hide show
  1. ml_factory.py +0 -370
ml_factory.py DELETED
@@ -1,370 +0,0 @@
1
- import os
2
- import json
3
- import time
4
- import math
5
- import threading
6
- import queue
7
- import pandas as pd
8
- import numpy as np
9
- import matplotlib.pyplot as plt
10
- import config
11
- import database as db_manager
12
- from ml_core import RegressionModel, ClassificationModel
13
-
14
- from sklearn.neural_network import MLPClassifier, MLPRegressor
15
- import river
16
- from river import tree as river_tree
17
- from river import linear_model as river_lm
18
-
19
- class ModelManager:
20
- def __init__(self, db_instance):
21
- self.db = db_instance
22
- self.models = {}
23
- self.lock = threading.Lock()
24
- self.train_queue = queue.Queue()
25
- self.auto_generated = set()
26
- self.training_status = {}
27
-
28
- self._load_existing_models()
29
- self.worker_thread = threading.Thread(target=self._worker_loop, daemon=True)
30
- self.worker_thread.start()
31
-
32
- def _instantiate_model(self, model_dir):
33
- try:
34
- json_path = os.path.join(model_dir, 'model.json')
35
- pkl_path = os.path.join(model_dir, 'model_weights.pkl')
36
- if not os.path.exists(json_path) or not os.path.exists(pkl_path): return None
37
- with open(json_path, 'r') as f: meta = json.load(f)
38
-
39
- if meta['type'] == "regression":
40
- instance = RegressionModel(name=meta['name'], framework=meta['framework'], algo_name=meta['algorithm'], window_size=meta['window_size'], weights_path=pkl_path)
41
- else:
42
- instance = ClassificationModel(name=meta['name'], framework=meta['framework'], algo_name=meta['algorithm'], window_size=meta['window_size'], threshold=meta['threshold'], weights_path=pkl_path)
43
- instance.total_trained = meta.get('total_trained', 0)
44
-
45
- # Si c'est un modèle auto, on l'ajoute à la liste pour ne pas le recréer
46
- if meta.get('is_auto', False) or instance.name.startswith("Auto_"):
47
- self.auto_generated.add(instance.name)
48
-
49
- self._initialize_features(instance)
50
- return instance
51
- except Exception as e:
52
- print(f"⚠️ Erreur chargement modèle depuis {model_dir}: {e}")
53
- return None
54
-
55
- def _initialize_features(self, instance):
56
- """Ingère la fenêtre d'historique pour aligner la mémoire du modèle avant la 1ère prédiction."""
57
- try:
58
- limit = instance.window_size + 1
59
- if instance.model_type == "regression":
60
- X, y = self.db.get_reg_data(instance.window_size, limit=limit)
61
- else:
62
- X, y = self.db.get_bin_data(instance.window_size, instance.threshold, limit=limit)
63
-
64
- total = len(X)
65
- if total < limit:
66
- # Pas assez de données pour initialiser
67
- instance.last_prediction = None
68
- return
69
-
70
- self.training_status[instance.name] = f"Initialisation 0/{total} features"
71
-
72
- for i, seq in enumerate(X):
73
- self.training_status[instance.name] = f"Initialisation {i+1}/{total} features"
74
- instance.last_sequence = seq
75
- time.sleep(0.05) # Mini-pause pour l'UI
76
-
77
- instance.last_prediction = instance.predict(instance.last_sequence) if instance.last_sequence else None
78
-
79
- if instance.name in self.training_status:
80
- del self.training_status[instance.name]
81
-
82
- except Exception as e:
83
- print(f"⚠️ Err initialisation features {instance.name}: {e}")
84
- if instance.name in self.training_status:
85
- del self.training_status[instance.name]
86
-
87
- def _load_existing_models(self):
88
- print("🧠 Chargement des modèles existants...")
89
- dirs_to_scan = [config.MODELS_REG_DIR, config.MODELS_BIN_DIR]
90
- for d in dirs_to_scan:
91
- if not os.path.exists(d): continue
92
- for m_name in os.listdir(d):
93
- m_path = os.path.join(d, m_name)
94
- if os.path.isdir(m_path):
95
- instance = self._instantiate_model(m_path)
96
- if instance:
97
- with self.lock:
98
- self.models[instance.name] = instance
99
- print(f" ✅ {instance.name} chargé (Données: {instance.total_trained:,}).")
100
-
101
- def check_auto_generation(self, current_history_length):
102
- """Vérifie pour chaque fenêtre si on a atteint la taille critique pour créer les modèles Auto."""
103
- for w in config.WINDOWS:
104
- if current_history_length >= w + 1:
105
- # Modèle de Régression
106
- reg_name = f"Auto_Reg_W{w}"
107
- if reg_name not in self.auto_generated:
108
- self.train_queue.put(("regression", reg_name, w, None, "river"))
109
- self.auto_generated.add(reg_name)
110
- print(f"🤖 [Auto-Factory] Création de {reg_name} déclenchée (Dataset W{w} prêt) !")
111
-
112
- # Modèles de Classification Binaire
113
- for t in config.THRESHOLDS:
114
- bin_name = f"Auto_Bin_W{w}_T{t}"
115
- if bin_name not in self.auto_generated:
116
- self.train_queue.put(("binary", bin_name, w, t, "river"))
117
- self.auto_generated.add(bin_name)
118
- print(f"🤖 [Auto-Factory] Création de {bin_name} déclenchée !")
119
-
120
- def _worker_loop(self):
121
- while True:
122
- try:
123
- m_type, name, window, threshold, framework = self.train_queue.get()
124
- print(f"🔧 [Usine] Début création de {name}...")
125
- self._create_and_train_model(m_type, name, window, threshold, framework, is_auto=True)
126
- self.train_queue.task_done()
127
- except Exception as e:
128
- print(f"❌ [Usine] Erreur fatale : {e}")
129
- time.sleep(5)
130
-
131
- def _create_and_train_model(self, m_type, name, window, threshold, framework, is_auto=False):
132
- if m_type == "regression":
133
- save_dir = os.path.join(config.MODELS_REG_DIR, name)
134
- db_getter = self.db.get_reg_data
135
- else:
136
- save_dir = os.path.join(config.MODELS_BIN_DIR, name)
137
- db_getter = self.db.get_bin_data
138
-
139
- os.makedirs(save_dir, exist_ok=True)
140
- pkl_path = os.path.join(save_dir, 'model_weights.pkl')
141
- json_path = os.path.join(save_dir, 'model.json')
142
-
143
- if m_type == "binary": X, y = db_getter(window, threshold)
144
- else: X, y = db_getter(window)
145
-
146
- total_data = len(X)
147
- if total_data < window + 1:
148
- if name in self.training_status: del self.training_status[name]
149
- return f"❌ Pas assez de données ({total_data} lignes)."
150
-
151
- self.training_status[name] = f"Entraînement 0/{total_data} cotes"
152
- algo_name = ""
153
- try:
154
- if framework == "sklearn":
155
- if m_type == "regression":
156
- model = MLPRegressor(hidden_layer_sizes=(32, 16), max_iter=200, random_state=42)
157
- model.fit(np.array(X), np.array(y))
158
- algo_name = "MLPRegressor"
159
- else:
160
- model = MLPClassifier(hidden_layer_sizes=(32, 16), max_iter=200, random_state=42)
161
- model.fit(np.array(X), np.array(y))
162
- algo_name = "MLPClassifier"
163
- else:
164
- if m_type == "regression":
165
- model = river_lm.LinearRegression()
166
- algo_name = "River LinearRegression"
167
- else:
168
- model = river_tree.HoeffdingAdaptiveTreeClassifier(seed=42)
169
- algo_name = "River Hoeffding Tree"
170
-
171
- for i, (x_seq, y_val) in enumerate(zip(X, y)):
172
- x_dict = {f"t-{i}": val for i, val in enumerate(reversed(x_seq))}
173
- model.learn_one(x_dict, y_val)
174
- if (i+1) % 10 == 0 or (i+1) == total_data:
175
- self.training_status[name] = f"Entraînement {i+1}/{total_data} cotes"
176
-
177
- import joblib
178
- joblib.dump(model, pkl_path)
179
- meta = {"name": name, "type": m_type, "framework": framework, "algorithm": algo_name, "window_size": window, "threshold": threshold, "created_at": time.time(), "is_auto": is_auto, "total_trained": total_data}
180
- with open(json_path, 'w') as f: json.dump(meta, f, indent=4)
181
-
182
- if m_type == "regression":
183
- instance = RegressionModel(name, framework, algo_name, window, pkl_path)
184
- else:
185
- instance = ClassificationModel(name, framework, algo_name, window, threshold, pkl_path)
186
- instance.total_trained = total_data
187
-
188
- with self.lock:
189
- self.models[name] = instance
190
-
191
- # Lancement de l'initialisation des features
192
- self._initialize_features(instance)
193
-
194
- return f"✅ {name} créé sur {total_data} lignes. Prédit: {instance.last_prediction}"
195
- except Exception as e:
196
- if name in self.training_status: del self.training_status[name]
197
- return f"❌ Erreur entraînement {name} : {str(e)}"
198
-
199
- def create_manual_model(self, name, m_type, window, threshold, framework):
200
- name = name.strip().replace(" ", "_")
201
- if not name: return "❌ Nom invalide.", ""
202
- if m_type == "binary" and threshold not in config.THRESHOLDS:
203
- db_path = self.db._get_bin_path(window, threshold)
204
- if not os.path.exists(db_path):
205
- count, msg = self.db.generate_custom_binary_db(window, threshold)
206
- if count == 0: return msg, ""
207
- result = self._create_and_train_model(m_type, name, window, threshold, framework)
208
- return result, name
209
-
210
- def process_round(self, raw_history, raw_cote):
211
- try:
212
- raw_history = [float(x) for x in raw_history]
213
- raw_cote = float(raw_cote)
214
- except:
215
- print("⚠️ [ML] Erreur conversion historique en float. Ignoré.")
216
- return
217
- with self.lock:
218
- for model in self.models.values():
219
- try:
220
- if model.model_type == "regression":
221
- model.evaluate_and_update(raw_history, raw_cote)
222
- else:
223
- binary_history = [config.get_label(x, model.threshold) for x in raw_history]
224
- label = config.get_label(raw_cote, model.threshold)
225
- model.evaluate_and_update(binary_history, label)
226
- if model.total_trained % 50 == 0:
227
- self._update_model_meta(model)
228
- except Exception as e:
229
- print(f"⚠️ Err process {model.name}: {e}")
230
-
231
- def _update_model_meta(self, model):
232
- if model.model_type == "regression":
233
- json_path = os.path.join(config.MODELS_REG_DIR, model.name, 'model.json')
234
- else:
235
- json_path = os.path.join(config.MODELS_BIN_DIR, model.name, 'model.json')
236
- try:
237
- if os.path.exists(json_path):
238
- with open(json_path, 'r') as f: meta = json.load(f)
239
- meta['total_trained'] = model.total_trained
240
- with open(json_path, 'w') as f: json.dump(meta, f, indent=4)
241
- except: pass
242
-
243
- def toggle_training(self, name, state):
244
- with self.lock:
245
- if name in self.models:
246
- self.models[name].is_training = state
247
- return f"Entraînement {'Activé' if state else 'Mis en Pause'}."
248
- return "❌ Modèle introuvable."
249
-
250
- def get_model_names(self):
251
- with self.lock: return list(self.models.keys())
252
-
253
- def get_model_dashboard(self, name):
254
- with self.lock:
255
- if name in self.models: return self.models[name].get_metrics()
256
- return "### 👈 Modèle introuvable."
257
-
258
- def get_model_state(self, name):
259
- with self.lock:
260
- if name in self.models: return self.models[name].is_training
261
- return False
262
-
263
- def get_leaderboards(self, reg_sort="MAE (Erreur Moy)", reg_order="Croissant", bin_sort="F1-Score %", bin_order="Décroissant"):
264
- reg_data, bin_data = [], []
265
- with self.lock:
266
- for name, model in self.models.items():
267
- init_status = self.training_status.get(name)
268
-
269
- if model.model_type == "regression":
270
- mae = np.mean(model.mae_deque) if model.mae_deque else 0
271
- rmse = math.sqrt(np.mean(model.sq_error_deque)) if model.sq_error_deque else 0
272
-
273
- if init_status: status = init_status
274
- elif not model.is_training: status = "🔴 En Pause"
275
- elif model.last_prediction is not None: status = f"🟢 Prédit: {model.last_prediction:.2f}x"
276
- else: status = "🟡 En attente de features..."
277
-
278
- reg_data.append({
279
- "Modèle": name, "Fenêtre (W)": model.window_size,
280
- "MAE (Erreur Moy)": float(f"{mae:.2f}"), "RMSE": float(f"{rmse:.2f}"),
281
- "Taille Données": model.total_trained, "Statut": status
282
- })
283
- else:
284
- acc = sum(model.accuracy_deque) / len(model.accuracy_deque) * 100 if model.accuracy_deque else 0
285
- f1, mcc = 0.0, 0.0
286
- if len(model.history_deque) > 10:
287
- tp = sum(1 for yt, yp in model.history_deque if yt == 0 and yp == 0)
288
- tn = sum(1 for yt, yp in model.history_deque if yt == 1 and yp == 1)
289
- fp = sum(1 for yt, yp in model.history_deque if yt == 1 and yp == 0)
290
- fn = sum(1 for yt, yp in model.history_deque if yt == 0 and yp == 1)
291
- prec = (tp / (tp + fp)) * 100 if (tp + fp) > 0 else 0
292
- rec = (tp / (tp + fn)) * 100 if (tp + fn) > 0 else 0
293
- f1 = (2 * prec * rec) / (prec + rec) if (prec + rec) > 0 else 0
294
- denom = math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn))
295
- mcc = ((tp*tn) - (fp*fn)) / denom if denom > 0 else 0
296
-
297
- if len(model.f1_history) == 0 or model.f1_history[-1][0] != model.total_trained:
298
- model.f1_history.append((model.total_trained, f1))
299
-
300
- if init_status: status = init_status
301
- elif not model.is_training: status = "🔴 En Pause"
302
- elif model.last_prediction is not None: status = f"🟢 Prédit: {model.last_prediction}"
303
- else: status = "🟡 En attente de features..."
304
-
305
- bin_data.append({
306
- "Modèle": name, "Fenêtre (W)": model.window_size, "Seuil (T)": f"{model.threshold}x",
307
- "Exactitude %": float(f"{acc:.1f}"), "F1-Score %": float(f"{f1:.1f}"),
308
- "MCC": float(f"{mcc:.3f}"), "Taille Données": model.total_trained, "Statut": status
309
- })
310
-
311
- df_reg = pd.DataFrame(reg_data)
312
- if not df_reg.empty:
313
- df_reg = df_reg.sort_values(by=reg_sort, ascending=(reg_order == "Croissant"))
314
-
315
- df_bin = pd.DataFrame(bin_data)
316
- if not df_bin.empty:
317
- df_bin = df_bin.sort_values(by=bin_sort, ascending=(bin_order == "Croissant"))
318
-
319
- fig_mae, fig_rmse, fig_f1, fig_acc = self._generate_charts(df_reg, df_bin)
320
-
321
- if not df_reg.empty:
322
- df_reg['MAE (Erreur Moy)'] = df_reg['MAE (Erreur Moy)'].astype(str) + "x"
323
- df_reg['RMSE'] = df_reg['RMSE'].astype(str) + "x"
324
- df_reg['Taille Données'] = df_reg['Taille Données'].astype(str) + " enr."
325
- if not df_bin.empty:
326
- df_bin['Exactitude %'] = df_bin['Exactitude %'].astype(str) + "%"
327
- df_bin['F1-Score %'] = df_bin['F1-Score %'].astype(str) + "%"
328
- df_bin['Taille Données'] = df_bin['Taille Données'].astype(str) + " enr."
329
-
330
- return df_reg, df_bin, fig_mae, fig_rmse, fig_f1, fig_acc
331
-
332
- def _generate_charts(self, df_reg, df_bin):
333
- fig_mae, ax = plt.subplots(figsize=(5, 3))
334
- if not df_reg.empty:
335
- ax.bar(df_reg['Modèle'], df_reg['MAE (Erreur Moy)'], color='#10b981')
336
- ax.set_title('MAE par Modèle (Régression)')
337
- ax.set_ylabel('MAE (x)')
338
- plt.xticks(rotation=45, ha='right')
339
- plt.tight_layout()
340
-
341
- fig_rmse, ax = plt.subplots(figsize=(5, 3))
342
- if not df_reg.empty:
343
- ax.bar(df_reg['Modèle'], df_reg['RMSE'], color='#3b82f6')
344
- ax.set_title('RMSE par Modèle (Régression)')
345
- ax.set_ylabel('RMSE (x)')
346
- plt.xticks(rotation=45, ha='right')
347
- plt.tight_layout()
348
-
349
- fig_f1, ax = plt.subplots(figsize=(5, 3))
350
- if not df_bin.empty:
351
- for name, model in self.models.items():
352
- if model.model_type == "binary" and len(model.f1_history) > 0:
353
- sizes = [x[0] for x in model.f1_history]
354
- f1s = [x[1] for x in model.f1_history]
355
- ax.plot(sizes, f1s, marker='o', label=name)
356
- ax.set_title('Évolution F1-Score vs Taille Dataset')
357
- ax.set_xlabel('Taille Dataset (enr.)')
358
- ax.set_ylabel('F1-Score (%)')
359
- ax.legend(fontsize=8)
360
- plt.tight_layout()
361
-
362
- fig_acc, ax = plt.subplots(figsize=(5, 3))
363
- if not df_bin.empty:
364
- ax.bar(df_bin['Modèle'], df_bin['Exactitude %'], color='#8b5cf6')
365
- ax.set_title('Précision (100) par Modèle (Binaire)')
366
- ax.set_ylabel('Précision (%)')
367
- plt.xticks(rotation=45, ha='right')
368
- plt.tight_layout()
369
-
370
- return fig_mae, fig_rmse, fig_f1, fig_acc