File size: 8,369 Bytes
bc200fc | 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | """
Paired Dataset Loader for Multi-Modal Training.
Loads the paired (CSV + PNG) dataset generated by generate_paired_dataset.py.
Compatible with LLaVA+DMMV-A+DMMV-S+Kronos training pipeline.
Output format matches TimeSeriesWithKlineDataset:
- ts: [seq_len, 5] OHLCV time series (log-transformed)
- image: [3, 336, 336] K-line chart image
- target: [pred_len] Close prices (log-transformed)
"""
import os
import json
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset
from PIL import Image
from pathlib import Path
class PairedDataset(Dataset):
"""
Load paired time series CSV and K-line PNG for multi-modal training.
Expects directory structure:
data_dir/
+-- train/
| +-- timeseries/*.csv
| +-- kline_img/*.png
| +-- samples_pred20.json
+-- val/
+-- test/
"""
def __init__(
self,
data_dir: str,
mode: str = 'train',
seq_len: int = 96,
pred_len: int = 20,
max_samples: int = None,
use_log_transform: bool = True,
exclude_tickers: list = None,
include_only: list = None
):
"""
Args:
data_dir: Path to paired_dataset directory
mode: 'train', 'val', or 'test'
seq_len: Input sequence length (should match CSV data)
pred_len: Prediction length
max_samples: Limit number of samples (for quick testing)
use_log_transform: Apply log(x+1) transform to prices
exclude_tickers: List of tickers to exclude (e.g., ['BTC-USD', 'ETH-USD'])
include_only: List of tickers to include only (e.g., ['BTC-USD', 'ETH-USD'])
"""
self.data_dir = Path(data_dir)
self.mode = mode
self.seq_len = seq_len
self.pred_len = pred_len
self.use_log_transform = use_log_transform
self.exclude_tickers = exclude_tickers or []
self.include_only = include_only or []
# Load sample index
samples_file = self.data_dir / mode / f"samples_pred{pred_len}.json"
if not samples_file.exists():
raise FileNotFoundError(f"Samples file not found: {samples_file}")
with open(samples_file, 'r') as f:
all_samples = json.load(f)
# 过滤数据
if self.include_only:
self.samples = [s for s in all_samples if s['ticker'] in self.include_only]
print(f"[PairedDataset] {mode}: {len(self.samples)} samples (仅包含{self.include_only})")
elif self.exclude_tickers:
self.samples = [s for s in all_samples if s['ticker'] not in self.exclude_tickers]
print(f"[PairedDataset] {mode}: {len(self.samples)} samples (排除{self.exclude_tickers})")
else:
self.samples = all_samples
print(f"[PairedDataset] {mode}: {len(self.samples)} samples loaded")
# Limit samples if requested
if max_samples is not None:
self.samples = self.samples[:max_samples]
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
sample = self.samples[idx]
# Load time series CSV
csv_path = self.data_dir / sample['csv_path']
df = pd.read_csv(csv_path)
# Extract OHLCV data
ohlcv = df[['Open', 'High', 'Low', 'Close', 'Volume']].values
# Apply log transform (standard practice for financial data)
if self.use_log_transform:
ohlcv = np.log(ohlcv + 1)
# Get target from sample info (already stored in manifest)
target = np.array(sample['target_close'])
if self.use_log_transform:
target = np.log(target + 1)
# Load K-line image
png_path = self.data_dir / sample['png_path']
try:
img = Image.open(png_path).convert('RGB')
img = img.resize((336, 336)) # LLaVA CLIP-336
img_tensor = torch.FloatTensor(np.array(img)).permute(2, 0, 1) / 255.0
except Exception as e:
print(f"Warning: Failed to load image {png_path}: {e}")
img_tensor = torch.zeros(3, 336, 336)
return {
'ts': torch.FloatTensor(ohlcv), # [96, 5]
'image': img_tensor, # [3, 336, 336]
'target': torch.FloatTensor(target), # [20]
'sample_id': sample['sample_id'] # For debugging
}
class PairedDatasetSimple(Dataset):
"""
Simplified version without K-line images.
For testing DMMV/Kronos models without LLaVA.
"""
def __init__(
self,
data_dir: str,
mode: str = 'train',
seq_len: int = 96,
pred_len: int = 20,
max_samples: int = None,
use_log_transform: bool = True
):
self.data_dir = Path(data_dir)
self.mode = mode
self.seq_len = seq_len
self.pred_len = pred_len
self.use_log_transform = use_log_transform
samples_file = self.data_dir / mode / f"samples_pred{pred_len}.json"
if not samples_file.exists():
raise FileNotFoundError(f"Samples file not found: {samples_file}")
with open(samples_file, 'r') as f:
self.samples = json.load(f)
if max_samples is not None:
self.samples = self.samples[:max_samples]
print(f"[PairedDatasetSimple] {mode}: {len(self.samples)} samples")
def __len__(self):
return len(self.samples)
def __getitem__(self, idx):
sample = self.samples[idx]
csv_path = self.data_dir / sample['csv_path']
df = pd.read_csv(csv_path)
ohlcv = df[['Open', 'High', 'Low', 'Close', 'Volume']].values
if self.use_log_transform:
ohlcv = np.log(ohlcv + 1)
target = np.array(sample['target_close'])
if self.use_log_transform:
target = np.log(target + 1)
return torch.FloatTensor(ohlcv), torch.FloatTensor(target)
def test_dataset():
"""Quick test to verify dataset loading works."""
import sys
# Use relative path for testing
data_dir = Path(__file__).parent.parent / "data" / "paired_dataset"
if not data_dir.exists():
print(f"[ERROR] Data directory not found: {data_dir}")
print("Please run generate_paired_dataset.py first.")
return False
print("=" * 60)
print("Testing PairedDataset Loading")
print("=" * 60)
success = True
for mode in ['train', 'val', 'test']:
try:
ds = PairedDataset(data_dir, mode=mode, max_samples=5)
if len(ds) == 0:
print(f"[WARN] {mode}: No samples")
continue
sample = ds[0]
print(f"\n[{mode}] First sample:")
print(f" sample_id: {sample['sample_id']}")
print(f" ts shape: {sample['ts'].shape}")
print(f" image shape: {sample['image'].shape}")
print(f" target shape: {sample['target'].shape}")
# Verify shapes
assert sample['ts'].shape == (96, 5), f"Expected ts shape (96, 5), got {sample['ts'].shape}"
assert sample['image'].shape == (3, 336, 336), f"Expected image shape (3, 336, 336), got {sample['image'].shape}"
assert sample['target'].shape[0] == 20, f"Expected target length 20, got {sample['target'].shape[0]}"
print(f" [OK] Shapes verified!")
except Exception as e:
print(f"[ERROR] {mode}: {e}")
success = False
print("\n" + "=" * 60)
if success:
print("[SUCCESS] Dataset loading verified!")
else:
print("[FAILED] Some tests failed")
print("=" * 60)
return success
if __name__ == "__main__":
test_dataset()
|