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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "9c91ef58",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import tensorflow as tf\n",
|
| 12 |
+
"import tensorflow.keras.backend as K\n",
|
| 13 |
+
"from tensorflow.keras import layers\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"import collections\n",
|
| 16 |
+
"import logging\n",
|
| 17 |
+
"import numpy as np\n",
|
| 18 |
+
"import tensorflow as tf\n",
|
| 19 |
+
"from tensorflow.keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint, ReduceLROnPlateau\n",
|
| 20 |
+
"import pandas as pd\n",
|
| 21 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 22 |
+
"import os\n",
|
| 23 |
+
"import math\n",
|
| 24 |
+
"import gc"
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"id": "9a965750",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"outputs": [],
|
| 33 |
+
"source": [
|
| 34 |
+
"name = \"ETTm1\" # dataset name\n",
|
| 35 |
+
"seq_len = 512\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"batch_size = 32\n",
|
| 38 |
+
"pred_len = 192\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"feature_type = \"M\"\n",
|
| 41 |
+
"target = \"\"\n",
|
| 42 |
+
"learning_rate = 0.0001\n",
|
| 43 |
+
"patience = 5\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"num_heads=1\n",
|
| 46 |
+
"d_model=16\n",
|
| 47 |
+
"rho = 0.1"
|
| 48 |
+
]
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"id": "d17cf421",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"outputs": [],
|
| 56 |
+
"source": [
|
| 57 |
+
"# please provide your own absolute links here\n",
|
| 58 |
+
"LOCAL_CACHE_DIR = '../Data/Benchmark/' # please include your dataset directory here\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"checkpoint_path = \"../Train_SAM/models/checkpoint\" + name + str(pred_len) + \"_SAM\" + \".model\" # where the model checkpoint should be saved + the .model file type\n",
|
| 61 |
+
"name_df = \"../Results_SAM/\" + name + \"_\" + str(pred_len) + \"_SAM\" + \".csv\" # a filepath .csv file type to save the mse and mae results"
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"id": "5a6e0049",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"outputs": [],
|
| 70 |
+
"source": [
|
| 71 |
+
"class CaptureWeightsCallback(tf.keras.callbacks.Callback):\n",
|
| 72 |
+
" \"\"\"\n",
|
| 73 |
+
" Custom TensorFlow callback for capturing and logging model weights during training, with a focus on attention weights.\n",
|
| 74 |
+
"\n",
|
| 75 |
+
" This callback is designed to monitor the evolution of model weights, particularly attention weights, across training epochs.\n",
|
| 76 |
+
" It facilitates the analysis of training dynamics and model behavior by storing weight snapshots at specified intervals.\n",
|
| 77 |
+
"\n",
|
| 78 |
+
" Attributes:\n",
|
| 79 |
+
" model (tf.keras.Model): Instance of the TensorFlow model being trained. The model should have a method\n",
|
| 80 |
+
" `get_last_attention_weights()` that this callback can invoke to obtain attention weights.\n",
|
| 81 |
+
" attention_weights_history (list): Accumulates the attention weights captured at the end of specified epochs. \n",
|
| 82 |
+
" This history facilitates post-training analysis of weight adjustments.\n",
|
| 83 |
+
"\n",
|
| 84 |
+
" Methods:\n",
|
| 85 |
+
" on_epoch_end(epoch, logs=None): Overrides the base class method to capture attention weights at the end of each epoch.\n",
|
| 86 |
+
" Weights are captured based on specified criteria, e.g., every 5 epochs.\n",
|
| 87 |
+
" get_attention_weights_history(): Provides access to the accumulated history of attention weights captured during training.\n",
|
| 88 |
+
" \"\"\"\n",
|
| 89 |
+
" \n",
|
| 90 |
+
" def __init__(self, model):\n",
|
| 91 |
+
" \"\"\"\n",
|
| 92 |
+
" Initializes the callback with a specific model to monitor its attention weights during training.\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" Parameters:\n",
|
| 95 |
+
" model (tf.keras.Model): The model whose attention weights are to be monitored and captured.\n",
|
| 96 |
+
" \"\"\"\n",
|
| 97 |
+
" super().__init__()\n",
|
| 98 |
+
" self.model = model\n",
|
| 99 |
+
" self.penultimate_weights = None\n",
|
| 100 |
+
" self.attention_weights_history = []\n",
|
| 101 |
+
"\n",
|
| 102 |
+
" def on_epoch_end(self, epoch, logs=None):\n",
|
| 103 |
+
" \"\"\"\n",
|
| 104 |
+
" Called at the end of an epoch during training to capture and store attention weights if the current\n",
|
| 105 |
+
" epoch satisfies the capture criteria (e.g., every 5 epochs).\n",
|
| 106 |
+
"\n",
|
| 107 |
+
" Parameters:\n",
|
| 108 |
+
" epoch (int): The current epoch number.\n",
|
| 109 |
+
" logs (dict): Currently unused. Contains logs from the training epoch.\n",
|
| 110 |
+
" \"\"\"\n",
|
| 111 |
+
" if epoch % 5 == 0: # Perform analysis every 5 epochs\n",
|
| 112 |
+
" # Retrieve attention weights from the model\n",
|
| 113 |
+
" last_attention_weights = self.model.get_last_attention_weights()\n",
|
| 114 |
+
" if last_attention_weights is not None:\n",
|
| 115 |
+
" self.attention_weights_history.append(last_attention_weights)\n",
|
| 116 |
+
" \n",
|
| 117 |
+
" def get_attention_weights_history(self):\n",
|
| 118 |
+
" \"\"\"\n",
|
| 119 |
+
" Returns the history of attention weights captured during training.\n",
|
| 120 |
+
"\n",
|
| 121 |
+
" Returns:\n",
|
| 122 |
+
" A list of attention weights captured at specified intervals during training.\n",
|
| 123 |
+
" \"\"\"\n",
|
| 124 |
+
" return self.attention_weights_history"
|
| 125 |
+
]
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"id": "22e2e8be",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"outputs": [],
|
| 133 |
+
"source": [
|
| 134 |
+
"def setup_callbacks(learning_rate, patience, checkpoint_path, model):\n",
|
| 135 |
+
" \"\"\"\n",
|
| 136 |
+
" Sets up and returns TensorFlow callbacks for use during model training. These callbacks include early stopping,\n",
|
| 137 |
+
" learning rate scheduling, model checkpointing, and a custom callback for capturing model weights.\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" This function is tailored to support flexible training configurations, allowing for dynamic adjustment of training\n",
|
| 140 |
+
" behavior based on model performance and training progress.\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" Parameters:\n",
|
| 143 |
+
" args (argparse.Namespace): Parsed command-line arguments containing training configurations such as patience for early stopping,\n",
|
| 144 |
+
" total training epochs, and initial learning rate.\n",
|
| 145 |
+
" checkpoint_path (str): File path where model checkpoints will be saved. The best model according to validation loss is checkpointed.\n",
|
| 146 |
+
" model (tf.keras.Model): The TensorFlow model being trained. Required for initializing the `CaptureWeightsCallback`.\n",
|
| 147 |
+
" model_name (str): Name of the model being trained. This can be used to adjust callback behavior for different models.\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" Returns:\n",
|
| 150 |
+
" tuple: A tuple containing:\n",
|
| 151 |
+
" - A list of TensorFlow callbacks configured for the training session.\n",
|
| 152 |
+
" - An instance of `CaptureWeightsCallback`, which can be used post-training to access captured weights.\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" Raises:\n",
|
| 155 |
+
" Exception: If an error occurs in the setup of callbacks, an exception is logged and raised to prevent silent training failures.\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" Example:\n",
|
| 158 |
+
" >>> callbacks, capture_weights_callback = setup_callbacks(args, './model_checkpoints', model, 'my_model')\n",
|
| 159 |
+
" This example demonstrates how to invoke `setup_callbacks` to obtain configured callbacks for training, including a custom\n",
|
| 160 |
+
" weight capture callback for post-training analysis.\n",
|
| 161 |
+
" \"\"\"\n",
|
| 162 |
+
" try:\n",
|
| 163 |
+
" checkpoint_callback = ModelCheckpoint(\n",
|
| 164 |
+
" filepath=checkpoint_path,\n",
|
| 165 |
+
" monitor='val_loss', \n",
|
| 166 |
+
" verbose=1,\n",
|
| 167 |
+
" save_best_only=True,\n",
|
| 168 |
+
" save_weights_only=True,\n",
|
| 169 |
+
" )\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" early_stop_callback = EarlyStopping(\n",
|
| 172 |
+
" monitor='val_loss',\n",
|
| 173 |
+
" patience=patience,\n",
|
| 174 |
+
" verbose=1,\n",
|
| 175 |
+
" )\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" lr_schedule_callback = LearningRateScheduler(\n",
|
| 178 |
+
" lambda epoch: cosine_annealing(epoch, 5, learning_rate, 1e-6),\n",
|
| 179 |
+
" verbose=1,\n",
|
| 180 |
+
" )\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" lrdecay = ReduceLROnPlateau(monitor='val_loss', factor=0.90, patience=3, min_lr=learning_rate * 0.001, verbose=1)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" capture_weights_callback = CaptureWeightsCallback(model)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" callbacks = [checkpoint_callback, lr_schedule_callback, capture_weights_callback, early_stop_callback]\n",
|
| 187 |
+
" \n",
|
| 188 |
+
" return callbacks, capture_weights_callback\n",
|
| 189 |
+
" except Exception as e:\n",
|
| 190 |
+
" logging.error(f\"Error setting up callbacks: {e}\")\n",
|
| 191 |
+
" raise\n"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"id": "5604ad15",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"outputs": [],
|
| 200 |
+
"source": [
|
| 201 |
+
"def cosine_annealing(epoch, max_epochs, initial_lr, min_lr):\n",
|
| 202 |
+
" \"\"\"\n",
|
| 203 |
+
" Applies cosine annealing to the learning rate.\n",
|
| 204 |
+
" \n",
|
| 205 |
+
" Parameters:\n",
|
| 206 |
+
" epoch (int): Current epoch.\n",
|
| 207 |
+
" max_epochs (int): Maximum number of epochs.\n",
|
| 208 |
+
" initial_lr (float): Initial learning rate.\n",
|
| 209 |
+
" min_lr (float): Minimum learning rate.\n",
|
| 210 |
+
" \n",
|
| 211 |
+
" Returns:\n",
|
| 212 |
+
" float: Adjusted learning rate.\n",
|
| 213 |
+
" \"\"\"\n",
|
| 214 |
+
" cos_inner = (math.pi * (epoch % max_epochs)) / max_epochs\n",
|
| 215 |
+
" return min_lr + (initial_lr - min_lr) * (math.cos(cos_inner) + 1) / 2\n"
|
| 216 |
+
]
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"id": "430e2b9e",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"outputs": [],
|
| 224 |
+
"source": [
|
| 225 |
+
"class RevNorm(layers.Layer):\n",
|
| 226 |
+
" \"\"\"\n",
|
| 227 |
+
" Implements Reversible Instance Normalization (RevNorm).\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" This layer normalizes input features per instance and can reverse the normalization process. It is designed\n",
|
| 230 |
+
" to maintain the statistical properties of the input data, making it particularly useful in generative models\n",
|
| 231 |
+
" where the exact inverse operation is necessary.\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" Attributes:\n",
|
| 234 |
+
" axis (int): The axis along which to compute the mean and standard deviation for normalization.\n",
|
| 235 |
+
" eps (float): A small constant added to the standard deviation to prevent division by zero.\n",
|
| 236 |
+
" affine (bool): Whether to apply a learnable affine transformation after normalization.\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" The original implementation can be found in the Google Research repository:\n",
|
| 239 |
+
" https://github.com/google-research/google-research/blob/master/tsmixer/tsmixer_basic/models/rev_in.py\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" Example usage:\n",
|
| 242 |
+
" rev_norm = RevNorm(axis=-1, eps=1e-5, affine=True)\n",
|
| 243 |
+
" normalized_output = rev_norm(input_tensor, mode='norm')\n",
|
| 244 |
+
" denormalized_output = rev_norm(normalized_output, mode='denorm', target_slice=slice_indices)\n",
|
| 245 |
+
" \"\"\"\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" def __init__(self, axis, eps=1e-5, affine=True):\n",
|
| 248 |
+
" super().__init__()\n",
|
| 249 |
+
" self.axis = axis # Defines the dimension along which normalization is performed.\n",
|
| 250 |
+
" self.eps = eps # Small epsilon value to ensure numerical stability.\n",
|
| 251 |
+
" self.affine = affine # Determines if learnable affine parameters should be used.\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" def build(self, input_shape):\n",
|
| 254 |
+
" \"\"\"\n",
|
| 255 |
+
" Initializes the layer's weights.\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" This method creates affine transformation weights if the `affine` attribute is set to True.\n",
|
| 258 |
+
" It defines two trainable weights, `affine_weight` and `affine_bias`, which are used to scale and shift\n",
|
| 259 |
+
" the normalized data respectively.\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" Args:\n",
|
| 262 |
+
" input_shape (TensorShape): The shape of the input tensor to the layer. The last dimension is used\n",
|
| 263 |
+
" to determine the shape of the affine weights.\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" Note: This method is automatically called during the first use of the layer.\n",
|
| 266 |
+
" \"\"\"\n",
|
| 267 |
+
" if self.affine:\n",
|
| 268 |
+
" self.affine_weight = self.add_weight(\n",
|
| 269 |
+
" 'affine_weight', shape=input_shape[-1], initializer='ones'\n",
|
| 270 |
+
" )\n",
|
| 271 |
+
" self.affine_bias = self.add_weight(\n",
|
| 272 |
+
" 'affine_bias', shape=input_shape[-1], initializer='zeros'\n",
|
| 273 |
+
" )\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" def call(self, x, mode, target_slice=None):\n",
|
| 276 |
+
" \"\"\"\n",
|
| 277 |
+
" Performs normalization or denormalization on the input tensor.\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" Args:\n",
|
| 280 |
+
" x (Tensor): Input tensor to be normalized or denormalized.\n",
|
| 281 |
+
" mode (str): 'norm' for normalization and 'denorm' for denormalization.\n",
|
| 282 |
+
" target_slice (slice, optional): Target slice for denormalization.\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" Returns:\n",
|
| 285 |
+
" Tensor: The normalized or denormalized output.\n",
|
| 286 |
+
" \"\"\"\n",
|
| 287 |
+
" if mode == 'norm':\n",
|
| 288 |
+
" self._get_statistics(x)\n",
|
| 289 |
+
" x = self._normalize(x)\n",
|
| 290 |
+
" elif mode == 'denorm':\n",
|
| 291 |
+
" x = self._denormalize(x, target_slice)\n",
|
| 292 |
+
" else:\n",
|
| 293 |
+
" raise NotImplementedError\n",
|
| 294 |
+
" return x\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" def _get_statistics(self, x):\n",
|
| 297 |
+
" \"\"\"\n",
|
| 298 |
+
" Computes the mean and standard deviation of the input tensor along the specified axis.\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" The calculated mean and standard deviation are used for normalizing the input data. They are computed\n",
|
| 301 |
+
" using `tf.reduce_mean` and `tf.sqrt(tf.reduce_variance(...) + self.eps)` to ensure numerical stability.\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" Args:\n",
|
| 304 |
+
" x (Tensor): Input tensor from which the statistics are computed.\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" Updates:\n",
|
| 307 |
+
" self.mean (Tensor): The mean of the input tensor, calculated along the specified axis.\n",
|
| 308 |
+
" self.stdev (Tensor): The standard deviation of the input tensor, ensuring numerical stability by adding `self.eps`.\n",
|
| 309 |
+
" \"\"\"\n",
|
| 310 |
+
" self.mean = tf.stop_gradient(\n",
|
| 311 |
+
" tf.reduce_mean(x, axis=self.axis, keepdims=True)\n",
|
| 312 |
+
" )\n",
|
| 313 |
+
" self.stdev = tf.stop_gradient(\n",
|
| 314 |
+
" tf.sqrt(\n",
|
| 315 |
+
" tf.math.reduce_variance(x, axis=self.axis, keepdims=True) + self.eps\n",
|
| 316 |
+
" )\n",
|
| 317 |
+
" )\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" def _normalize(self, x):\n",
|
| 320 |
+
" \"\"\"\n",
|
| 321 |
+
" Normalizes the input tensor using the computed mean and standard deviation.\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" This method subtracts the mean from the input tensor and divides it by the standard deviation, effectively\n",
|
| 324 |
+
" standardizing the input to have a mean of 0 and a standard deviation of 1. If affine transformation is enabled,\n",
|
| 325 |
+
" it further applies scaling and shifting to the standardized input.\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" Args:\n",
|
| 328 |
+
" x (Tensor): Input tensor to be normalized.\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" Returns:\n",
|
| 331 |
+
" Tensor: The normalized tensor.\n",
|
| 332 |
+
" \"\"\"\n",
|
| 333 |
+
" x = x - self.mean\n",
|
| 334 |
+
" x = x / self.stdev\n",
|
| 335 |
+
" if self.affine:\n",
|
| 336 |
+
" x = x * self.affine_weight\n",
|
| 337 |
+
" x = x + self.affine_bias\n",
|
| 338 |
+
" return x\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" def _denormalize(self, x, target_slice=None):\n",
|
| 341 |
+
" \"\"\"\n",
|
| 342 |
+
" Reverses the normalization process for the given slice of the input tensor.\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" This method applies the inverse of the normalization operation. If affine transformation was applied during\n",
|
| 345 |
+
" normalization, it reverses this process first. Then, it multiplies the tensor by the standard deviation and adds\n",
|
| 346 |
+
" the mean to denormalize the data.\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" Args:\n",
|
| 349 |
+
" x (Tensor): Normalized tensor that needs to be denormalized.\n",
|
| 350 |
+
" target_slice (slice, optional): Specific slice of the tensor to denormalize. Useful when different parts\n",
|
| 351 |
+
" of the tensor require different reverse operations.\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" Returns:\n",
|
| 354 |
+
" Tensor: The denormalized tensor.\n",
|
| 355 |
+
" \"\"\"\n",
|
| 356 |
+
" if self.affine:\n",
|
| 357 |
+
" x = x - self.affine_bias[target_slice]\n",
|
| 358 |
+
" x = x / self.affine_weight[target_slice]\n",
|
| 359 |
+
" x = x * self.stdev[:, :, target_slice]\n",
|
| 360 |
+
" x = x + self.mean[:, :, target_slice]\n",
|
| 361 |
+
" return x\n"
|
| 362 |
+
]
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"id": "323930c3",
|
| 368 |
+
"metadata": {},
|
| 369 |
+
"outputs": [],
|
| 370 |
+
"source": [
|
| 371 |
+
"class SAM:\n",
|
| 372 |
+
" \"\"\"\n",
|
| 373 |
+
" Sharpness-Aware Minimization (SAM) for Enhanced Training Stability.\n",
|
| 374 |
+
" \n",
|
| 375 |
+
" SAM optimizes a model's parameters in the direction that enhances model\n",
|
| 376 |
+
" performance while simultaneously minimizing loss sharpness, aiming to improve\n",
|
| 377 |
+
" generalization. This implementation wraps around a base TensorFlow optimizer\n",
|
| 378 |
+
" to apply the SAM methodology.\n",
|
| 379 |
+
" \n",
|
| 380 |
+
" Reference:\n",
|
| 381 |
+
" \"Sharpness-Aware Minimization for Efficiently Improving Generalization\"\n",
|
| 382 |
+
" by Foret, Kleiner, Mobahi, and Neyshabur. https://openreview.net/pdf?id=6Tm1mposlrM\n",
|
| 383 |
+
"\n",
|
| 384 |
+
" The original implementation can be found at:\n",
|
| 385 |
+
" - https://github.com/davda54/sam\n",
|
| 386 |
+
" \n",
|
| 387 |
+
" Attributes:\n",
|
| 388 |
+
" base_optimizer (tf.keras.optimizers.Optimizer): The TensorFlow optimizer to wrap.\n",
|
| 389 |
+
" rho (float): The neighborhood size for sharpness-aware optimization.\n",
|
| 390 |
+
" eps (float): A small epsilon value to prevent division by zero.\n",
|
| 391 |
+
" \"\"\"\n",
|
| 392 |
+
"\n",
|
| 393 |
+
" def __init__(self, base_optimizer, rho=0.05, eps=1e-12):\n",
|
| 394 |
+
" \"\"\"\n",
|
| 395 |
+
" Initializes the SAM optimizer wrapper.\n",
|
| 396 |
+
" \n",
|
| 397 |
+
" Parameters:\n",
|
| 398 |
+
" base_optimizer (tf.keras.optimizers.Optimizer): The base optimizer.\n",
|
| 399 |
+
" rho (float): The neighborhood size for sharpness-aware optimization.\n",
|
| 400 |
+
" eps (float): A small epsilon value to prevent division by zero.\n",
|
| 401 |
+
" \"\"\"\n",
|
| 402 |
+
" assert rho >= 0.0, f\"Invalid rho, should be non-negative: {rho}\"\n",
|
| 403 |
+
" self.rho = rho\n",
|
| 404 |
+
" self.eps = eps\n",
|
| 405 |
+
" self.base_optimizer = base_optimizer\n",
|
| 406 |
+
"\n",
|
| 407 |
+
" def first_step(self, gradients, trainable_vars):\n",
|
| 408 |
+
" \"\"\"\n",
|
| 409 |
+
" Performs the first optimization step, moving weights in the direction\n",
|
| 410 |
+
" that increases loss sharpness.\n",
|
| 411 |
+
" \n",
|
| 412 |
+
" Parameters:\n",
|
| 413 |
+
" gradients (List[tf.Tensor]): Gradients of the loss with respect to the model parameters.\n",
|
| 414 |
+
" trainable_vars (List[tf.Variable]): The model's trainable variables.\n",
|
| 415 |
+
" \"\"\"\n",
|
| 416 |
+
" self.e_ws = []\n",
|
| 417 |
+
" grad_norm = tf.linalg.global_norm(gradients)\n",
|
| 418 |
+
" ew_multiplier = self.rho / (grad_norm + self.eps)\n",
|
| 419 |
+
"\n",
|
| 420 |
+
" for i in range(len(trainable_vars)):\n",
|
| 421 |
+
" e_w = tf.math.multiply(gradients[i], ew_multiplier)\n",
|
| 422 |
+
" trainable_vars[i].assign_add(e_w)\n",
|
| 423 |
+
" self.e_ws.append(e_w)\n",
|
| 424 |
+
"\n",
|
| 425 |
+
" def second_step(self, gradients, trainable_variables):\n",
|
| 426 |
+
" \"\"\"\n",
|
| 427 |
+
" Performs the second optimization step, applying the base optimizer\n",
|
| 428 |
+
" update after reverting the first step's perturbation.\n",
|
| 429 |
+
" \n",
|
| 430 |
+
" Parameters:\n",
|
| 431 |
+
" gradients (List[tf.Tensor]): Gradients of the loss with respect to the model parameters after the first step.\n",
|
| 432 |
+
" trainable_variables (List[tf.Variable]): The model's trainable variables.\n",
|
| 433 |
+
" \"\"\"\n",
|
| 434 |
+
" for i in range(len(trainable_variables)):\n",
|
| 435 |
+
" trainable_variables[i].assign_add(-self.e_ws[i]) # Revert first step\n",
|
| 436 |
+
" self.base_optimizer.apply_gradients(zip(gradients, trainable_variables))\n"
|
| 437 |
+
]
|
| 438 |
+
},
|
| 439 |
+
{
|
| 440 |
+
"cell_type": "code",
|
| 441 |
+
"execution_count": null,
|
| 442 |
+
"id": "3adf7700",
|
| 443 |
+
"metadata": {},
|
| 444 |
+
"outputs": [],
|
| 445 |
+
"source": [
|
| 446 |
+
"class SpectralNormalizedAttention(layers.MultiHeadAttention):\n",
|
| 447 |
+
" \"\"\"\n",
|
| 448 |
+
" Spectral Normalized Multi-Head Attention Layer.\n",
|
| 449 |
+
" \n",
|
| 450 |
+
" This layer extends the MultiHeadAttention layer with spectral normalization on the\n",
|
| 451 |
+
" query, key, and value weights, implementing the sigma-reparam method described in\n",
|
| 452 |
+
" \"Stabilizing Transformer Training by Preventing Attention Entropy Collapse\".\n",
|
| 453 |
+
" \n",
|
| 454 |
+
" Paper URL: https://openreview.net/forum?id=LL8gz8FHxH\n",
|
| 455 |
+
" GitHub Code: https://github.com/apple/ml-sigma-reparam\n",
|
| 456 |
+
" \n",
|
| 457 |
+
" Attributes:\n",
|
| 458 |
+
" gamma (tf.Variable): Scaling factor for the normalized weights, trainable.\n",
|
| 459 |
+
" \"\"\"\n",
|
| 460 |
+
"\n",
|
| 461 |
+
" def __init__(self, *args, **kwargs):\n",
|
| 462 |
+
" \"\"\"Initializes the SpectralNormalizedAttention layer with standard arguments for MultiHeadAttention.\"\"\"\n",
|
| 463 |
+
" super(SpectralNormalizedAttention, self).__init__(*args, **kwargs)\n",
|
| 464 |
+
" self.gamma = self.add_weight(name='gamma', shape=[], initializer='ones', trainable=True)\n",
|
| 465 |
+
"\n",
|
| 466 |
+
" def build(self, input_shape):\n",
|
| 467 |
+
" \"\"\"Builds the layer, initializing weights.\"\"\"\n",
|
| 468 |
+
" super(SpectralNormalizedAttention, self).build(input_shape)\n",
|
| 469 |
+
" # Additional initializations can be added here if necessary.\n",
|
| 470 |
+
"\n",
|
| 471 |
+
" def _normalize_weights(self, W):\n",
|
| 472 |
+
" \"\"\"\n",
|
| 473 |
+
" Normalizes the weights matrix W using its spectral norm.\n",
|
| 474 |
+
" \n",
|
| 475 |
+
" Parameters:\n",
|
| 476 |
+
" W (tf.Tensor): The weight matrix to normalize.\n",
|
| 477 |
+
" \n",
|
| 478 |
+
" Returns:\n",
|
| 479 |
+
" tf.Tensor: Spectrally normalized weights.\n",
|
| 480 |
+
" \"\"\"\n",
|
| 481 |
+
" singular_values = tf.linalg.svd(W, compute_uv=False)\n",
|
| 482 |
+
" spectral_norm = tf.reduce_max(singular_values)\n",
|
| 483 |
+
" return W / spectral_norm\n",
|
| 484 |
+
"\n",
|
| 485 |
+
" def call(self, query, value, key=None, attention_mask=None, return_attention_scores=False):\n",
|
| 486 |
+
" \"\"\"\n",
|
| 487 |
+
" Calls the SpectralNormalizedAttention layer. Normalizes the query, key, and value weights\n",
|
| 488 |
+
" before calling the parent MultiHeadAttention layer.\n",
|
| 489 |
+
" \n",
|
| 490 |
+
" Parameters:\n",
|
| 491 |
+
" query (tf.Tensor): Query tensor.\n",
|
| 492 |
+
" value (tf.Tensor): Value tensor.\n",
|
| 493 |
+
" key (tf.Tensor): Key tensor. Defaults to None, in which case the query is used as the key.\n",
|
| 494 |
+
" attention_mask (tf.Tensor): Optional tensor to mask out certain positions from attending to others.\n",
|
| 495 |
+
" return_attention_scores (bool): Flag to return attention scores along with output.\n",
|
| 496 |
+
" \n",
|
| 497 |
+
" Returns:\n",
|
| 498 |
+
" A tuple of (output tensor, attention scores) if return_attention_scores is True, otherwise just the output tensor.\n",
|
| 499 |
+
" \"\"\"\n",
|
| 500 |
+
" key = query if key is None else key\n",
|
| 501 |
+
" query = self._normalize_weights(query) * self.gamma\n",
|
| 502 |
+
" key = self._normalize_weights(key) * self.gamma\n",
|
| 503 |
+
" value = self._normalize_weights(value) * self.gamma\n",
|
| 504 |
+
"\n",
|
| 505 |
+
" return super(SpectralNormalizedAttention, self).call(query, value, key, attention_mask, return_attention_scores)\n",
|
| 506 |
+
"\n"
|
| 507 |
+
]
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"cell_type": "code",
|
| 511 |
+
"execution_count": null,
|
| 512 |
+
"id": "663d4c7e",
|
| 513 |
+
"metadata": {},
|
| 514 |
+
"outputs": [],
|
| 515 |
+
"source": [
|
| 516 |
+
"class BaseModel(tf.keras.Model):\n",
|
| 517 |
+
" \"\"\"\n",
|
| 518 |
+
" A base model class that integrates various enhancements including \n",
|
| 519 |
+
" Reversible Instance Normalization and Channel-Wise Attention, and optionally,\n",
|
| 520 |
+
" spectral normalization and SAM optimization. To use SAMformer, enable use_sam,\n",
|
| 521 |
+
" use_attention, use_revin and trainable.\n",
|
| 522 |
+
" \n",
|
| 523 |
+
" Attributes:\n",
|
| 524 |
+
" pred_len (int): The length of the output predictions.\n",
|
| 525 |
+
" num_heads (int): The number of heads in the multi-head attention mechanism. \n",
|
| 526 |
+
" d_model (int): The dimensionality of the embedding vectors.\n",
|
| 527 |
+
" use_sam (bool): If True, applies Sharpness-Aware Minimization (SAM) optimization technique during training, \n",
|
| 528 |
+
" aiming to improve model generalization by considering the loss landscape's sharpness.\n",
|
| 529 |
+
" use_attention (bool): If True, enables the multi-head attention mechanism in the model. If False, the model is\n",
|
| 530 |
+
" equivalent to a simple linear layer.\n",
|
| 531 |
+
" use_revin (bool): If True, applies Reversible Instance Normalization (RevIN) to the model.\n",
|
| 532 |
+
" trainable (bool): Specifies if the model's weights should be updated or frozen during training. Useful to \n",
|
| 533 |
+
" highlight some attention layer issues in Time Series Forecasting.\n",
|
| 534 |
+
" rho (float): The neighborhood size parameter for SAM optimization. It determines the radius within which SAM \n",
|
| 535 |
+
" seeks to minimize the sharpness of the loss landscape.\n",
|
| 536 |
+
" spec (bool): If True, applies spectral normalization (sigma-reparam) to the attention mechanism, aiming to\n",
|
| 537 |
+
" stabilize the training by constraining the spectral norm of the weight matrices.\n",
|
| 538 |
+
" \n",
|
| 539 |
+
" Methods:\n",
|
| 540 |
+
" call(inputs, training=False): Defines the computation from inputs to outputs, optionally applying SAM, \n",
|
| 541 |
+
" spectral normalization, and reversible instance normalization based on the \n",
|
| 542 |
+
" configuration.\n",
|
| 543 |
+
" _apply_attention(x): Applies the attention mechanism to the input tensor, capturing the inter-dependencies \n",
|
| 544 |
+
" within the data thanks to the Channel-Wise Attention mechanism.\n",
|
| 545 |
+
" get_last_attention_weights(): Retrieves the attention weights from the last but one batch, useful for \n",
|
| 546 |
+
" analysis and debugging purposes.\n",
|
| 547 |
+
" train_step(data): Custom training logic, including the application of SAM's two-step optimization process, \n",
|
| 548 |
+
" to improve model generalization and performance stability.\n",
|
| 549 |
+
"\n",
|
| 550 |
+
" \"\"\"\n",
|
| 551 |
+
"\n",
|
| 552 |
+
" def __init__(self, pred_len, num_heads=1, d_model=16, use_sam=None, \n",
|
| 553 |
+
" use_attention=None, use_revin=None, \n",
|
| 554 |
+
" trainable=None, rho=None, spec=None):\n",
|
| 555 |
+
" super(BaseModel, self).__init__()\n",
|
| 556 |
+
" self.pred_len = pred_len\n",
|
| 557 |
+
" self.num_heads = num_heads\n",
|
| 558 |
+
" self.d_model = d_model\n",
|
| 559 |
+
" self.use_sam = use_sam\n",
|
| 560 |
+
" self.use_attention = use_attention\n",
|
| 561 |
+
" self.use_revin = use_revin\n",
|
| 562 |
+
" self.rho = rho if use_sam and trainable else 0.0\n",
|
| 563 |
+
" self.spec = spec\n",
|
| 564 |
+
"\n",
|
| 565 |
+
" # Define model layers\n",
|
| 566 |
+
" self.rev_norm = RevNorm(axis=-2)\n",
|
| 567 |
+
" self.attention_layer = layers.MultiHeadAttention(num_heads=num_heads, key_dim=d_model)\n",
|
| 568 |
+
" self.dense = layers.Dense(pred_len)\n",
|
| 569 |
+
" self.all_attention_weights = collections.deque(maxlen=2)\n",
|
| 570 |
+
" self.all_dense_weights = collections.deque(maxlen=2)\n",
|
| 571 |
+
"\n",
|
| 572 |
+
" if self.spec:\n",
|
| 573 |
+
" self.spec_layer = SpectralNormalizedAttention(num_heads=num_heads, key_dim=d_model)\n",
|
| 574 |
+
"\n",
|
| 575 |
+
" #Define trainability of attention layer\n",
|
| 576 |
+
" self.attention_layer.trainable = trainable\n",
|
| 577 |
+
"\n",
|
| 578 |
+
" def call(self, inputs, training=False):\n",
|
| 579 |
+
" \"\"\"\n",
|
| 580 |
+
" The forward pass for the model.\n",
|
| 581 |
+
" \n",
|
| 582 |
+
" Parameters:\n",
|
| 583 |
+
" inputs (Tensor): Input tensor.\n",
|
| 584 |
+
" training (bool): Whether the call is for training.\n",
|
| 585 |
+
" \n",
|
| 586 |
+
" Returns:\n",
|
| 587 |
+
" Tensor: The output of the model.\n",
|
| 588 |
+
" \"\"\"\n",
|
| 589 |
+
"\n",
|
| 590 |
+
" x = inputs\n",
|
| 591 |
+
" if self.use_revin:\n",
|
| 592 |
+
" x = self.rev_norm(x, mode='norm')\n",
|
| 593 |
+
" x = tf.transpose(x, perm=[0, 2, 1])\n",
|
| 594 |
+
"\n",
|
| 595 |
+
" if self.use_attention:\n",
|
| 596 |
+
" attention_output = self._apply_attention(x)\n",
|
| 597 |
+
" x = layers.Add()([x, attention_output])\n",
|
| 598 |
+
"\n",
|
| 599 |
+
" x = self.dense(x)\n",
|
| 600 |
+
" outputs = tf.transpose(x, perm=[0, 2, 1])\n",
|
| 601 |
+
"\n",
|
| 602 |
+
" if self.use_revin:\n",
|
| 603 |
+
" outputs = self.rev_norm(outputs, mode='denorm')\n",
|
| 604 |
+
"\n",
|
| 605 |
+
" return outputs\n",
|
| 606 |
+
"\n",
|
| 607 |
+
" def _apply_attention(self, x):\n",
|
| 608 |
+
" \"\"\"\n",
|
| 609 |
+
" Applies the attention mechanism to the input tensor.\n",
|
| 610 |
+
" \n",
|
| 611 |
+
" Parameters:\n",
|
| 612 |
+
" x (Tensor): The input tensor.\n",
|
| 613 |
+
" training (bool): Whether the call is for training.\n",
|
| 614 |
+
" \n",
|
| 615 |
+
" Returns:\n",
|
| 616 |
+
" Tensor: The output tensor after applying attention.\n",
|
| 617 |
+
" \"\"\"\n",
|
| 618 |
+
" if self.spec:\n",
|
| 619 |
+
" attention_output, weights = self.spec_layer(x, x, return_attention_scores=True)\n",
|
| 620 |
+
" else:\n",
|
| 621 |
+
" attention_output, weights = self.attention_layer(x, x, return_attention_scores=True)\n",
|
| 622 |
+
" \n",
|
| 623 |
+
" self.all_attention_weights.append(weights.numpy())\n",
|
| 624 |
+
" return attention_output\n",
|
| 625 |
+
"\n",
|
| 626 |
+
" def get_last_attention_weights(self):\n",
|
| 627 |
+
" \"\"\"Returns the attention weights from the last but one batch.\"\"\"\n",
|
| 628 |
+
" if len(self.all_attention_weights) > 1:\n",
|
| 629 |
+
" return self.all_attention_weights[-2]\n",
|
| 630 |
+
" return None\n",
|
| 631 |
+
"\n",
|
| 632 |
+
" def train_step(self, data):\n",
|
| 633 |
+
" sam_optimizer = SAM(self.optimizer, rho=self.rho, eps=1e-12) \n",
|
| 634 |
+
"\n",
|
| 635 |
+
" # Unpack the data.\n",
|
| 636 |
+
" x, y = data\n",
|
| 637 |
+
"\n",
|
| 638 |
+
" with tf.GradientTape() as tape:\n",
|
| 639 |
+
" y_pred = self(x, training=True) # Forward pass\n",
|
| 640 |
+
" loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)\n",
|
| 641 |
+
"\n",
|
| 642 |
+
" # Compute gradients\n",
|
| 643 |
+
" gradients = tape.gradient(loss, self.trainable_variables)\n",
|
| 644 |
+
"\n",
|
| 645 |
+
" # Apply SAM's first step\n",
|
| 646 |
+
" sam_optimizer.first_step(gradients, self.trainable_variables)\n",
|
| 647 |
+
"\n",
|
| 648 |
+
" with tf.GradientTape() as tape:\n",
|
| 649 |
+
" y_pred = self(x, training=True) # Forward pass again\n",
|
| 650 |
+
" loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)\n",
|
| 651 |
+
"\n",
|
| 652 |
+
" # Compute gradients again\n",
|
| 653 |
+
" gradients = tape.gradient(loss, self.trainable_variables)\n",
|
| 654 |
+
"\n",
|
| 655 |
+
" # Apply SAM's second step\n",
|
| 656 |
+
" sam_optimizer.second_step(gradients, self.trainable_variables)\n",
|
| 657 |
+
"\n",
|
| 658 |
+
" # Update metrics\n",
|
| 659 |
+
" self.compiled_metrics.update_state(y, y_pred)\n",
|
| 660 |
+
"\n",
|
| 661 |
+
" # Return a dict mapping metric names to current value\n",
|
| 662 |
+
" return {m.name: m.result() for m in self.metrics}\n",
|
| 663 |
+
" "
|
| 664 |
+
]
|
| 665 |
+
},
|
| 666 |
+
{
|
| 667 |
+
"cell_type": "code",
|
| 668 |
+
"execution_count": null,
|
| 669 |
+
"id": "cdc39fe9",
|
| 670 |
+
"metadata": {},
|
| 671 |
+
"outputs": [],
|
| 672 |
+
"source": [
|
| 673 |
+
"class TSFDataLoader:\n",
|
| 674 |
+
" \"\"\"Generate data loader from raw data.\"\"\"\n",
|
| 675 |
+
"\n",
|
| 676 |
+
" def __init__(\n",
|
| 677 |
+
" self, data, batch_size, seq_len, pred_len, feature_type, target='OT'\n",
|
| 678 |
+
" ):\n",
|
| 679 |
+
" self.data = data\n",
|
| 680 |
+
" self.batch_size = batch_size\n",
|
| 681 |
+
" self.seq_len = seq_len\n",
|
| 682 |
+
" self.pred_len = pred_len\n",
|
| 683 |
+
" self.feature_type = feature_type\n",
|
| 684 |
+
" self.target = target\n",
|
| 685 |
+
" self.target_slice = slice(0, None)\n",
|
| 686 |
+
"\n",
|
| 687 |
+
" self._read_data()\n",
|
| 688 |
+
"\n",
|
| 689 |
+
" def _read_data(self):\n",
|
| 690 |
+
" \"\"\"Load raw data and split datasets.\"\"\"\n",
|
| 691 |
+
"\n",
|
| 692 |
+
" # copy data from cloud storage if not exists\n",
|
| 693 |
+
" if not os.path.isdir(LOCAL_CACHE_DIR):\n",
|
| 694 |
+
" os.mkdir(LOCAL_CACHE_DIR)\n",
|
| 695 |
+
"\n",
|
| 696 |
+
" file_name = self.data + '.csv'\n",
|
| 697 |
+
" cache_filepath = os.path.join(LOCAL_CACHE_DIR, file_name)\n",
|
| 698 |
+
" if not os.path.isfile(cache_filepath):\n",
|
| 699 |
+
" tf.io.gfile.copy(\n",
|
| 700 |
+
" os.path.join(DATA_DIR, file_name), cache_filepath, overwrite=True\n",
|
| 701 |
+
" )\n",
|
| 702 |
+
" df_raw = pd.read_csv(cache_filepath)\n",
|
| 703 |
+
"\n",
|
| 704 |
+
" \n",
|
| 705 |
+
" \n",
|
| 706 |
+
" # S: univariate-univariate, M: multivariate-multivariate, MS:\n",
|
| 707 |
+
" # multivariate-univariate\n",
|
| 708 |
+
" df = df_raw.set_index('date')\n",
|
| 709 |
+
" if self.feature_type == 'S':\n",
|
| 710 |
+
" df = df[[self.target]]\n",
|
| 711 |
+
" elif self.feature_type == 'MS':\n",
|
| 712 |
+
" target_idx = df.columns.get_loc(self.target)\n",
|
| 713 |
+
" self.target_slice = slice(target_idx, target_idx + 1)\n",
|
| 714 |
+
"\n",
|
| 715 |
+
" # split train/valid/test\n",
|
| 716 |
+
" n = len(df)\n",
|
| 717 |
+
" if self.data.startswith('ETTm'):\n",
|
| 718 |
+
" train_end = 12 * 30 * 24 * 4\n",
|
| 719 |
+
" val_end = train_end + 4 * 30 * 24 * 4\n",
|
| 720 |
+
" test_end = val_end + 4 * 30 * 24 * 4\n",
|
| 721 |
+
" elif self.data.startswith('ETTh'):\n",
|
| 722 |
+
" train_end = 12 * 30 * 24\n",
|
| 723 |
+
" val_end = train_end + 4 * 30 * 24\n",
|
| 724 |
+
" test_end = val_end + 4 * 30 * 24\n",
|
| 725 |
+
" else:\n",
|
| 726 |
+
" train_end = int(n * 0.7)\n",
|
| 727 |
+
" val_end = n - int(n * 0.2)\n",
|
| 728 |
+
" test_end = n\n",
|
| 729 |
+
" \n",
|
| 730 |
+
" train_df = df[:train_end]\n",
|
| 731 |
+
" val_df = df[train_end - self.seq_len : val_end]\n",
|
| 732 |
+
" test_df = df[val_end - self.seq_len : test_end]\n",
|
| 733 |
+
"\n",
|
| 734 |
+
" # standardize by training set\n",
|
| 735 |
+
" self.scaler = StandardScaler()\n",
|
| 736 |
+
" self.scaler1 = StandardScaler()\n",
|
| 737 |
+
" \n",
|
| 738 |
+
" self.scaler.fit(train_df.values)\n",
|
| 739 |
+
" # self.scaler1.fit(df.iloc[:train_end, :-5].values)\n",
|
| 740 |
+
"\n",
|
| 741 |
+
" def scale_df(df, scaler):\n",
|
| 742 |
+
" data = scaler.transform(df.values)\n",
|
| 743 |
+
" # return pd.DataFrame(df, index=df.index, columns=df.columns)\n",
|
| 744 |
+
" return pd.DataFrame(data, index=df.index, columns=df.columns)\n",
|
| 745 |
+
"\n",
|
| 746 |
+
" self.train_df = scale_df(train_df, self.scaler)\n",
|
| 747 |
+
" self.val_df = scale_df(val_df, self.scaler)\n",
|
| 748 |
+
" self.test_df = scale_df(test_df, self.scaler)\n",
|
| 749 |
+
" self.n_feature = self.train_df.shape[-1]\n",
|
| 750 |
+
"\n",
|
| 751 |
+
" def _split_window(self, data):\n",
|
| 752 |
+
" inputs = data[:, : self.seq_len, :]\n",
|
| 753 |
+
" labels = data[:, self.seq_len :, self.target_slice]\n",
|
| 754 |
+
" # Slicing doesn't preserve static shape information, so set the shapes\n",
|
| 755 |
+
" # manually. This way the `tf.data.Datasets` are easier to inspect.\n",
|
| 756 |
+
" inputs.set_shape([None, self.seq_len, None])\n",
|
| 757 |
+
" labels.set_shape([None, self.pred_len, self.n_feature])\n",
|
| 758 |
+
" return inputs, labels\n",
|
| 759 |
+
"\n",
|
| 760 |
+
" def _make_dataset(self, data, shuffle=True):\n",
|
| 761 |
+
" data = np.array(data, dtype=np.float32)\n",
|
| 762 |
+
" ds = tf.keras.utils.timeseries_dataset_from_array(\n",
|
| 763 |
+
" data=data,\n",
|
| 764 |
+
" targets=None,\n",
|
| 765 |
+
" sequence_length=(self.seq_len + self.pred_len),\n",
|
| 766 |
+
" sequence_stride=1,\n",
|
| 767 |
+
" shuffle=False,\n",
|
| 768 |
+
" batch_size=self.batch_size,\n",
|
| 769 |
+
" )\n",
|
| 770 |
+
" ds = ds.map(self._split_window)\n",
|
| 771 |
+
" return ds\n",
|
| 772 |
+
"\n",
|
| 773 |
+
" def _make_dataset_test(self, data, shuffle=True):\n",
|
| 774 |
+
" data = np.array(data, dtype=np.float32)\n",
|
| 775 |
+
" ds = tf.keras.utils.timeseries_dataset_from_array(\n",
|
| 776 |
+
" data=data,\n",
|
| 777 |
+
" targets=None,\n",
|
| 778 |
+
" sequence_length=(self.seq_len + self.pred_len),\n",
|
| 779 |
+
" sequence_stride=1,\n",
|
| 780 |
+
" shuffle=False,\n",
|
| 781 |
+
" batch_size=1)\n",
|
| 782 |
+
" ds = ds.map(self._split_window)\n",
|
| 783 |
+
" return ds\n",
|
| 784 |
+
"\n",
|
| 785 |
+
"\n",
|
| 786 |
+
" def inverse_transform(self, data):\n",
|
| 787 |
+
" return self.scaler.inverse_transform(data)\n",
|
| 788 |
+
"\n",
|
| 789 |
+
" def get_train(self, shuffle=True):\n",
|
| 790 |
+
" return self._make_dataset(self.train_df, shuffle=shuffle)\n",
|
| 791 |
+
"\n",
|
| 792 |
+
" def get_val(self):\n",
|
| 793 |
+
" return self._make_dataset(self.val_df, shuffle=False)\n",
|
| 794 |
+
"\n",
|
| 795 |
+
" def get_test(self):\n",
|
| 796 |
+
" return self._make_dataset(self.test_df, shuffle=False)\n",
|
| 797 |
+
"\n",
|
| 798 |
+
"\n",
|
| 799 |
+
"def load_data(name, batch_size, seq_len, pred_len, feature_type, target):\n",
|
| 800 |
+
" \"\"\"\n",
|
| 801 |
+
" Loads or generates training, validation, and testing datasets based on the specified configurations.\n",
|
| 802 |
+
"\n",
|
| 803 |
+
" Parameters:\n",
|
| 804 |
+
" args (argparse.Namespace): Command line arguments specifying dataset configurations.\n",
|
| 805 |
+
"\n",
|
| 806 |
+
" Returns:\n",
|
| 807 |
+
" tuple: Training, validation, and test datasets as tf.data.Dataset objects.\n",
|
| 808 |
+
" \"\"\"\n",
|
| 809 |
+
" data_loader = TSFDataLoader(name, batch_size, seq_len, pred_len, feature_type, target)\n",
|
| 810 |
+
" train_data, val_data, test_data = data_loader.get_train(), data_loader.get_val(), data_loader.get_test()\n",
|
| 811 |
+
"\n",
|
| 812 |
+
" return train_data, val_data, test_data, data_loader.n_feature"
|
| 813 |
+
]
|
| 814 |
+
},
|
| 815 |
+
{
|
| 816 |
+
"cell_type": "code",
|
| 817 |
+
"execution_count": null,
|
| 818 |
+
"id": "fe7abdc1",
|
| 819 |
+
"metadata": {},
|
| 820 |
+
"outputs": [],
|
| 821 |
+
"source": [
|
| 822 |
+
"train_data, val_data, test_data, n_features = load_data(name, batch_size, seq_len, pred_len, feature_type, target)\n",
|
| 823 |
+
"new_cols = ['mse', 'mae', \"seq_len\", \"learning_rate\", \"batch_size\", \"num_heads\", \n",
|
| 824 |
+
" \"d_model\", \"minimization_neighbourhood\"]\n",
|
| 825 |
+
"\n",
|
| 826 |
+
"df = pd.DataFrame(columns=new_cols)\n",
|
| 827 |
+
"\n",
|
| 828 |
+
"numEvalSamples = 1\n",
|
| 829 |
+
"seeds = [2022]"
|
| 830 |
+
]
|
| 831 |
+
},
|
| 832 |
+
{
|
| 833 |
+
"cell_type": "code",
|
| 834 |
+
"execution_count": null,
|
| 835 |
+
"id": "29470575",
|
| 836 |
+
"metadata": {},
|
| 837 |
+
"outputs": [],
|
| 838 |
+
"source": [
|
| 839 |
+
"for sd in range(numEvalSamples):\n",
|
| 840 |
+
" tf.keras.backend.clear_session() \n",
|
| 841 |
+
"\n",
|
| 842 |
+
" tf.keras.utils.set_random_seed(seeds[sd])\n",
|
| 843 |
+
" \n",
|
| 844 |
+
" print(f\"..............iteration{sd}.................\")\n",
|
| 845 |
+
" print()\n",
|
| 846 |
+
" model = BaseModel(pred_len, num_heads=num_heads, d_model=d_model, use_sam=True, use_attention=True, use_revin=True, trainable=True, rho=rho, \n",
|
| 847 |
+
" spec=False)\n",
|
| 848 |
+
" optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)\n",
|
| 849 |
+
" model.compile(optimizer=optimizer, loss='mae', metrics=['mse', 'mae'], run_eagerly=True)\n",
|
| 850 |
+
" \n",
|
| 851 |
+
" callbacks, capture_weights_callback = setup_callbacks(learning_rate, patience, checkpoint_path, model)\n",
|
| 852 |
+
" \n",
|
| 853 |
+
" history = model.fit(\n",
|
| 854 |
+
" train_data,\n",
|
| 855 |
+
" epochs=300,\n",
|
| 856 |
+
" validation_data=val_data,\n",
|
| 857 |
+
" callbacks=callbacks)\n",
|
| 858 |
+
" \n",
|
| 859 |
+
" model.load_weights(checkpoint_path)\n",
|
| 860 |
+
" df.loc[sd, :] = model.evaluate(test_data)[-2:] + [ seq_len, learning_rate, batch_size, num_heads, \n",
|
| 861 |
+
" d_model, rho]\n",
|
| 862 |
+
" df.to_csv(name_df, header=True, index=False)\n",
|
| 863 |
+
"\n",
|
| 864 |
+
" del model\n",
|
| 865 |
+
" tf.keras.backend.clear_session()\n",
|
| 866 |
+
" # garbage collector\n",
|
| 867 |
+
" gc.collect()\n",
|
| 868 |
+
"\n",
|
| 869 |
+
" # remove_dir(checkpoint_path)\n",
|
| 870 |
+
"\n",
|
| 871 |
+
"print(\"................completed Successfully......................\")\n"
|
| 872 |
+
]
|
| 873 |
+
},
|
| 874 |
+
{
|
| 875 |
+
"cell_type": "code",
|
| 876 |
+
"execution_count": null,
|
| 877 |
+
"id": "852cd02e",
|
| 878 |
+
"metadata": {},
|
| 879 |
+
"outputs": [],
|
| 880 |
+
"source": []
|
| 881 |
+
}
|
| 882 |
+
],
|
| 883 |
+
"metadata": {
|
| 884 |
+
"kernelspec": {
|
| 885 |
+
"display_name": "Python 3 (ipykernel)",
|
| 886 |
+
"language": "python",
|
| 887 |
+
"name": "python3"
|
| 888 |
+
},
|
| 889 |
+
"language_info": {
|
| 890 |
+
"codemirror_mode": {
|
| 891 |
+
"name": "ipython",
|
| 892 |
+
"version": 3
|
| 893 |
+
},
|
| 894 |
+
"file_extension": ".py",
|
| 895 |
+
"mimetype": "text/x-python",
|
| 896 |
+
"name": "python",
|
| 897 |
+
"nbconvert_exporter": "python",
|
| 898 |
+
"pygments_lexer": "ipython3",
|
| 899 |
+
"version": "3.11.5"
|
| 900 |
+
}
|
| 901 |
+
},
|
| 902 |
+
"nbformat": 4,
|
| 903 |
+
"nbformat_minor": 5
|
| 904 |
+
}
|