FinMM-Project-FinMM / src /utils /train_utils.py
GoldenGrapeGentleman1's picture
Upload Project_FinMM before machine wipe (part 2)
d702e58 verified
Raw History Blame Contribute Delete
4.33 kB
"""
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
}