File size: 4,300 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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | """
从checkpoint真正运行模型推理,生成真实预测结果
"""
import sys
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 json
from pathlib import Path
import pandas as pd
print("\n" + "="*70)
print("从Checkpoint运行真实推理")
print("="*70 + "\n")
# Step 1: 选择测试样本
print("Step 1: 选择真实测试样本...")
manifest_path = Path('/workspace/Finance/fin-mm/data/paired_dataset/manifest_pred20.json')
with open(manifest_path) as f:
manifest = json.load(f)
test_samples = manifest['splits']['test']
# 选择3个样本
selected = []
for sample in test_samples:
ticker = sample['ticker']
target = np.array(sample['target_close'])
trend = (target[-1] - target[0]) / target[0] * 100
if ticker == 'AAPL' and trend > 5 and len([s for s in selected if 'AAPL' in s[0]]) == 0:
selected.append(('AAPL (Uptrend)', sample))
elif ticker == 'MSFT' and trend < -2 and len([s for s in selected if 'MSFT' in s[0]]) == 0:
selected.append(('MSFT (Downtrend)', sample))
elif ticker == 'SPY' and len(selected) == 2:
selected.append(('SPY (Volatile)', sample))
break
print(f"✓ 选择了{len(selected)}个样本:")
for title, sample in selected:
print(f" - {title}: {sample['sample_id']}")
# Step 2: 准备输入数据
print("\nStep 2: 准备输入数据...")
data_base = Path('/workspace/Finance/fin-mm/data/paired_dataset')
test_inputs = []
test_targets = []
for title, sample in selected:
csv_path = data_base / sample['csv_path']
df = pd.read_csv(csv_path)
# OHLCV数据
ohlcv = df[['Open', 'High', 'Low', 'Close', 'Volume']].values # [96, 5]
target = np.array(sample['target_close']) # [20]
test_inputs.append(ohlcv)
test_targets.append(target)
test_inputs_tensor = torch.FloatTensor(np.array(test_inputs)) # [3, 96, 5]
test_targets_array = np.array(test_targets) # [3, 20]
print(f"✓ 输入shape: {test_inputs_tensor.shape}")
print(f"✓ 目标shape: {test_targets_array.shape}")
# Step 3: 逐个模型推理
print("\nStep 3: 运行模型推理...")
models_to_run = {
'DLinear': '/workspace/Finance/Project_FinMM/results/v3/dlinear_pred20.pth',
'PatchTST': '/workspace/Finance/Project_FinMM/results/v3/patchtst_pred20.pth',
}
all_predictions = {}
for model_name, ckpt_path in models_to_run.items():
print(f"\n{model_name}:")
try:
# 加载模型配置
if model_name == 'DLinear':
from baselines.dlinear import DLinear
class Cfg:
seq_len = 96
pred_len = 20
enc_in = 5
individual = False
model = DLinear(Cfg())
elif model_name == 'PatchTST':
from baselines.patchtst import PatchTST
class Cfg:
seq_len = 96
pred_len = 20
enc_in = 5
d_model = 128
n_heads = 8
d_ff = 256
patch_len = 16
stride = 8
model = PatchTST(Cfg())
# 加载权重
state_dict = torch.load(ckpt_path, map_location='cpu')
model.load_state_dict(state_dict)
model.eval()
# 推理
with torch.no_grad():
outputs = model(test_inputs_tensor) # [3, 20, 5] or [3, 20]
if outputs.dim() == 3:
pred = outputs[:, :, 3].numpy() # Close price
else:
pred = outputs.numpy()
all_predictions[model_name] = pred
# 计算MAPE
mape = np.mean(np.abs((pred - test_targets_array) / (test_targets_array + 1e-8))) * 100
print(f" ✓ 推理完成, MAPE={mape:.2f}%")
except Exception as e:
print(f" ❌ 失败: {e}")
# 保存结果
output_file = Path('/workspace/Finance/Project_FinMM/real_predictions.npz')
np.savez(output_file,
ground_truth=test_targets_array,
**all_predictions)
print(f"\n✓ 保存到: {output_file}")
print(f"✓ 包含模型: {list(all_predictions.keys())}")
print("\n" + "="*70)
print("✅ 真实推理完成!")
print("="*70 + "\n")
|