import torch
from models.TimeMixer import Model
from utils.tools import EarlyStopping, adjust_learning_rate
# Model configuration
class ModelConfig:
def __init__(self):
self.seq_len = 96 # input sequence length
self.label_len = 48 # start token length
self.pred_len = 96 # prediction length
# Model parameters
self.e_layers = 2 # encoder layers
self.d_model = 16 # dimension of model
self.d_ff = 32 # dimension of fcn
self.down_sampling_layers = 3 # number of down sampling layers
self.down_sampling_window = 2 # down sampling window size
self.enc_in = 7 # number of input features
self.c_out = 7 # number of output features
self.moving_avg = 25 # window size of moving average
self.factor = 1
self.dropout = 0.1
self.embed = 'timeF'
self.activation = 'gelu'
self.output_attention = False
self.channel_independence = 1
self.use_norm = 1
self.down_sampling_method = 'avg'
# Training/prediction pipeline
def train_and_predict(csv_path):
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Create datasets
config = ModelConfig()
train_dataset = CustomDataset(
root_path=csv_path,
flag='train',
size=[config.seq_len, config.label_len, config.pred_len],
features='M', # 'M' for multivariate, 'S' for univariate
target='target_column' # your target column name
)
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=32,
shuffle=True,
num_workers=0
)
# Initialize model
model = Model(config).to(device)
# Training configuration
criterion = torch.nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
scheduler = torch.optim.lr_scheduler.OneCycleLR(
optimizer,
max_lr=0.01,
steps_per_epoch=len(train_loader),
epochs=10,
pct_start=0.2
)
# Training
model.train()
for epoch in range(10):
total_loss = 0
for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(train_loader):
optimizer.zero_grad()
batch_x = batch_x.float().to(device)
batch_y = batch_y.float().to(device)
batch_x_mark = batch_x_mark.float().to(device)
batch_y_mark = batch_y_mark.float().to(device)
# decoder input
dec_inp = torch.zeros_like(batch_y[:, -config.pred_len:, :]).float()
dec_inp = torch.cat([batch_y[:, :config.label_len, :], dec_inp], dim=1).float().to(device)
# forward
outputs = model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
# compute loss
outputs = outputs[:, -config.pred_len:, :]
batch_y = batch_y[:, -config.pred_len:, :].to(device)
loss = criterion(outputs, batch_y)
# backward
loss.backward()
optimizer.step()
scheduler.step()
total_loss += loss.item()
print(f'Epoch {epoch}, Loss: {total_loss/len(train_loader)}')
# Prediction
model.eval()
test_dataset =