Download eda.py from duyle2408/milk10k_new_code: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/datasets/duyle2408/milk10k_new_code/resolve/main/eda.py
- Command line
-
hf download hf://datasets/duyle2408/milk10k_new_code/eda.py
-
curl -L -o eda.py https://huggingface.co/datasets/duyle2408/milk10k_new_code/resolve/main/eda.py
13.8 kB
| #!/usr/bin/env python3 | |
| """Reproducible EDA for the unlabeled image-to-image retrieval dataset.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import tempfile | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| import cv2 | |
| os.environ.setdefault("MPLCONFIGDIR", str(Path(tempfile.gettempdir()) / "matplotlib-cache")) | |
| import matplotlib | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image, ImageDraw, ImageOps | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt # noqa: E402 | |
| MANIFESTS = { | |
| "train": "train_unlabeled.json", | |
| "gallery": "public_test/public_test/gallery.json", | |
| "query": "public_test/public_test/queries.json", | |
| } | |
| PLOT_METRICS = [ | |
| "luminance_mean", | |
| "luminance_std", | |
| "blur_laplacian_var", | |
| "entropy", | |
| "high_frequency_energy", | |
| "near_black_ratio", | |
| "edge_density", | |
| ] | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data-root", type=Path, default=Path("data/dataset2")) | |
| parser.add_argument("--output-dir", type=Path, default=Path("eda_output")) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--grid-size", type=int, default=48) | |
| return parser.parse_args() | |
| def load_manifest(path: Path) -> list[dict[str, str]]: | |
| with path.open(encoding="utf-8") as handle: | |
| rows = json.load(handle) | |
| if not isinstance(rows, list): | |
| raise ValueError("manifest root must be a JSON list") | |
| for index, row in enumerate(rows): | |
| if not isinstance(row, dict) or not isinstance(row.get("image_id"), str) or not isinstance(row.get("image_path"), str): | |
| raise ValueError(f"row {index} must contain string image_id and image_path") | |
| return rows | |
| def resolve_image(data_root: Path, manifest: Path, relative: str) -> Path: | |
| rel = Path(relative) | |
| candidates = [ | |
| data_root / rel, | |
| manifest.parent / rel, | |
| manifest.parent.parent / rel, | |
| ] | |
| for candidate in candidates: | |
| if candidate.is_file(): | |
| return candidate.resolve() | |
| return candidates[0].resolve() | |
| def sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def image_metrics(rgb: np.ndarray) -> dict[str, float]: | |
| gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) | |
| histogram = np.bincount(gray.ravel(), minlength=256).astype(np.float64) | |
| probabilities = histogram[histogram > 0] / gray.size | |
| blurred = cv2.GaussianBlur(gray, (0, 0), 1.0) | |
| edges = cv2.Canny(gray, 50, 150) | |
| return { | |
| "luminance_mean": float(gray.mean()), | |
| "luminance_std": float(gray.std()), | |
| "red_mean": float(rgb[..., 0].mean()), | |
| "red_std": float(rgb[..., 0].std()), | |
| "green_mean": float(rgb[..., 1].mean()), | |
| "green_std": float(rgb[..., 1].std()), | |
| "blue_mean": float(rgb[..., 2].mean()), | |
| "blue_std": float(rgb[..., 2].std()), | |
| "blur_laplacian_var": float(cv2.Laplacian(gray, cv2.CV_64F).var()), | |
| "entropy": float(-(probabilities * np.log2(probabilities)).sum()), | |
| "high_frequency_energy": float(np.mean(np.abs(gray.astype(np.float32) - blurred.astype(np.float32)))), | |
| "near_black_ratio": float(np.mean(np.all(rgb < 10, axis=2))), | |
| "edge_density": float(np.mean(edges > 0)), | |
| } | |
| def inspect_dataset(data_root: Path) -> tuple[pd.DataFrame, dict, list[str]]: | |
| records: list[dict] = [] | |
| integrity: dict = {"splits": {}, "hash_groups": {}} | |
| problems: list[str] = [] | |
| hashes: defaultdict[str, list[str]] = defaultdict(list) | |
| for split, relative_manifest in MANIFESTS.items(): | |
| manifest = data_root / relative_manifest | |
| rows = load_manifest(manifest) | |
| ids = [row["image_id"] for row in rows] | |
| paths = [row["image_path"] for row in rows] | |
| split_info = { | |
| "rows": len(rows), | |
| "unique_ids": len(set(ids)), | |
| "unique_manifest_paths": len(set(paths)), | |
| "duplicate_ids": sorted(key for key, count in Counter(ids).items() if count > 1), | |
| "duplicate_manifest_paths": sorted(key for key, count in Counter(paths).items() if count > 1), | |
| "missing": [], | |
| "broken": [], | |
| } | |
| integrity["splits"][split] = split_info | |
| for row in rows: | |
| path = resolve_image(data_root, manifest, row["image_path"]) | |
| if not path.is_file(): | |
| split_info["missing"].append(str(path)) | |
| problems.append(f"missing: {path}") | |
| continue | |
| try: | |
| with Image.open(path) as image: | |
| image.load() | |
| mode, image_format, size = image.mode, image.format, image.size | |
| rgb = np.asarray(image.convert("RGB")) | |
| digest = sha256(path) | |
| hashes[digest].append(f"{split}:{row['image_id']}") | |
| records.append( | |
| { | |
| "split": split, | |
| "image_id": row["image_id"], | |
| "manifest_path": row["image_path"], | |
| "resolved_path": str(path), | |
| "sha256": digest, | |
| "format": image_format, | |
| "mode": mode, | |
| "width": size[0], | |
| "height": size[1], | |
| "file_size_bytes": path.stat().st_size, | |
| **image_metrics(rgb), | |
| } | |
| ) | |
| except Exception as exc: # report corrupt/unsupported images and continue | |
| message = f"{path}: {type(exc).__name__}: {exc}" | |
| split_info["broken"].append(message) | |
| problems.append(f"broken: {message}") | |
| if split_info["duplicate_ids"]: | |
| problems.append(f"{split}: duplicate image_id values") | |
| if split_info["duplicate_manifest_paths"]: | |
| problems.append(f"{split}: duplicate image_path values") | |
| integrity["hash_groups"] = {digest: items for digest, items in hashes.items() if len(items) > 1} | |
| return pd.DataFrame(records), integrity, problems | |
| def create_summary(metrics: pd.DataFrame) -> pd.DataFrame: | |
| numeric = [ | |
| "width", "height", "file_size_bytes", *PLOT_METRICS, | |
| "red_mean", "red_std", "green_mean", "green_std", "blue_mean", "blue_std", | |
| ] | |
| return metrics.groupby("split")[numeric].agg(["count", "mean", "std", "min", "median", "max"]) | |
| def thumbnail(path: str, size: int = 128) -> Image.Image: | |
| with Image.open(path) as image: | |
| return ImageOps.fit(image.convert("RGB"), (size, size), method=Image.Resampling.LANCZOS) | |
| def save_grid(rows: pd.DataFrame, output: Path, title: str, limit: int = 48) -> None: | |
| rows = rows.head(limit) | |
| if rows.empty: | |
| return | |
| columns = min(8, len(rows)) | |
| item_width, image_size, label_height = 128, 128, 32 | |
| grid_rows = math.ceil(len(rows) / columns) | |
| canvas = Image.new("RGB", (columns * item_width, grid_rows * (image_size + label_height) + 28), "white") | |
| draw = ImageDraw.Draw(canvas) | |
| draw.text((6, 6), title, fill="black") | |
| for index, (_, row) in enumerate(rows.iterrows()): | |
| x = (index % columns) * item_width | |
| y = 28 + (index // columns) * (image_size + label_height) | |
| canvas.paste(thumbnail(row["resolved_path"], image_size), (x, y)) | |
| draw.text((x + 2, y + image_size + 2), str(row["image_id"])[:20], fill="black") | |
| draw.text((x + 2, y + image_size + 16), str(row["split"]), fill="black") | |
| canvas.save(output, quality=92) | |
| def save_grids(metrics: pd.DataFrame, output_dir: Path, seed: int, grid_size: int) -> None: | |
| for split in MANIFESTS: | |
| subset = metrics[metrics["split"] == split] | |
| sample = subset.sample(n=min(grid_size, len(subset)), random_state=seed) | |
| save_grid(sample, output_dir / f"grid_random_{split}.jpg", f"Random sample: {split}", grid_size) | |
| extremes = { | |
| "most_blurred": ("blur_laplacian_var", True), | |
| "most_noisy": ("high_frequency_energy", False), | |
| "darkest": ("luminance_mean", True), | |
| "brightest": ("luminance_mean", False), | |
| "most_near_black": ("near_black_ratio", False), | |
| } | |
| for name, (column, ascending) in extremes.items(): | |
| ordered = metrics.sort_values([column, "image_id"], ascending=[ascending, True]) | |
| save_grid(ordered, output_dir / f"grid_{name}.jpg", name.replace("_", " ").title(), grid_size) | |
| def save_distributions(metrics: pd.DataFrame, output: Path) -> None: | |
| figure, axes = plt.subplots(3, 3, figsize=(15, 12)) | |
| axes = axes.ravel() | |
| colors = {"train": "#4C78A8", "gallery": "#F58518", "query": "#E45756"} | |
| for axis, metric in zip(axes, PLOT_METRICS): | |
| for split in MANIFESTS: | |
| values = metrics.loc[metrics["split"] == split, metric].dropna() | |
| axis.hist(values, bins=40, density=True, alpha=0.4, label=split, color=colors[split]) | |
| axis.set_title(metric.replace("_", " ")) | |
| axis.grid(alpha=0.2) | |
| for axis in axes[len(PLOT_METRICS):]: | |
| axis.axis("off") | |
| axes[0].legend() | |
| figure.suptitle("Image degradation metrics by split", fontsize=16) | |
| figure.tight_layout() | |
| figure.savefig(output, dpi=150) | |
| plt.close(figure) | |
| def write_integrity_report(path: Path, integrity: dict, problems: list[str]) -> None: | |
| lines = ["IMAGE RETRIEVAL DATASET INTEGRITY", "=" * 33] | |
| for split, info in integrity["splits"].items(): | |
| lines.extend( | |
| [ | |
| "", | |
| f"[{split}]", | |
| f"rows: {info['rows']}", | |
| f"unique_ids: {info['unique_ids']}", | |
| f"unique_manifest_paths: {info['unique_manifest_paths']}", | |
| f"missing: {len(info['missing'])}", | |
| f"broken: {len(info['broken'])}", | |
| f"duplicate_ids: {info['duplicate_ids'] or 'none'}", | |
| f"duplicate_manifest_paths: {info['duplicate_manifest_paths'] or 'none'}", | |
| ] | |
| ) | |
| lines.extend(["", "[exact duplicate SHA-256 groups]"]) | |
| if integrity["hash_groups"]: | |
| lines.extend(f"{digest}: {', '.join(items)}" for digest, items in integrity["hash_groups"].items()) | |
| else: | |
| lines.append("none") | |
| lines.extend(["", "[problems]", *(problems or ["none"])]) | |
| path.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| def write_markdown_report(path: Path, metrics: pd.DataFrame, integrity: dict) -> None: | |
| counts = metrics.groupby("split").size().to_dict() | |
| medians = metrics.groupby("split")[PLOT_METRICS].median().reindex(MANIFESTS) | |
| lines = [ | |
| "# Image retrieval EDA", | |
| "", | |
| "## Dataset", | |
| "", | |
| f"- Readable images: **{len(metrics):,}**.", | |
| *[f"- {split}: **{counts.get(split, 0):,}** images." for split in MANIFESTS], | |
| f"- Exact duplicate groups: **{len(integrity['hash_groups'])}**.", | |
| "", | |
| "## Median degradation metrics", | |
| "", | |
| medians.round(4).to_markdown(), | |
| "", | |
| "## Distribution shift: query versus train", | |
| "", | |
| ] | |
| for metric in PLOT_METRICS: | |
| train = medians.loc["train", metric] | |
| query = medians.loc["query", metric] | |
| delta = query - train | |
| relative = delta / abs(train) * 100 if train else float("nan") | |
| lines.append(f"- `{metric}`: {delta:+.4f} ({relative:+.1f}% of train median).") | |
| lines.extend( | |
| [ | |
| "", | |
| "## Retrieval implications", | |
| "", | |
| "- Large blur/noise shifts suggest matching augmentations for representation learning.", | |
| "- Near-black regions can represent rotation borders or occlusion; avoid treating them as scene content.", | |
| "- Inspect the extreme grids before choosing color, texture, or edge-sensitive descriptors.", | |
| "- This EDA does not infer labels or perform retrieval.", | |
| "", | |
| "See `distributions.png` and the `grid_*.jpg` files for visual evidence.", | |
| ] | |
| ) | |
| path.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| def main() -> int: | |
| args = parse_args() | |
| data_root = args.data_root.resolve() | |
| output_dir = args.output_dir.resolve() | |
| if args.grid_size < 1: | |
| print("error: --grid-size must be at least 1", file=sys.stderr) | |
| return 2 | |
| missing_manifests = [str(data_root / relative) for relative in MANIFESTS.values() if not (data_root / relative).is_file()] | |
| if missing_manifests: | |
| print("error: missing manifest(s):\n " + "\n ".join(missing_manifests), file=sys.stderr) | |
| return 2 | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| try: | |
| metrics, integrity, problems = inspect_dataset(data_root) | |
| except (OSError, json.JSONDecodeError, ValueError) as exc: | |
| print(f"error: invalid manifest: {exc}", file=sys.stderr) | |
| return 2 | |
| metrics.to_csv(output_dir / "image_metrics.csv", index=False) | |
| if not metrics.empty: | |
| create_summary(metrics).to_csv(output_dir / "summary.csv") | |
| save_grids(metrics, output_dir, args.seed, args.grid_size) | |
| save_distributions(metrics, output_dir / "distributions.png") | |
| write_markdown_report(output_dir / "report.md", metrics, integrity) | |
| write_integrity_report(output_dir / "integrity_report.txt", integrity, problems) | |
| print(f"EDA complete: {len(metrics):,} readable images -> {output_dir}") | |
| if problems: | |
| print(f"Integrity failed with {len(problems)} problem(s); see integrity_report.txt", file=sys.stderr) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |