import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import pandas as pd
import numpy as np
from torch.amp import autocast, GradScaler
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import onnx
import onnxruntime
from tqdm import tqdm
import torch.nn.functional as F
Configuration
class Config:
def init(self):
self.task_name = 'short_term_forecast'
self.seq_len = 120 # Input sequence length
self.pred_len = 15 # Prediction length (30 minutes into the future)
self.d_model = 128 # Model dimension
self.enc_in = 4 # Number of input features (Open, High, Low, Close)
self.e_layers = 4 # Number of encoder layers
self.dropout = 0.3 # Reduced dropout for better generalization
self.batch_size = 256 # Increased batch size for better GPU utilization
self.learning_rate = 0.0005
self.epochs = 100
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.data_path = '/mnt/d/FX/fx_csv/22_23_1M.csv'
self.model_save_path = '/mnt/d/FX/Mixer_Models'
self.results_save_path = '/mnt/d/FX/Mixer_Results'
self.num_workers = 8
self.label_len = 0 # Typically 0 for forecasting tasks
self.down_sampling_window = 2 # Example value, adjust as needed
self.down_sampling_layers = 2 # Example value, adjust as needed
self.channel_independence = False
self.decomp_method = 'dft_decomp' # or 'moving_avg'
self.top_k = 1 # For DFT decomposition
self.moving_avg = 10 # For moving average decomposition
self.d_ff = 256 # Feed-forward dimension
self.embed = 'timeF' # Time feature embedding, 'timeF' or 'fixed'
self.freq = 'm' # Frequency of your time series, 'h' for hourly
self.use_norm = 1 # Whether to use normalization
self.down_sampling_method = 'avg' # 'max', 'avg', or 'conv'
self.c_out = 4 # Output size, typically same as enc_in for forecasting
configs = Config()
class DFT_series_decomp(nn.Module):
"""
Series decomposition block
"""
class series_decomp(nn.Module):
"""
Series decomposition block
"""
def init(self, kernel_size):
super(series_decomp, self).init()
self.moving_avg = moving_avg(kernel_size, stride=1)
def forward(self, x):
moving_mean = self.moving_avg(x)
# Pad `moving_mean` to match `x` if necessary
if moving_mean.shape[1] < x.shape[1]:
padding_size = x.shape[1] - moving_mean.shape[1]
moving_mean = F.pad(moving_mean, (0, 0, 0, padding_size)) # Padding on the second dimension
res = x - moving_mean
return res, moving_mean
Assistant
class moving_avg(nn.Module):
"""
Moving average block to highlight the trend of time series
"""
def init(self, kernel_size, stride):
super(moving_avg, self).init()
self.kernel_size = kernel_size
self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0)
def forward(self, x):
# padding on the both ends of time series
front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1)
end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1)
x = torch.cat([front, x, end], dim=1)
x = self.avg(x.permute(0, 2, 1))
x = x.permute(0, 2, 1)
return x
class Normalize(nn.Module):
def init(self, enc_in, affine=True, non_norm=False):
super(Normalize, self).init()
self.non_norm = non_norm
if not self.non_norm:
self.norm_layer = nn.LayerNorm(enc_in, elementwise_affine=affine)
def forward(self, x, operation='norm'):
if self.non_norm:
return x
if operation == 'norm':
return self.norm_layer(x)
elif operation == 'denorm':
return x * self.norm_layer.weight + self.norm_layer.bias
else:
raise ValueError('Operation must be either "norm" or "denorm"')
model = Model(configs).to(configs.device)
optimizer = torch.optim.AdamW(model.parameters(), lr=configs.learning_rate)
criterion = ExponentialMSELoss(alpha=0.1).to(configs.device)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=5)
best_test_loss = float('inf')
for epoch in range(configs.epochs):
train_loss, train_mae = train(model, train_loader, optimizer, criterion, configs.device, epoch, configs)
test_loss, test_mae = evaluate(model, test_loader, criterion, configs.device, configs)
scheduler.step(test_loss)
print(f"\nEpoch {epoch+1}/{configs.epochs}")
print(f"Train Loss: {train_loss:.4f}, Train MAE: {train_mae:.4f}")
print(f"Test Loss: {test_loss:.4f}, Test MAE: {test_mae:.4f}")
print(f"Current Learning Rate: {optimizer.param_groups[0]['lr']:.6f}")
if test_loss < best_test_loss:
best_test_loss = test_loss
save_model(model, configs.model_save_path, epoch+1, test_loss)
# Save final results
if not os.path.exists(configs.results_save_path):
os.makedirs(configs.results_save_path)
with open(os.path.join(configs.results_save_path, 'training_results.txt'), 'w') as f:
f.write(f"Final Train Loss: {train_loss:.4f}\n")
f.write(f"Final Train MAE: {train_mae:.4f}\n")
f.write(f"Final Test Loss: {test_loss:.4f}\n")
f.write(f"Final Test MAE: {test_mae:.4f}\n")
f.write(f"Best Test Loss: {best_test_loss:.4f}\n")
print("Training completed. Results saved.")
if name == "main":
main()
Your implementation for a short-term Forex forecasting model using PyTorch is comprehensive and includes several sophisticated components. Here's an overview of your code along with some recommendations and considerations to ensure everything functions as intended.
1. Overview of the Code
Configuration (Config Class)
Purpose: Centralizes all hyperparameters and configurations, making it easier to manage and modify settings.
Key Parameters:
Data Parameters:seq_len, pred_len, enc_in, c_out.
Model Parameters:d_model, e_layers, d_ff, dropout.
Training Parameters:batch_size, learning_rate, epochs, num_workers.
Purpose: Handles the creation of input-output pairs for the model, incorporating time-based features.
Time Features: Extracts month, day, weekday, hour, and minute (grouped into 15-minute intervals) from the datetime index.
preprocess_data Function:
Purpose: Loads the CSV data, scales the features, splits the dataset into training and testing sets, and creates DataLoaders.
Scaling: Uses StandardScaler to normalize the input features (Open, High, Low, Close).
Model Architecture
Decomposition Modules:
DFT_series_decomp: Performs Discrete Fourier Transform-based decomposition to separate seasonality and trend.
series_decomp & moving_avg: Utilize moving averages for trend extraction.
Embedding Layers:
DataEmbedding_wo_pos: Combines value embeddings (TokenEmbedding) with temporal embeddings (TemporalEmbedding) without positional encoding.
Multi-Scale Mixing:
MultiScaleSeasonMixing & MultiScaleTrendMixing: Handle multi-scale interactions for seasonality and trend components.
Main Model Class:
Components:
PastDecomposableMixing (pdm_blocks): Applies multiple layers of decomposable mixing.
Prediction Layers: Linear layers tailored for forecasting tasks.
Normalization: Layer normalization applied at various stages.
Forward Methods: Different paths for forecasting, imputation, anomaly detection, and classification tasks.
Training and Evaluation
Loss Function:ExponentialMSELoss introduces an exponential weighting to the standard MSE, emphasizing larger errors.
Training Loop (train Function):
Utilizes mixed precision training with autocast and GradScaler to optimize performance and memory usage.
Tracks both loss and Mean Absolute Error (MAE) for performance monitoring.
Evaluation Loop (evaluate Function):
Similar to the training loop but without gradient computations.
Model Saving (save_model Function):
Exports the trained model to ONNX format for interoperability.
Main Execution (main Function):
Orchestrates data preprocessing, model initialization, training, evaluation, and saving of results.
2. Recommendations and Considerations
While your implementation is robust, here are some recommendations and points to verify to ensure optimal performance and functionality:
a. Data Handling
CSV Structure: Ensure that your CSV file (22_23_1M.csv) contains the expected columns: DateTime, Open, High, Low, Close.
Datetime Parsing: Verify that the DateTime column is correctly parsed and set as the index. Any inconsistencies in datetime formats can lead to errors in time feature extraction.
Missing Values: Check for any missing or NaN values in your dataset. Missing data can adversely affect model training and predictions.
b. Time Feature Engineering
Minute Grouping: You're grouping minutes into 15-minute intervals. Ensure that this aligns with your forecasting horizon and that it doesn't lead to significant information loss.
Start Date: The start_date is set based on the first index of the DataFrame. Confirm that this aligns with your data's actual timeline.
c. Model Architecture
Decomposition Methods: You've implemented both DFT-based and moving average-based decomposition. Experiment with both to determine which yields better performance for your specific dataset.
Channel Independence: Depending on whether channel_independence is True or False, the model behaves differently. Ensure that this setting aligns with your forecasting needs.
Multi-Scale Mixing: The multi-scale approach is powerful but can be computationally intensive. Monitor GPU memory usage, especially with higher down_sampling_layers.
d. Training Considerations
Batch Size: A batch size of 256 is set, which is generally large. Ensure your GPU memory can handle this, or consider reducing it if you encounter memory issues.
Learning Rate Scheduler:ReduceLROnPlateau adjusts the learning rate based on the validation loss. Monitor to ensure it adjusts appropriately and doesn't reduce the learning rate too aggressively.
Loss Function: The ExponentialMSELoss emphasizes larger errors. This can be beneficial but may also lead to instability if outliers are present. Monitor the loss values to ensure they're behaving as expected.
e. Mixed Precision Training
Compatibility: Ensure that all model components and operations are compatible with mixed precision. Some custom layers or operations might not support it, leading to potential issues.
Loss Scaling:GradScaler helps in preventing gradient underflow. However, monitor the scaling process to ensure it's operating correctly, especially if you encounter NaNs or infinite values.
f. Model Saving and Deployment
ONNX Export: Not all PyTorch operations are supported in ONNX. After exporting, validate the ONNX model using tools like onnxruntime to ensure it's functioning correctly.
Dynamic Axes: You've set dynamic axes for batch sizes, which is good for flexibility. Ensure that all variable-length dimensions are appropriately handled during inference.
g. General Code Robustness
Error Handling: Incorporate try-except blocks where necessary, especially around data loading and model exporting, to handle unexpected issues gracefully.
Logging: Consider using a logging library (like Python's built-in logging module) instead of print statements for better control over log levels and outputs.
Reproducibility: Set random seeds for PyTorch, NumPy, and other libraries to ensure reproducible results.
3. Potential Enhancements
Here are some ideas to further improve your model and training pipeline:
a. Hyperparameter Tuning
Grid or Random Search: Explore different hyperparameter settings (like d_model, e_layers, dropout, learning_rate) to find the optimal configuration.
Automated Tools: Utilize tools like Optuna or Hyperopt for more efficient hyperparameter optimization.
b. Early Stopping
Implement early stopping based on validation performance to prevent overfitting and reduce training time.
c. Additional Metrics
Diversity of Metrics: In addition to MAE, consider metrics like Root Mean Squared Error (RMSE), Mean Absolute Percentage Error (MAPE), or others relevant to your forecasting objectives.
Visualizations: Plot training and validation loss curves, as well as prediction vs. actual values, to gain insights into model performance.
d. Cross-Validation
Implement cross-validation strategies to ensure that your model generalizes well across different data splits.
e. Model Interpretability
Incorporate methods to interpret the model's predictions, such as feature importance analysis or attention visualization if applicable.
f. Optimization
Gradient Accumulation: If limited by GPU memory, consider gradient accumulation to effectively simulate larger batch sizes.
Distributed Training: For larger datasets or models, explore distributed training strategies using multiple GPUs or machines.
4. Next Steps and Debugging Tips
If you encounter issues or unexpected behaviors while running your code, here are some debugging tips:
Check Data Loading:
Verify that ForexDataset correctly slices the data and that the time features align with the input sequences.
Model Forward Pass:
Insert print statements or use debugging tools (like pdb) to inspect tensor shapes and ensure they're consistent across layers.
Loss and Metrics:
Monitor the loss and MAE values for anomalies (e.g., exploding loss values) which can indicate issues in the model or data.
ONNX Export:
Test the exported ONNX model separately to ensure it's operational. Use onnxruntime to run inference and compare results with the PyTorch model.
5. Conclusion
Your implementation demonstrates a deep understanding of advanced time series forecasting techniques and PyTorch's capabilities. By carefully reviewing the recommendations and ensuring each component functions as intended, you can optimize your model's performance and robustness. If you have specific questions or encounter particular challenges, feel free to ask for more targeted assistance!