File size: 11,633 Bytes
47f1575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ⏱️ TP-4 : Prédiction de Séries Temporelles avec LSTM\n",
    "\n",
    "**Objectif** : Prédire la consommation électrique avec des réseaux LSTM.\n",
    "\n",
    "**Compétences** :\n",
    "- Préparation de données temporelles\n",
    "- Fenêtres glissantes (windowing)\n",
    "- Architecture LSTM avec Keras\n",
    "- Early stopping et régularisation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
    "\n",
    "import tensorflow as tf\n",
    "from tensorflow.keras.models import Sequential\n",
    "from tensorflow.keras.layers import LSTM, Dense, Dropout\n",
    "from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\n",
    "\n",
    "# Reproductibilité\n",
    "np.random.seed(42)\n",
    "tf.random.set_seed(42)\n",
    "\n",
    "print(f\"✅ TensorFlow version : {tf.__version__}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Génération de données synthétiques (consommation électrique)\n",
    "# En pratique, remplacez par vos données réelles\n",
    "\n",
    "def generate_energy_data(n_days=365*2):\n",
    "    \"\"\"Génère des données de consommation électrique simulées\"\"\"\n",
    "    hours = np.arange(n_days * 24)\n",
    "    \n",
    "    # Tendance\n",
    "    trend = 0.001 * hours\n",
    "    \n",
    "    # Saisonnalité journalière\n",
    "    daily = 10 * np.sin(2 * np.pi * hours / 24)\n",
    "    \n",
    "    # Saisonnalité hebdomadaire\n",
    "    weekly = 5 * np.sin(2 * np.pi * hours / (24 * 7))\n",
    "    \n",
    "    # Saisonnalité annuelle\n",
    "    yearly = 15 * np.sin(2 * np.pi * hours / (24 * 365))\n",
    "    \n",
    "    # Bruit\n",
    "    noise = np.random.normal(0, 3, len(hours))\n",
    "    \n",
    "    # Consommation totale\n",
    "    consumption = 50 + trend + daily + weekly + yearly + noise\n",
    "    consumption = np.maximum(consumption, 0)  # Pas de valeurs négatives\n",
    "    \n",
    "    return consumption\n",
    "\n",
    "# Génération des données\n",
    "data = generate_energy_data(n_days=730)  # 2 ans de données\n",
    "\n",
    "# Création du DataFrame\n",
    "dates = pd.date_range(start='2022-01-01', periods=len(data), freq='H')\n",
    "df = pd.DataFrame({'consumption': data}, index=dates)\n",
    "\n",
    "print(f\"📊 Période : {df.index[0]} à {df.index[-1]}\")\n",
    "print(f\"📊 Total : {len(df)} heures de données\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualisation des données\n",
    "fig, axes = plt.subplots(3, 1, figsize=(15, 10))\n",
    "\n",
    "# Vue complète\n",
    "axes[0].plot(df.index, df['consumption'], alpha=0.7)\n",
    "axes[0].set_title('Consommation électrique - Vue complète (2 ans)')\n",
    "axes[0].set_ylabel('kWh')\n",
    "\n",
    "# Vue d'une semaine\n",
    "one_week = df.iloc[:24*7]\n",
    "axes[1].plot(one_week.index, one_week['consumption'], marker='o')\n",
    "axes[1].set_title('Consommation - Vue hebdomadaire')\n",
    "axes[1].set_ylabel('kWh')\n",
    "\n",
    "# Vue d'une journée\n",
    "one_day = df.iloc[:24]\n",
    "axes[2].plot(one_day.index.hour, one_day['consumption'], marker='o')\n",
    "axes[2].set_title('Consommation - Vue journalière')\n",
    "axes[2].set_xlabel('Heure')\n",
    "axes[2].set_ylabel('kWh')\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Feature Engineering temporel\n",
    "df['hour'] = df.index.hour\n",
    "df['day_of_week'] = df.index.dayofweek\n",
    "df['month'] = df.index.month\n",
    "df['is_weekend'] = (df['day_of_week'] >= 5).astype(int)\n",
    "\n",
    "# Lags (valeurs précédentes)\n",
    "for lag in [1, 2, 3, 24, 48]:\n",
    "    df[f'lag_{lag}'] = df['consumption'].shift(lag)\n",
    "\n",
    "# Rolling statistics\n",
    "df['rolling_mean_24'] = df['consumption'].rolling(window=24).mean()\n",
    "df['rolling_std_24'] = df['consumption'].rolling(window=24).std()\n",
    "\n",
    "# Suppression des NaN\n",
    "df = df.dropna()\n",
    "\n",
    "print(f\"✅ Features créées : {df.shape[1]} colonnes\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Préparation des séquences pour LSTM\n",
    "def create_sequences(data, target_col, sequence_length=24):\n",
    "    \"\"\"\n",
    "    Crée des séquences pour LSTM\n",
    "    data : DataFrame avec features\n",
    "    target_col : nom de la colonne cible\n",
    "    sequence_length : longueur de la séquence (ex: 24 heures)\n",
    "    \"\"\"\n",
    "    X, y = [], []\n",
    "    values = data.values\n",
    "    target_idx = data.columns.get_loc(target_col)\n",
    "    \n",
    "    for i in range(sequence_length, len(values)):\n",
    "        X.append(values[i-sequence_length:i])\n",
    "        y.append(values[i, target_idx])\n",
    "    \n",
    "    return np.array(X), np.array(y)\n",
    "\n",
    "# Séparation train/test\n",
    "train_size = int(len(df) * 0.8)\n",
    "train_df = df.iloc[:train_size]\n",
    "test_df = df.iloc[train_size:]\n",
    "\n",
    "# Normalisation\n",
    "scaler = MinMaxScaler()\n",
    "train_scaled = scaler.fit_transform(train_df)\n",
    "test_scaled = scaler.transform(test_df)\n",
    "\n",
    "# Conversion en DataFrame pour garder les noms de colonnes\n",
    "train_scaled = pd.DataFrame(train_scaled, columns=df.columns, index=train_df.index)\n",
    "test_scaled = pd.DataFrame(test_scaled, columns=df.columns, index=test_df.index)\n",
    "\n",
    "# Création des séquences\n",
    "SEQUENCE_LENGTH = 24  # 24 heures d'historique\n",
    "\n",
    "X_train, y_train = create_sequences(train_scaled, 'consumption', SEQUENCE_LENGTH)\n",
    "X_test, y_test = create_sequences(test_scaled, 'consumption', SEQUENCE_LENGTH)\n",
    "\n",
    "print(f\"📊 X_train shape : {X_train.shape}\")\n",
    "print(f\"📊 y_train shape : {y_train.shape}\")\n",
    "print(f\"📊 X_test shape : {X_test.shape}\")\n",
    "print(f\"📊 y_test shape : {y_test.shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Construction du modèle LSTM\n",
    "model = Sequential([\n",
    "    LSTM(64, return_sequences=True, input_shape=(SEQUENCE_LENGTH, X_train.shape[2])),\n",
    "    Dropout(0.2),\n",
    "    LSTM(32, return_sequences=False),\n",
    "    Dropout(0.2),\n",
    "    Dense(16, activation='relu'),\n",
    "    Dense(1)\n",
    "])\n",
    "\n",
    "model.compile(\n",
    "    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n",
    "    loss='mse',\n",
    "    metrics=['mae']\n",
    ")\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Callbacks\n",
    "callbacks = [\n",
    "    EarlyStopping(\n",
    "        monitor='val_loss',\n",
    "        patience=10,\n",
    "        restore_best_weights=True\n",
    "    ),\n",
    "    ReduceLROnPlateau(\n",
    "        monitor='val_loss',\n",
    "        factor=0.5,\n",
    "        patience=5,\n",
    "        min_lr=1e-6\n",
    "    )\n",
    "]\n",
    "\n",
    "# Entraînement\n",
    "history = model.fit(\n",
    "    X_train, y_train,\n",
    "    epochs=100,\n",
    "    batch_size=32,\n",
    "    validation_split=0.2,\n",
    "    callbacks=callbacks,\n",
    "    verbose=1\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualisation de l'entraînement\n",
    "fig, axes = plt.subplots(1, 2, figsize=(14, 5))\n",
    "\n",
    "# Loss\n",
    "axes[0].plot(history.history['loss'], label='Train')\n",
    "axes[0].plot(history.history['val_loss'], label='Validation')\n",
    "axes[0].set_title('Loss (MSE)')\n",
    "axes[0].set_xlabel('Epoch')\n",
    "axes[0].set_ylabel('Loss')\n",
    "axes[0].legend()\n",
    "\n",
    "# MAE\n",
    "axes[1].plot(history.history['mae'], label='Train')\n",
    "axes[1].plot(history.history['val_mae'], label='Validation')\n",
    "axes[1].set_title('MAE')\n",
    "axes[1].set_xlabel('Epoch')\n",
    "axes[1].set_ylabel('MAE')\n",
    "axes[1].legend()\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prédictions\n",
    "y_pred = model.predict(X_test)\n",
    "\n",
    "# Métriques (sur données normalisées)\n",
    "mse = mean_squared_error(y_test, y_pred)\n",
    "mae = mean_absolute_error(y_test, y_pred)\n",
    "rmse = np.sqrt(mse)\n",
    "\n",
    "print(f\"📊 MSE  : {mse:.6f}\")\n",
    "print(f\"📊 MAE  : {mae:.6f}\")\n",
    "print(f\"📊 RMSE : {rmse:.6f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualisation des prédictions\n",
    "plt.figure(figsize=(15, 6))\n",
    "\n",
    "# Plot des 500 premières prédictions\n",
    "n_plot = 500\n",
    "plt.plot(y_test[:n_plot], label='Réel', alpha=0.8)\n",
    "plt.plot(y_pred[:n_plot], label='Prédit', alpha=0.8)\n",
    "plt.title(f'Prédictions LSTM - {n_plot} premiers points de test')\n",
    "plt.xlabel('Temps')\n",
    "plt.ylabel('Consommation (normalisée)')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Scatter plot : Réel vs Prédit\n",
    "plt.figure(figsize=(8, 8))\n",
    "plt.scatter(y_test, y_pred, alpha=0.5)\n",
    "plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--', lw=2)\n",
    "plt.xlabel('Valeurs réelles')\n",
    "plt.ylabel('Valeurs prédites')\n",
    "plt.title('Réel vs Prédit')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 🎓 Conclusion\n",
    "\n",
    "Dans ce TP, nous avons :\n",
    "\n",
    "1. ✅ **Généré** des données de consommation électrique avec patterns temporels\n",
    "2. ✅ **Créé** des features temporelles (heure, jour, mois, lags, rolling stats)\n",
    "3. ✅ **Préparé** les séquences pour LSTM avec windowing\n",
    "4. ✅ **Construit** un modèle LSTM avec Dropout et Early Stopping\n",
    "5. ✅ **Évalué** les performances sur l'ensemble de test\n",
    "\n",
    "**Améliorations possibles** :\n",
    "- Utiliser des données météo comme features externes\n",
    "- Tester des architectures plus complexes (Bidirectional LSTM, GRU)\n",
    "- Faire du multi-step forecasting (prédire plusieurs heures en avance)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}