File size: 7,569 Bytes
5cda98e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Entraînement des modèles ML avec les données locales CSV
VERSION CORRIGÉE - Utilise synthetic_data_v2.csv
"""

import pandas as pd
import numpy as np
import pickle
from pathlib import Path
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import lightgbm as lgb
from tensorflow import keras
from tensorflow.keras import layers
import sys

# Ajouter le dossier parent
sys.path.insert(0, str(Path(__file__).parent.parent))
from src.config import MODEL_CONFIG

print("=" * 80)
print("🤖 ENTRAÎNEMENT MODÈLES - DONNÉES CSV LOCALES (70,000 lignes)")
print("=" * 80)

# ============================================================================
# ÉTAPE 1 : CHARGER LES DONNÉES DEPUIS LE CSV
# ============================================================================

print("\n📂 ÉTAPE 1 : Chargement des données depuis CSV")
print("-" * 80)

csv_path = Path('data/synthetic/synthetic_data_v2.csv')

if not csv_path.exists():
    print(f"❌ Fichier non trouvé : {csv_path}")
    print("Exécutez d'abord : python scripts/generate_new_data.py")
    sys.exit(1)

df = pd.read_csv(csv_path)
print(f"✅ {len(df)} lignes chargées")

# Vérifier les quartiers
quartiers = sorted(df['quartier'].unique())
print(f"\n📊 Quartiers dans les données ({len(quartiers)}) :")
for q in quartiers:
    count = len(df[df['quartier'] == q])
    pct = count / len(df) * 100
    print(f"  {q:25s}: {count:6d} ({pct:5.2f}%)")

# Vérifier distribution coupures
print(f"\n📊 Distribution coupures :")
for val, count in df['coupure'].value_counts().items():
    pct = count / len(df) * 100
    label = "Non" if val == 0 else "Oui"
    print(f"  {label:5s}: {count:6d} ({pct:5.2f}%)")

# ============================================================================
# ÉTAPE 2 : PRÉPARER LES FEATURES
# ============================================================================

print("\n🔧 ÉTAPE 2 : Préparation des features")
print("-" * 80)

# Features à utiliser
feature_cols = MODEL_CONFIG['features']
target_col = MODEL_CONFIG['target']

print(f"Features utilisées ({len(feature_cols)}) :")
for i, feat in enumerate(feature_cols, 1):
    print(f"  {i}. {feat}")

X = df[feature_cols].values
y = df[target_col].values

print(f"\n✅ Features préparées")
print(f"  X shape : {X.shape}")
print(f"  y shape : {y.shape}")
print(f"  Coupures : {y.sum()} ({y.mean()*100:.2f}%)")

# ============================================================================
# ÉTAPE 3 : SPLIT TRAIN/TEST
# ============================================================================

print("\n🔀 ÉTAPE 3 : Split train/test (80/20)")
print("-" * 80)

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=MODEL_CONFIG['test_size'],
    random_state=MODEL_CONFIG['random_state'],
    stratify=y
)

print(f"✅ Train : {len(X_train):,} samples ({y_train.mean()*100:.2f}% coupures)")
print(f"✅ Test  : {len(X_test):,} samples ({y_test.mean()*100:.2f}% coupures)")

# ============================================================================
# ÉTAPE 4 : NORMALISATION
# ============================================================================

print("\n📐 ÉTAPE 4 : Normalisation des données")
print("-" * 80)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(f"✅ Scaler entraîné")
print(f"  Moyennes : {scaler.mean_[:4]}")
print(f"  Écarts-types : {scaler.scale_[:4]}")

# ============================================================================
# ÉTAPE 5 : ENTRAÎNEMENT LIGHTGBM
# ============================================================================

print("\n🌳 ÉTAPE 5 : Entraînement LightGBM")
print("-" * 80)

lgb_params = {
    'objective': 'binary',
    'metric': 'binary_logloss',
    'boosting_type': 'gbdt',
    'num_leaves': 31,
    'learning_rate': 0.05,
    'feature_fraction': 0.9,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': -1,
    'random_state': 42
}

train_data = lgb.Dataset(X_train_scaled, label=y_train)
test_data = lgb.Dataset(X_test_scaled, label=y_test, reference=train_data)

print("🔄 Entraînement en cours...")
lgb_model = lgb.train(
    lgb_params,
    train_data,
    num_boost_round=100,
    valid_sets=[test_data],
    callbacks=[lgb.early_stopping(stopping_rounds=10)]
)

# Évaluation
y_pred_lgb = lgb_model.predict(X_test_scaled)
accuracy_lgb = ((y_pred_lgb > 0.5) == y_test).mean()

print(f"✅ LightGBM entraîné")
print(f"  Précision test : {accuracy_lgb*100:.2f}%")
print(f"  Prédiction moyenne : {y_pred_lgb.mean()*100:.2f}%")

# ============================================================================
# ÉTAPE 6 : ENTRAÎNEMENT LSTM
# ============================================================================

print("\n🧠 ÉTAPE 6 : Entraînement LSTM")
print("-" * 80)

# Reshape pour LSTM (samples, timesteps, features)
X_train_lstm = X_train_scaled.reshape(-1, 1, X_train_scaled.shape[1])
X_test_lstm = X_test_scaled.reshape(-1, 1, X_test_scaled.shape[1])

# Modèle LSTM
lstm_model = keras.Sequential([
    layers.LSTM(64, input_shape=(1, X_train_scaled.shape[1]), return_sequences=True),
    layers.Dropout(0.2),
    layers.LSTM(32),
    layers.Dropout(0.2),
    layers.Dense(16, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

lstm_model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['accuracy']
)

print("🔄 Entraînement en cours (peut prendre 10-15 minutes)...")
history = lstm_model.fit(
    X_train_lstm, y_train,
    validation_data=(X_test_lstm, y_test),
    epochs=50,
    batch_size=32,
    verbose=1,
    callbacks=[
        keras.callbacks.EarlyStopping(patience=5, restore_best_weights=True)
    ]
)

# Évaluation
y_pred_lstm = lstm_model.predict(X_test_lstm, verbose=0).flatten()
accuracy_lstm = ((y_pred_lstm > 0.5) == y_test).mean()

print(f"\n✅ LSTM entraîné")
print(f"  Précision test : {accuracy_lstm*100:.2f}%")
print(f"  Prédiction moyenne : {y_pred_lstm.mean()*100:.2f}%")

# ============================================================================
# ÉTAPE 7 : SAUVEGARDE DES MODÈLES
# ============================================================================

print("\n💾 ÉTAPE 7 : Sauvegarde des modèles")
print("-" * 80)

models_dir = Path('models')
models_dir.mkdir(parents=True, exist_ok=True)

# Sauvegarder LightGBM
lgb_path = models_dir / 'lgbm_model.pkl'
with open(lgb_path, 'wb') as f:
    pickle.dump(lgb_model, f)
print(f"✅ LightGBM sauvegardé : {lgb_path}")

# Sauvegarder LSTM
lstm_path = models_dir / 'lstm_model.keras'
lstm_model.save(lstm_path)
print(f"✅ LSTM sauvegardé : {lstm_path}")

# Sauvegarder Scaler
scaler_path = models_dir / 'scaler.pkl'
with open(scaler_path, 'wb') as f:
    pickle.dump(scaler, f)
print(f"✅ Scaler sauvegardé : {scaler_path}")

# ============================================================================
# RÉSUMÉ FINAL
# ============================================================================

print("\n" + "=" * 80)
print("📊 RÉSUMÉ FINAL")
print("=" * 80)
print(f"✅ Données : {len(df):,} lignes, {len(quartiers)} quartiers")
print(f"✅ LightGBM : {accuracy_lgb*100:.2f}% précision")
print(f"✅ LSTM : {accuracy_lstm*100:.2f}% précision")
print(f"✅ Modèles sauvegardés dans : {models_dir}/")
print("\n" + "=" * 80)
print("✅ ENTRAÎNEMENT TERMINÉ")
print("=" * 80)
print("\nProchaine étape : streamlit run streamlit_app/app.py")