Download src/experiments/baselines/run_real_inference.py from GoldenGrapeGentleman1/FinMM-Project-FinMM: direct link, hf CLI and curl.
- Browser
- Download file 4.3 kB
-
https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/experiments/baselines/run_real_inference.py
- Command line
-
hf download hf://GoldenGrapeGentleman1/FinMM-Project-FinMM/src/experiments/baselines/run_real_inference.py
-
curl -L -o run_real_inference.py https://huggingface.co/GoldenGrapeGentleman1/FinMM-Project-FinMM/resolve/main/src/experiments/baselines/run_real_inference.py
4.3 kB
| """ | |
| 从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") | |