Riy777 commited on
Commit
6bed741
·
verified ·
1 Parent(s): 1d8d5f9

Delete learning_hub/trainer.py

Browse files
Files changed (1) hide show
  1. learning_hub/trainer.py +0 -106
learning_hub/trainer.py DELETED
@@ -1,106 +0,0 @@
1
- # learning_hub/trainer.py
2
- # (V1.0 - Internal Incremental Trainer)
3
-
4
- import os
5
- import json
6
- import asyncio
7
- import traceback
8
- import numpy as np
9
- import pandas as pd
10
- from datetime import datetime
11
- import xgboost as xgb
12
- from .schemas import TrainingReport
13
-
14
- class InternalTrainer:
15
- def __init__(self, r2_service, memory_store):
16
- self.r2 = r2_service
17
- self.memory_store = memory_store
18
- self.local_model_path = "ml_models/layer2/Titan_XGB_V1.json"
19
- self.training_lock = asyncio.Lock()
20
- print("✅ Learning Hub: Internal Trainer loaded")
21
-
22
- async def run_training_cycle(self):
23
- """دورة التدريب الكاملة: تحميل -> تدريب -> تقييم -> نشر"""
24
- if self.training_lock.locked(): return
25
-
26
- async with self.training_lock:
27
- print("🏋️‍♂️ [Trainer] Starting internal training session...")
28
- try:
29
- # 1. تحميل البيانات الجديدة
30
- samples = await self.memory_store.load_and_clear_pending_samples()
31
- if not samples: return
32
-
33
- df = pd.DataFrame([s.model_dump() for s in samples])
34
- X_new = np.array(df['features'].tolist())
35
- y_new = np.array(df['label'].tolist())
36
-
37
- # 2. تحميل النموذج الحالي
38
- if not os.path.exists(self.local_model_path):
39
- print("❌ [Trainer] Base model not found locally!")
40
- return
41
-
42
- model = xgb.Booster()
43
- model.load_model(self.local_model_path)
44
-
45
- # 3. تقييم الأداء قبل التدريب (Baseline)
46
- dtrain = xgb.DMatrix(X_new, label=y_new)
47
- preds_before = model.predict(dtrain)
48
- acc_before = ((preds_before > 0.5) == y_new).mean()
49
- print(f" -> Accuracy BEFORE update: {acc_before:.2%}")
50
-
51
- # 4. التدريب التزايدي (Incremental Learning)
52
- # نستخدم xgb_model للاستمرار من حيث توقفنا
53
- # نستخدم learning_rate منخفض جداً لتفادي النسيان الكارثي
54
- params = {
55
- 'eta': 0.01, # تعلم بطيء جداً للحفاظ على المعرفة القديمة
56
- 'max_depth': 6,
57
- 'objective': 'binary:logistic',
58
- 'tree_method': 'hist', # سريع جداً
59
- 'eval_metric': 'logloss'
60
- }
61
-
62
- # تدريب لعدد قليل من الجولات (Rounds)
63
- new_model = xgb.train(
64
- params,
65
- dtrain,
66
- num_boost_round=10, # فقط 10 أشجار جديدة لتصحيح المسار
67
- xgb_model=model # ✅ السر: البناء فوق النموذج القديم
68
- )
69
-
70
- # 5. تقييم الأداء بعد التدريب
71
- preds_after = new_model.predict(dtrain)
72
- acc_after = ((preds_after > 0.5) == y_new).mean()
73
- print(f" -> Accuracy AFTER update: {acc_after:.2%}")
74
-
75
- # 6. قرار النشر (Safety Check)
76
- # نقبل النموذج إذا تحسنت الدقة أو بقيت مستقرة، بشرط ألا تنهار
77
- status = "REJECTED"
78
- if acc_after >= acc_before - 0.02: # سماحية بسيطة جداً
79
- status = "SUCCESS"
80
-
81
- # حفظ محلياً
82
- new_model.save_model(self.local_model_path)
83
-
84
- # رفع إلى R2 (تحديث النموذج الحي)
85
- with open(self.local_model_path, "rb") as f:
86
- await self.r2.upload_file_async(f, "ml_models/layer2/Titan_XGB_V1.json")
87
- print(" ✅ [Trainer] New model deployed to R2.")
88
- else:
89
- print(" ⚠️ [Trainer] New model performed worse. Discarding.")
90
-
91
- # 7. رفع التقرير
92
- report = TrainingReport(
93
- model_name="Titan_XGB_Incremental",
94
- samples_count=len(samples),
95
- old_accuracy=acc_before,
96
- new_accuracy=acc_after,
97
- training_status=status,
98
- log_message=f"Trained on {len(samples)} samples. Eta=0.01, Rounds=10."
99
- )
100
-
101
- report_key = f"reports/training_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
102
- await self.r2.upload_json_async(report.model_dump(), report_key)
103
-
104
- except Exception as e:
105
- print(f"❌ [Trainer] Cycle failed: {e}")
106
- traceback.print_exc()