-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_prism_splits.py
More file actions
189 lines (146 loc) · 6.38 KB
/
create_prism_splits.py
File metadata and controls
189 lines (146 loc) · 6.38 KB
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
#!/usr/bin/env python3
"""
Simple script to generate train/val/test splits for PRISM datasets.
Creates JSON files that can be loaded by DataPreparer.
Usage:
python create_prism_splits.py
"""
import pandas as pd
import numpy as np
import json
from pathlib import Path
from sklearn.model_selection import train_test_split
def create_splits_for_prism_data():
"""
Create train/val/test splits for the main PRISM dataset.
Saves indices to JSON file that DataPreparer can load.
"""
print("=== Creating PRISM Dataset Splits ===")
# Data paths (adjust these to match your actual data)
data_paths = [
"prism/data/tahoe_4M_moa-encoded.parquet",
"data/tahoe_4M_moa-encoded.parquet",
"tahoe_4M_moa-encoded.parquet"
]
# Find the data file
data_path = None
for path in data_paths:
if Path(path).exists():
data_path = path
break
if data_path is None:
print("Error: Could not find data file. Tried:")
for path in data_paths:
print(f" - {path}")
print("\nPlease update the data_paths list in this script or place your data file in one of these locations.")
return False
print(f"Found data file: {data_path}")
# Load the dataset
print("Loading dataset...")
df = pd.read_parquet(data_path)
n_samples = len(df)
print(f"Dataset contains {n_samples:,} samples")
print(f"Columns: {list(df.columns)}")
# Find MoA labels for stratified splitting
moa_column = None
possible_columns = ['moa-fine-encoded', 'moa-fine', 'moa', 'labels']
for col in possible_columns:
if col in df.columns:
moa_column = col
break
if moa_column:
print(f"Using '{moa_column}' for stratified splitting")
labels = df[moa_column].values
# Convert string labels to integers if needed
if isinstance(labels[0], str):
unique_labels = np.unique(labels)
label_to_idx = {label: idx for idx, label in enumerate(unique_labels)}
labels = np.array([label_to_idx[label] for label in labels])
print(f"Converted {len(unique_labels)} string labels to integers")
print(f"Label distribution: {dict(zip(*np.unique(labels, return_counts=True)))}")
else:
print("Warning: No MoA column found, using random splitting")
labels = np.random.randint(0, 10, n_samples) # Create dummy labels
# Create indices
indices = np.arange(n_samples)
print("\nCreating 80% train / 10% val / 10% test splits...")
# First split: 90% train+val, 10% test
train_val_indices, test_indices = train_test_split(
indices, test_size=0.1, random_state=42, stratify=labels
)
# Second split: 80% train, 10% val (of the remaining 90%)
train_indices, val_indices = train_test_split(
train_val_indices, test_size=0.111, random_state=42, # 0.111 ≈ 10/90
stratify=labels[train_val_indices]
)
# Create splits dictionary
splits = {
"train": train_indices.tolist(),
"val": val_indices.tolist(),
"test": test_indices.tolist()
}
# Print split statistics
print(f"\nSplit sizes:")
print(f" Train: {len(splits['train']):,} samples ({len(splits['train'])/n_samples:.1%})")
print(f" Val: {len(splits['val']):,} samples ({len(splits['val'])/n_samples:.1%})")
print(f" Test: {len(splits['test']):,} samples ({len(splits['test'])/n_samples:.1%})")
# Validate splits
all_indices = set(splits['train'] + splits['val'] + splits['test'])
assert len(all_indices) == n_samples, "Split validation failed: not all samples covered"
assert len(all_indices) == len(splits['train']) + len(splits['val']) + len(splits['test']), "Split validation failed: overlapping indices"
print("✓ Split validation passed")
# Save splits
output_dir = Path("prism/data/splits")
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / "train_val_test_splits.json"
with open(output_path, 'w') as f:
json.dump(splits, f, indent=2)
print(f"\n✓ Splits saved to: {output_path}")
# Also save to the general data/splits directory
general_output_dir = Path("data/splits")
general_output_dir.mkdir(parents=True, exist_ok=True)
general_output_path = general_output_dir / "train_val_test_splits.json"
with open(general_output_path, 'w') as f:
json.dump(splits, f, indent=2)
print(f"✓ Splits also saved to: {general_output_path}")
# Show example of how to use
print(f"\n=== Usage Instructions ===")
print(f"These splits can now be used by DataPreparer:")
print(f"1. Make sure your config file has:")
print(f" data:")
print(f" splits_path: \"{output_path}\"")
print(f"2. When you call data_preparer.prepare_train_val_test(), it will automatically load these splits")
print(f"3. This ensures reproducible train/val/test splits across different runs")
return True
def create_demo_splits():
"""Create a small demo splits file for testing."""
print("\n=== Creating Demo Splits ===")
# Create demo splits for 1000 samples
n_samples = 1000
indices = np.arange(n_samples)
# Simple splitting
np.random.seed(42)
shuffled = np.random.permutation(indices)
train_end = int(0.8 * n_samples) # 800
val_end = int(0.9 * n_samples) # 900
demo_splits = {
"train": shuffled[:train_end].tolist(),
"val": shuffled[train_end:val_end].tolist(),
"test": shuffled[val_end:].tolist()
}
# Save demo splits
demo_output = Path("data/splits/demo_splits.json")
demo_output.parent.mkdir(parents=True, exist_ok=True)
with open(demo_output, 'w') as f:
json.dump(demo_splits, f, indent=2)
print(f"Demo splits saved to: {demo_output}")
print(f" Train: {len(demo_splits['train'])} samples")
print(f" Val: {len(demo_splits['val'])} samples")
print(f" Test: {len(demo_splits['test'])} samples")
if __name__ == "__main__":
success = create_splits_for_prism_data()
if not success:
print("\nCreating demo splits instead...")
create_demo_splits()
print("\n=== Complete! ===")
print("You can now use these splits with DataPreparer for reproducible train/val/test splits.")