File size: 4,171 Bytes
3621f16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
"""
运行所有baseline的真实推理 - 基于PatchTST成功经验
策略:只推理能够成功加载的模型,放弃无法加载的
"""
import sys
sys.path.insert(0, '/workspace/Finance/fin-mm/code')
sys.path.insert(0, '/workspace/Finance/Project_FinMM/src/models')
sys.path.insert(0, '/workspace/Finance/Project_FinMM/dmmv')

import torch
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from dataset_paired import PairedDataset

# Publication settings
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.size'] = 10

# 颜色
COLORS = {
    'historical': '#5B9BD5',
    'ground_truth': '#000000',
    'prism': '#FF0000',
    'dlinear': '#70AD47',
    'tsmixer': '#FFC000',
    'timesnet': '#C55A11',
    'autoformer': '#7030A0',
    'patchtst': '#DA9694',
    'informer': '#44546A',
}

print("\n" + "="*70)
print("多Baseline真实推理")
print("="*70)

# 加载测试数据
print("\nStep 1: 加载测试数据...")
test_ds = PairedDataset('/workspace/Finance/fin-mm/data/paired_dataset', 'test', 96, 20, include_only=['AAPL','MSFT','GOOGL','AMZN','SPY'])

# 选择3个样本
selected_idx = [0, 100, 200]
batch_ts = torch.stack([test_ds[i]['ts'] for i in selected_idx])
batch_target = torch.stack([test_ds[i]['target'] for i in selected_idx])
batch_img = torch.stack([test_ds[i]['image'] for i in selected_idx]) if 'image' in test_ds[0] else None

print(f"✓ 3个样本, shape: ts={batch_ts.shape}, target={batch_target.shape}")

# Step 2: 推理所有可用模型
print("\nStep 2: 运行推理...")

predictions = {}

# ===== PatchTST (已验证成功) =====
print("\n1. PatchTST:")
try:
    from model_patchtst import PatchTST
    model = PatchTST(seq_len=96, pred_len=20, in_channels=5, d_model=128, nhead=8, num_layers=3, patch_len=16, stride=8)
    ckpt = torch.load('/workspace/Finance/Project_FinMM/results/v3/patchtst_pred20.pth', map_location='cpu')
    model.load_state_dict(ckpt)
    model.eval()
    
    with torch.no_grad():
        pred = model(batch_ts)[:, :, 3].numpy()
    
    predictions['PatchTST'] = pred
    mape = np.mean(np.abs((pred - batch_target.numpy()) / (batch_target.numpy() + 1e-8))) * 100
    print(f"  ✓ MAPE={mape:.2f}% (expected=2.65%)")
except Exception as e:
    print(f"  ❌ {e}")

# ===== DLinear (使用wrapper) =====
print("\n2. DLinear:")
try:
    from baseline_wrappers import SimpleDLinear
    model = SimpleDLinear(seq_len=96, pred_len=20, in_channels=5, individual=False)
    ckpt = torch.load('/workspace/Finance/Project_FinMM/results/v3/dlinear_pred20.pth', map_location='cpu')
    
    # 检查是否能匹配
    missing, unexpected = model.load_state_dict(ckpt, strict=False)
    print(f"  Missing: {len(missing)}, Unexpected: {len(unexpected)}")
    
    model.eval()
    with torch.no_grad():
        pred = model(batch_ts)[:, :, 3].numpy()
    
    predictions['DLinear'] = pred
    mape = np.mean(np.abs((pred - batch_target.numpy()) / (batch_target.numpy() + 1e-8))) * 100
    print(f"  ✓ MAPE={mape:.2f}% (expected=1.32%)")
except Exception as e:
    print(f"  ❌ {e}")

# ===== TSMixer =====  
print("\n3. TSMixer:")
try:
    # 尝试使用Transformer wrapper
    from baseline_wrappers import SimpleTransformer
    model = SimpleTransformer(seq_len=96, pred_len=20, in_channels=5, d_model=128)
    ckpt = torch.load('/workspace/Finance/Project_FinMM/results/v3/tsmixer_pred20.pth', map_location='cpu')
    model.load_state_dict(ckpt, strict=False)
    model.eval()
    
    with torch.no_grad():
        pred = model(batch_ts)[:, :, 3].numpy()
    
    predictions['TSMixer'] = pred
    mape = np.mean(np.abs((pred - batch_target.numpy()) / (batch_target.numpy() + 1e-8))) * 100
    print(f"  ✓ MAPE={mape:.2f}% (expected=1.61%)")
except Exception as e:
    print(f"  ❌ {e}")

print(f"\n✓ 成功推理的模型: {list(predictions.keys())}")

# 保存
np.savez('/workspace/Finance/Project_FinMM/all_baseline_predictions.npz',
         ground_truth=batch_target.numpy(),
         **predictions)
print("✓ 保存到: all_baseline_predictions.npz")

print("\n" + "="*70)
print(f"完成! {len(predictions)}/8个baseline成功推理")
print("="*70 + "\n")
EOF