HotSight / scripts /make_random_splits.py
hotsight's picture
Super-squash branch 'main' using huggingface_hub
4e6a175
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
"""Create dataset splits or transfer clip assignments to the pretraining set."""
import argparse
import csv
import random
from collections import Counter, defaultdict
from pathlib import Path
SITES = ("Canopy", "Graminoid")
MIN_VALIDATION_PERCENTAGE = 10
MAX_VALIDATION_PERCENTAGE = 20
# Clips in each tuple must remain in the same split. These are the inseparable
# flights documented in markdown/flights.md; all other clips are singletons.
FLIGHT_GROUPS = {
"Canopy": (
("Canopy-06", "Canopy-07", "Canopy-08", "Canopy-09", "Canopy-10",
"Canopy-11", "Canopy-17"),
("Canopy-12", "Canopy-13", "Canopy-15"),
("Canopy-20", "Canopy-21", "Canopy-22"),
),
"Graminoid": (
("Graminoid-04", "Graminoid-05"),
("Graminoid-09", "Graminoid-10", "Graminoid-11"),
("Graminoid-12", "Graminoid-13", "Graminoid-14"),
("Graminoid-16", "Graminoid-17", "Graminoid-18"),
),
}
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"data_root",
nargs="?",
type=Path,
default=Path("Data"),
help="dataset root containing samples.csv (default: %(default)s)",
)
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument(
"--test",
choices=SITES,
help="burn site assigned entirely to the test split",
)
mode.add_argument(
"--finetune-split",
type=Path,
help=(
"splits.csv whose clip assignments should be transferred to this "
"more densely sampled dataset"
),
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="random seed used for reproducible tie-breaking (default: %(default)s)",
)
return parser.parse_args()
def load_samples(manifest):
clips = {site: set() for site in SITES}
clip_sites = {}
frames = []
seen_frames = set()
with manifest.open(newline="") as handle:
reader = csv.DictReader(handle)
required = {"pair_id", "unit", "rgb_path"}
if not reader.fieldnames or not required.issubset(reader.fieldnames):
raise RuntimeError(f"invalid samples.csv header: {manifest}")
for line_number, row in enumerate(reader, start=2):
clip = row["pair_id"].strip()
site = row["unit"].strip()
rgb_path = row["rgb_path"].strip()
if not clip:
raise RuntimeError(f"empty pair_id on samples.csv line {line_number}")
if not rgb_path:
raise RuntimeError(f"empty rgb_path on samples.csv line {line_number}")
path = Path(rgb_path)
if len(path.parts) < 2 or path.parts[-2] != "rgb":
raise RuntimeError(
f"unexpected rgb_path {rgb_path!r} on samples.csv line "
f"{line_number}"
)
frame = (Path(*path.parts[:-2]) / path.name).as_posix()
if site not in clips:
raise RuntimeError(
f"unknown unit {site!r} on samples.csv line {line_number}"
)
if frame in seen_frames:
raise RuntimeError(f"duplicate rgb_path {frame!r} in samples.csv")
previous_site = clip_sites.setdefault(clip, site)
if previous_site != site:
raise RuntimeError(f"clip {clip!r} belongs to multiple units")
seen_frames.add(frame)
clips[site].add(clip)
frames.append((frame, clip, site))
for site in SITES:
if not clips[site]:
raise RuntimeError(f"samples.csv contains no {site} clips")
return frames, clips
def load_clip_splits(path):
clip_splits = {}
unit_splits = defaultdict(set)
with path.open(newline="") as handle:
reader = csv.DictReader(handle)
required = {"frame", "split"}
if not reader.fieldnames or not required.issubset(reader.fieldnames):
raise RuntimeError(f"invalid splits.csv header: {path}")
for line_number, row in enumerate(reader, start=2):
frame = Path(row["frame"].strip())
split = row["split"].strip()
if len(frame.parts) != 3:
raise RuntimeError(
f"unexpected frame path {frame.as_posix()!r} on line "
f"{line_number} of {path}"
)
if split not in {"train", "val", "test"}:
raise RuntimeError(
f"unknown split {split!r} on line {line_number} of {path}"
)
unit, clip = frame.parts[:2]
if unit not in SITES:
raise RuntimeError(
f"unknown unit {unit!r} on line {line_number} of {path}"
)
previous = clip_splits.setdefault(clip, split)
if previous != split:
raise RuntimeError(
f"clip {clip!r} occurs in both {previous!r} and {split!r}"
)
unit_splits[unit].add(split)
if not clip_splits:
raise RuntimeError(f"no split assignments found in {path}")
test_sites = [site for site in SITES if unit_splits[site] == {"test"}]
if len(test_sites) != 1:
raise RuntimeError(
f"expected exactly one entirely held-out unit in {path}, found "
f"{len(test_sites)}"
)
test_site = test_sites[0]
training_site = next(site for site in SITES if site != test_site)
if not unit_splits[training_site] or not unit_splits[training_site] <= {
"train",
"val",
}:
raise RuntimeError(
f"unexpected assignments for training unit {training_site!r} in "
f"{path}"
)
return clip_splits, test_site
def make_flight_blocks(site, clips):
blocks = []
grouped = set()
for documented_group in FLIGHT_GROUPS[site]:
present = tuple(clip for clip in documented_group if clip in clips)
if present:
blocks.append(present)
grouped.update(present)
blocks.extend((clip,) for clip in sorted(clips - grouped))
return blocks
def choose_validation_blocks(blocks, frame_counts, rng):
if len(blocks) < 2:
raise RuntimeError("at least two flight blocks are needed for train/val")
block_frame_counts = [
sum(frame_counts[clip] for clip in block) for block in blocks
]
total_frames = sum(block_frame_counts)
candidates = []
for mask in range(1, (1 << len(blocks)) - 1):
val_frames = sum(
count
for index, count in enumerate(block_frame_counts)
if mask & (1 << index)
)
if (
MIN_VALIDATION_PERCENTAGE * total_frames
<= 100 * val_frames
<= MAX_VALIDATION_PERCENTAGE * total_frames
):
candidates.append(mask)
if not candidates:
raise RuntimeError(
"no combination of complete flight blocks puts validation between "
f"{MIN_VALIDATION_PERCENTAGE}% and {MAX_VALIDATION_PERCENTAGE}% "
"of frames"
)
selected_mask = rng.choice(candidates)
selected = [
block for index, block in enumerate(blocks) if selected_mask & (1 << index)
]
return selected
def transfer_validation_blocks(blocks, frame_counts, clip_splits, rng):
fixed_validation = []
unassigned = []
for block in blocks:
assignments = {clip_splits[clip] for clip in block if clip in clip_splits}
if "test" in assignments:
raise RuntimeError(
f"training block {block!r} is assigned to test in finetune splits"
)
if len(assignments) > 1:
raise RuntimeError(
f"flight block {block!r} crosses train and validation in "
"finetune splits"
)
if assignments == {"val"}:
fixed_validation.append(block)
elif not assignments:
unassigned.append(block)
total_frames = sum(frame_counts.values())
fixed_frames = sum(
frame_counts[clip] for block in fixed_validation for clip in block
)
candidates = []
for mask in range(1 << len(unassigned)):
val_frames = fixed_frames + sum(
sum(frame_counts[clip] for clip in block)
for index, block in enumerate(unassigned)
if mask & (1 << index)
)
if (
MIN_VALIDATION_PERCENTAGE * total_frames
<= 100 * val_frames
<= MAX_VALIDATION_PERCENTAGE * total_frames
):
candidates.append(mask)
if not candidates:
raise RuntimeError(
"no assignment of target-only flight blocks puts validation "
f"between {MIN_VALIDATION_PERCENTAGE}% and "
f"{MAX_VALIDATION_PERCENTAGE}% of frames"
)
selected_mask = rng.choice(candidates)
selected = fixed_validation + [
block
for index, block in enumerate(unassigned)
if selected_mask & (1 << index)
]
return selected
def main():
args = parse_args()
root = args.data_root.resolve()
manifest = root / "samples.csv"
output = root / "splits.csv"
frames, clips = load_samples(manifest)
rng = random.Random(args.seed)
if args.finetune_split:
clip_splits, test_site = load_clip_splits(args.finetune_split.resolve())
else:
clip_splits = None
test_site = args.test
training_site = next(site for site in SITES if site != test_site)
blocks = make_flight_blocks(training_site, clips[training_site])
frame_counts = Counter(
clip for _, clip, site in frames if site == training_site
)
if clip_splits is None:
val_blocks = choose_validation_blocks(blocks, frame_counts, rng)
else:
val_blocks = transfer_validation_blocks(
blocks, frame_counts, clip_splits, rng
)
val_clips = {clip for block in val_blocks for clip in block}
target_only = []
if clip_splits is not None:
for site in SITES:
for clip in sorted(clips[site] - clip_splits.keys()):
if site == test_site:
split = "test"
elif clip in val_clips:
split = "val"
else:
split = "train"
target_only.append(f"{clip}={split}")
rows = []
for frame, clip, site in frames:
if site == test_site:
split = "test"
elif clip in val_clips:
split = "val"
else:
split = "train"
rows.append({"frame": frame, "split": split})
with output.open("w", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=("frame", "split"))
writer.writeheader()
writer.writerows(rows)
training_frames = sum(frame_counts.values())
val_frames = sum(frame_counts[clip] for clip in val_clips)
val_ratio = val_frames / training_frames
print(f"wrote {output}")
print(
f"{training_site}: {training_frames - val_frames} train and "
f"{val_frames} val frames ({val_ratio:.1%} val)"
)
test_frames = sum(1 for _, _, site in frames if site == test_site)
print(f"{test_site}: {test_frames} test frames")
if target_only:
print("target-only clips: " + ", ".join(target_only))
if __name__ == "__main__":
main()