loft-table5-ablation / code /prepare_data.py
mendoanjoe's picture
data prep
c58d6a8 verified
Raw History Blame Contribute Delete
2.33 kB
#!/usr/bin/env python3
"""Materialise zh-plus/tiny-imagenet parquet files into the ImageFolder layout that the
author code (utils_data.tinyimgnet_dataloaders) expects:
<root>/train/<label:03d>/images/*.JPEG (100,000 images, 500 per class)
<root>/val/<label:03d>/images/*.JPEG ( 10,000 images, 50 per class)
Class directories are named with the zero-padded *integer* label, so that ImageFolder's
lexicographic sort of directory names reproduces the ClassLabel index order exactly
(000..199). Raw JPEG bytes are written unchanged (no re-encode).
"""
import io
import os
import sys
import time
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download
REPO = "zh-plus/tiny-imagenet"
TRAIN = "data/train-00000-of-00001-1359597a978bc4fa.parquet"
VALID = "data/valid-00000-of-00001-70d52db3c749a935.parquet"
def dump(pq_path, split, root):
out = os.path.join(root, split)
pf = pq.ParquetFile(pq_path)
n = 0
t0 = time.time()
for batch in pf.iter_batches(batch_size=2000, columns=["image", "label"]):
img = batch.column("image")
if hasattr(img, "field"):
try:
raw = img.field("bytes")
except (KeyError, IndexError):
raw = img.field(0)
else:
raw = img
labels = batch.column("label").to_pylist()
for i in range(batch.num_rows):
y = int(labels[i])
d = os.path.join(out, f"{y:03d}", "images")
os.makedirs(d, exist_ok=True)
with open(os.path.join(d, f"{split}_{n:06d}.JPEG"), "wb") as f:
f.write(raw[i].as_py())
n += 1
if n % 20000 == 0:
print(f" {split}: {n} images ({time.time() - t0:.1f}s)", flush=True)
return n
def main():
root = sys.argv[1] if len(sys.argv) > 1 else "/work/tiny-imagenet-200"
os.makedirs(root, exist_ok=True)
n_tr = dump(hf_hub_download(REPO, TRAIN, repo_type="dataset"), "train", root)
n_va = dump(hf_hub_download(REPO, VALID, repo_type="dataset"), "val", root)
print(f"train={n_tr} val={n_va} at {root}")
assert n_tr == 100000 and n_va == 10000, (n_tr, n_va)
n_classes = len(os.listdir(os.path.join(root, "train")))
print(f"classes: {n_classes}")
assert n_classes == 200
if __name__ == "__main__":
main()