File size: 4,325 Bytes
d702e58 | 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 | """
Unified Training Functions Module.
All v2 experiment scripts call this module to ensure consistent training logic.
"""
import torch
import torch.nn as nn
import numpy as np
def train_model(model, train_loader, val_loader, test_loader, args, model_name):
"""
Unified training procedure.
Args:
model: PyTorch model
train_loader, val_loader, test_loader: Data loaders
args: Command line arguments
model_name: Model name (for saving)
"""
optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)
best_mape = float('inf')
patience_counter = 0
print(f"Starting training | Early stopping: stop if MAPE no improvement for {args.patience} epochs\n")
for epoch in range(1, args.epochs + 1):
# ========== Training Phase ==========
model.train()
train_losses = []
for batch_idx, (bx, by) in enumerate(train_loader):
optimizer.zero_grad()
pred = model(bx.cuda())[:, :, 3]
loss = nn.MSELoss()(pred, by.cuda())
loss.backward()
# Gradient clipping (for large models)
if 'DMMV' in model_name or 'trimodal' in model_name:
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
train_losses.append(loss.item())
# Print progress every 20%
total = len(train_loader)
milestones = [int(total * p) for p in [0.2, 0.4, 0.6, 0.8]]
if batch_idx in milestones or batch_idx == total - 1:
pct = (batch_idx + 1) / total * 100
print(f" Epoch {epoch}/{args.epochs}: {pct:.0f}% | loss={loss.item():.4f}")
train_mse = np.mean(train_losses)
print(f" Training done | avg_MSE={train_mse:.4f}")
# ========== Validation Phase (every epoch) ==========
model.eval()
vp, vt = [], []
with torch.no_grad():
for bx, by in val_loader:
vp.append(model(bx.cuda())[:, :, 3])
vt.append(by.cuda())
vp = torch.cat(vp).cpu().numpy()
vt = torch.cat(vt).cpu().numpy()
# Compute metrics
val_mse = np.mean((vp - vt) ** 2)
val_mape = np.mean(np.abs((vp - vt) / (vt + 1e-8))) * 100
val_direction = np.mean((np.sign(vp[:, -1] - vp[:, 0]) == np.sign(vt[:, -1] - vt[:, 0])).astype(float)) * 100
print(f" Val MSE={val_mse:.4f} MAPE={val_mape:.2f}% Dir={val_direction:.1f}%", end='')
# Early Stopping check
if val_mape < best_mape:
best_mape = val_mape
torch.save(model.state_dict(), f'./results/v2/{model_name}_pred{args.pred_len}.pth')
print(f" [SAVED]")
patience_counter = 0
else:
patience_counter += 1
print(f" [patience {patience_counter}/{args.patience}]")
if patience_counter >= args.patience:
print(f"\nEarly stopping: MAPE no improvement for {args.patience} epochs\n")
break
# ========== Test Set Evaluation ==========
print(f"\nEvaluating on test set...", end='', flush=True)
model.load_state_dict(torch.load(f'./results/v2/{model_name}_pred{args.pred_len}.pth'))
model.eval()
tp, tt = [], []
with torch.no_grad():
for bx, by in test_loader:
tp.append(model(bx.cuda())[:, :, 3])
tt.append(by.cuda())
tp = torch.cat(tp).cpu().numpy()
tt = torch.cat(tt).cpu().numpy()
test_mse = np.mean((tp - tt) ** 2)
test_mape = np.mean(np.abs((tp - tt) / (tt + 1e-8))) * 100
test_direction = np.mean((np.sign(tp[:, -1] - tp[:, 0]) == np.sign(tt[:, -1] - tt[:, 0])).astype(float)) * 100
test_ic = np.corrcoef(tp.flatten(), tt.flatten())[0, 1]
print(f" MSE={test_mse:.4f} MAPE={test_mape:.2f}% Dir={test_direction:.1f}% IC={test_ic:.3f}")
print(f"Training complete! Model: ./results/v2/{model_name}_pred{args.pred_len}.pth | Best val MAPE={best_mape:.2f}%\n")
return {
'best_val_mape': best_mape,
'test_mse': test_mse,
'test_mape': test_mape,
'test_direction': test_direction,
'test_ic': test_ic
}
|