Spaces:
Paused
Paused
Create model_trainer.py
Browse files
learning_hub/model_trainer.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# learning_hub/model_trainer.py
|
| 2 |
+
# (V32.0 - DORMANT: Model Retraining Logic)
|
| 3 |
+
# ⚠️ This module is currently DISABLED by default.
|
| 4 |
+
# It is kept for future manual triggering of model retraining.
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import asyncio
|
| 8 |
+
import traceback
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import xgboost as xgb
|
| 12 |
+
from typing import List, Dict
|
| 13 |
+
|
| 14 |
+
class ModelTrainer:
|
| 15 |
+
"""
|
| 16 |
+
🏋️♂️ The Gym: Responsible for heavy lifting (Model Retraining).
|
| 17 |
+
Not active in the daily loop. Only triggered manually for regime updates.
|
| 18 |
+
"""
|
| 19 |
+
def __init__(self, r2_service):
|
| 20 |
+
self.r2 = r2_service
|
| 21 |
+
self.local_model_path = "ml_models/layer2/Titan_XGB_V1.json"
|
| 22 |
+
print("💤 [ModelTrainer] Module loaded but dormant.")
|
| 23 |
+
|
| 24 |
+
async def train_model_manually(self, training_data: List[Dict]):
|
| 25 |
+
"""
|
| 26 |
+
دالة للتدريب اليدوي عند الحاجة.
|
| 27 |
+
تتوقع قائمة من القواميس تحتوي على 'features' و 'label'.
|
| 28 |
+
"""
|
| 29 |
+
print("🏋️♂️ [ModelTrainer] Manual training sequence started...")
|
| 30 |
+
try:
|
| 31 |
+
if not training_data:
|
| 32 |
+
print("❌ [Trainer] No data provided.")
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
# 1. Prepare Data
|
| 36 |
+
df = pd.DataFrame(training_data)
|
| 37 |
+
if 'features' not in df.columns or 'label' not in df.columns:
|
| 38 |
+
print("❌ [Trainer] Data missing features/label columns.")
|
| 39 |
+
return
|
| 40 |
+
|
| 41 |
+
X = np.array(df['features'].tolist())
|
| 42 |
+
y = np.array(df['label'].tolist())
|
| 43 |
+
dtrain = xgb.DMatrix(X, label=y)
|
| 44 |
+
|
| 45 |
+
# 2. Load Existing Model (Warm Start)
|
| 46 |
+
model = xgb.Booster()
|
| 47 |
+
if os.path.exists(self.local_model_path):
|
| 48 |
+
model.load_model(self.local_model_path)
|
| 49 |
+
print(" -> Loaded existing model for incremental training.")
|
| 50 |
+
|
| 51 |
+
# 3. Train (Incremental)
|
| 52 |
+
params = {
|
| 53 |
+
'eta': 0.01,
|
| 54 |
+
'max_depth': 6,
|
| 55 |
+
'objective': 'binary:logistic',
|
| 56 |
+
'eval_metric': 'logloss'
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# تحديث النموذج بـ 50 جولة فقط
|
| 60 |
+
new_model = xgb.train(params, dtrain, num_boost_round=50, xgb_model=model)
|
| 61 |
+
|
| 62 |
+
# 4. Save
|
| 63 |
+
new_model.save_model(self.local_model_path)
|
| 64 |
+
print(f"✅ [Trainer] Model updated and saved to {self.local_model_path}")
|
| 65 |
+
|
| 66 |
+
# 5. Upload to R2 (Logic commented out until needed)
|
| 67 |
+
# await self.r2.upload_file_async(...)
|
| 68 |
+
|
| 69 |
+
return "Training Success"
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"❌ [Trainer] Training failed: {e}")
|
| 73 |
+
traceback.print_exc()
|
| 74 |
+
return f"Error: {e}"
|