"**Set-up instructions:** this notebook give a tutorial on the learning task supported by `TimesNet`.\n",
"\n",
"`TimesNet` can support basically 5 tasks, which are respectively long-term forecast, short-term forecast, imputation, anomaly detection, classification."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Install Python 3.8. For convenience, execute the following command."
" The core idea of `TimesNet` lies in the construction of `TimesBlock`, which generally gets the base frequencies by implementing FFT on the data, and then reshapes the times series to 2D variation respectively from the main base frequencies, followed by a 2D convolution whose outputs are reshaped back and added with weight to form the final output.\n",
"So far we've got `TimesBlock`, which is excel at retrieving intra- and inter- period temporal information. We become capable of building a `TimesNet`. `TimesNet` is proficient in multitasks including short- and long-term forecasting, imputation, classification, and anomaly detection.\n",
"The basic idea of forecasting is to lengthen the known sequence to (seq_len+pred_len), which is the total length after forecasting. Then by several TimesBlock layers together with layer normalization, some underlying intra- and inter- period information is represented. With these information, we can project it to the output space. Whereafter by denorm ( if Non-stationary Transformer) we get the final output."
" # De-Normalization from Non-stationary Transformer\n",
" dec_out = dec_out * \\\n",
" (stdev[:, 0, :].unsqueeze(1).repeat(\n",
" 1, self.pred_len + self.seq_len, 1)) #lengthen the stdev to fit the dec_out\n",
" dec_out = dec_out + \\\n",
" (means[:, 0, :].unsqueeze(1).repeat(\n",
" 1, self.pred_len + self.seq_len, 1)) #lengthen the mean to fit the dec_out\n",
" return dec_out"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 4.2 Imputation\n",
"\n",
"Imputation is a task aiming at completing some missing value in the time series, so in some degree it's similar to forecast. We can still use the similar step to cope with it."
"By now we've successfully build up `TimesNet`. We are now facing the problem how to train and test this neural network. The action of training, validating as well as testing is implemented at __*exp*__ part, in which codes for different tasks are gathered. These experiments are not only for `TimesNet` training, but also feasible for any other time series representation model. But here, we simply use `TimesNet` to analyse.\n",
"`TimesNet` is a state-of-art in multiple tasks, while here we would only introduce its training for long-term forecast task, since the backbone of the training process for other tasks is similar to this one. Again, test and validation code can be easily understood once you've aware how the training process works. So first of all, we are going to focus on the training of `TimesNet` on task long-term forecasting.\n",
"\n",
"We will discuss many aspects, including the training process, training loss etc."
"The following codes represents the process of training model for long-term forecasting task. We'll have a detailed look at it. To make it brief, the training part can be briefly divided into several parts, including Data Preparation, Creating Save Path, Initialization, Optimizer and Loss Function Selection, Using Mixed Precision Training, Training Loop, Validation and Early Stopping, Learning Rate Adjustment, Loading the Best Model.\n",
"For more details, please see the code below. 'train' process is defined in the experiment <font color=orange>__class Exp_Long_Term_Forecast__</font>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def train(self, setting): #setting is the args for this model training\n",
"<font color=purple>__EarlyStopping__</font> is typically a custom class or function that monitors the performance of a model during training, usually by tracking a certain metric (commonly validation loss or accuracy).It's a common technique used in deep learning to prevent overfitting during the training.\n",
"\n",
"Let's see the code below(original code is in `tools.py`)."
"The optimizer and criterion are defined in <font color=orange>__class Exp_Long_Term_Forecast__</font> and called in the training process by function `self._select_optimizer()` and `self._select_criterion()`. Here, for long-term forecasting task, we simply adopt Adam optimizer and MSELoss to meature the loss between real data and predicted ones."
"AMP is a technique used in deep learning to improve training speed and reduce memory usage. AMP achieves this by mixing calculations in half-precision (16-bit floating-point) and single-precision (32-bit floating-point).\n",
"\n",
"Let's have a closer look on this snippet:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#in forward process:\n",
"with torch.cuda.amp.autocast():\n",
"\n",
"...\n",
"\n",
"#in BP process:\n",
"if self.args.use_amp:\n",
" scaler.scale(loss).backward()\n",
" scaler.step(model_optim)\n",
" scaler.update()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"` with torch.cuda.amp.autocast():` : The purpose of using torch.cuda.amp.autocast() is to take advantage of the speed and memory efficiency benefits of mixed-precision training while maintaining numerical stability. Some deep learning models can benefit significantly from this technique, especially on modern GPUs with hardware support for half-precision arithmetic. It allows you to perform certain calculations more quickly while still ensuring that critical calculations (e.g., gradient updates) are performed with sufficient precision to avoid loss of accuracy.\n",
"\n",
"`scaler.scale(loss).backward()`: If AMP is enabled, it uses a scaler object created with torch.cuda.amp.GradScaler() to automatically scale the loss and perform backward propagation. This is a crucial part of AMP, ensuring numerical stability. Before backpropagation, the loss is scaled to an appropriate range to prevent gradients from diverging too quickly or causing numerical instability.\n",
"\n",
"`scaler.step(model_optim)`: Next, the scaler calls the step method, which applies the scaled gradients to the model's optimizer (model_optim). This is used to update the model's weights to minimize the loss function.\n",
"\n",
"`scaler.update()`: Finally, the scaler calls the update method, which updates the scaling factor to ensure correct scaling of the loss for the next iteration. This step helps dynamically adjust the scaling of gradients to adapt to different training scenarios."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 5.5 Learning Rate Adjustment\n",
"\n",
"While the optimizer are responsible for adapting the learning rate with epochs, we would still like to do some adjustment on it manually, as indicated in the function `adjust_learning_rate(model_optim, epoch + 1, self.args)`, whose codes are shown below(original code is in `tools.py`): "
" #2nd type: only update in epochs that are written in Dict lr_adjust\n",
" if epoch in lr_adjust.keys():\n",
" lr = lr_adjust[epoch]\n",
" \n",
" # change the learning rate for different parameter groups within the optimizer\n",
" for param_group in optimizer.param_groups:\n",
" param_group['lr'] = lr\n",
" print('Updating learning rate to {}'.format(lr))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 6. Validation and Testing\n",
"\n",
"During training, the model continuously adjusts its weights and parameters to minimize training error. However, this may not reflect the model's performance on unseen data. Validation allows us to periodically assess the model's performance on data that is different from the training data, providing insights into the model's generalization ability.\n",
"\n",
"By comparing performance on the validation set, we can identify whether the model is overfitting. Overfitting occurs when a model performs well on training data but poorly on unseen data. Monitoring performance on the validation set helps detect overfitting early and take measures to prevent it, such as early stopping or adjusting hyperparameters.\n",
"\n",
"Here, we still take long-term forecasting as an example, similar to train process:"
"Testing is similar to validation, but it's purpose is to examine how well the model behaves, so it's common to add some visualization with __matplotlib.pyplot__. "
"In the process of training, we simply take the dataloader for granted, by the function `self._get_data(flag='train')`. So how does this line work? Have a look at the definition(in <font color=orange>__class Exp_Long_Term_Forecast__</font>):"
" target=args.target, #target feature in S or MS task\n",
" timeenc=timeenc,\n",
" freq=freq,\n",
" seasonal_patterns=args.seasonal_patterns\n",
" )\n",
" print(flag, len(data_set))\n",
" data_loader = DataLoader(\n",
" data_set,\n",
" batch_size=batch_size,\n",
" shuffle=shuffle_flag,\n",
" num_workers=args.num_workers,\n",
" drop_last=drop_last)\n",
" return data_set, data_loader\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From above, it's easy to find that data_provider is responsible for collate the dataset into batches according to different tasks and running mode. It passes the parameters to dataloader(`Data`) to instruct it how to manage a data file into pieces of usable data. Then it also generates the final dara_loader by passing the built-up dataset and some other params to the standard class Dataloader. After that, a dataset that fits the need of the model and a enumerable dataloader are generated. \n",
"\n",
"So how to organize the data file into pieces of data that fits the model? Let's see `data_loader.py`! There are many dataloaders in it, and of course you can write your own dataloader, but here we'll only focus on <font color=orange>__class Dataset_ETT_hour(Dataset)__</font> as an example."
"`__init__()` is the constructor used to initialize various parameters and attributes of the dataset. It takes a series of arguments, including the path to the data file, the dataset's flag (e.g., train, validate, test), dataset size, feature type, target variable, whether to scale the data, time encoding, time frequency, and more. These parameters are used to configure how the dataset is loaded and processed."
" when entering this branch, we choose arg.embed as timeF meaning we want to \n",
" encode the temporal info. 'freq' should be the smallest time step, and has \n",
" options:[s:secondly, t:minutely, h:hourly, d:daily, b:business days, w:weekly, m:monthly], you can also use more detailed freq like 15min or 3h')\n",
" So you should check the timestep of your data and set 'freq' arg. \n",
" After the time_features encoding, each date info format will be encoded into \n",
" # data_x and data_y are same copy of a certain part of data\n",
" self.data_x = data[border1:border2]\n",
" self.data_y = data[border1:border2]\n",
" self.data_stamp = data_stamp"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`__read_data__()` splits the dataset into 3 parts, selects the needed columns and manages time stamp info. It gives out the well-managed data array for later use. Next, we have to finish the overload of <font color=orange>__class Dataset__</font>, see `__getitem__(self, index)` and `__len__(self)`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def __getitem__(self, index):\n",
" #given an index, calculate the positions after this index to truncate the dataset\n",
"You can also add an inverse_transform for scaler if needed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def inverse_transform(self, data):\n",
" return self.scaler.inverse_transform(data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By now, we have finished constructing the dataset and dataloader. If you want to construct your own data and run it on the net, you can find proper data and try to accomplish the functions listed above. Here are some widely used datasets in times series analysis.\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 8. Running the Experiment and Visualizing Result\n",
"\n",
"After managing the data, model well, we need to write a shell script for the experiment. In the script, we need to run `run.py` with several arguments, which is part of the configuration. Here, let's see `TimesNet` on task long-term forecast with dataset ETTh1 for example."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"vscode": {
"languageId": "shellscript"
}
},
"outputs": [],
"source": [
"model_name=TimesNet\n",
"\n",
"\n",
"python -u run.py \\\n",
" --task_name long_term_forecast \\\n",
" --is_training 1 \\\n",
" --root_path ./dataset/ETT-small/ \\\n",
" --data_path ETTh1.csv \\\n",
" --model_id ETTh1_96_96 \\\n",
" --model $model_name \\\n",
" --data ETTh1 \\\n",
" --features M \\\n",
" --seq_len 96 \\\n",
" --label_len 48 \\\n",
" --pred_len 96 \\\n",
" --e_layers 2 \\\n",
" --d_layers 1 \\\n",
" --factor 3 \\\n",
" --enc_in 7 \\\n",
" --dec_in 7 \\\n",
" --c_out 7 \\\n",
" --d_model 16 \\\n",
" --d_ff 32 \\\n",
" --des 'Exp' \\\n",
" --itr 1 \\\n",
" --top_k 5\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"After finishing the shell script, you can run it in shell using bash. For example, you can run the following command, for `TimesNet` ETTh1 long-term forecast:"
"Here, the bash command may not be successfully implemented due to a lack of proper packages in the environment. If that's the case, simply follow the error information to install the missing package step by step until you achieve success. The sign of a successful experiment running is that information about the experiment is printed out, such as:"
">>>>>>>start training : long_term_forecast_ETTh1_96_96_TimesNet_ETTh1_ftM_sl96_ll48_pl96_dm16_nh8_el2_dl1_df32_fc3_ebtimeF_dtTrue_Exp_0>>>>>>>>>>>>>>>>>>>>>>>>>>\n",
"train 8449\n",
"val 2785\n",
"test 2785"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then, the model starts training. Once one epoch finishes training, information like below will be printer out:"