Download Scripts/iasset_embeddings_analysis.py from moiaraya/I-AsSET: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/iasset_embeddings_analysis.py
- Command line
-
hf download hf://datasets/moiaraya/I-AsSET/Scripts/iasset_embeddings_analysis.py
-
curl -L -o iasset_embeddings_analysis.py https://huggingface.co/datasets/moiaraya/I-AsSET/resolve/main/Scripts/iasset_embeddings_analysis.py
17.2 kB
| #!/usr/bin/env python3 | |
| """Domain-gap analysis for IASSET (real test set vs. synthetic training sets). | |
| Stages | |
| features : image index + ImageHash bits + DINOv2 + Inception(pool3) embeddings | |
| metrics : synthetic-vs-real similarity metrics (long-format CSV) | |
| reduce : offline PCA / t-SNE / UMAP projections (CSV per feature and method) | |
| all : runs the three stages in order | |
| Example | |
| python iasset_analysis.py all --root /media/rtx5090/IASSET --out results | |
| """ | |
| import argparse | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image | |
| from tqdm import tqdm | |
| import torch | |
| from torch.utils.data import DataLoader | |
| from torch.utils.data import Dataset | |
| IMG_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"} | |
| # Sub-folders that never contain RGB renderings (adjust if your layout differs) | |
| SKIP_DIRS = {"depth", "labels", "annotations", "mask", "masks", "segmentation", "normals", "instance"} | |
| SKIP_DATASETS = {"IRIS_Test_Remapped"} | |
| HASH_SIZES = {"ahash": [8, 16, 32], "phash": [8, 16, 32], "dhash": [8, 16, 32], | |
| "whash": [8, 16, 32], "colorhash": [3, 4, 5]} # colorhash: binbits | |
| THUMB = 512 # images are downscaled (longest side) before hashing, for speed | |
| class ImageDataset(Dataset): | |
| def __init__(self, paths, tf): | |
| self.paths = paths | |
| self.tf = tf | |
| def __len__(self): | |
| return len(self.paths) | |
| def __getitem__(self, i): | |
| with Image.open(self.paths[i]) as img: | |
| img = img.convert("RGB") | |
| return self.tf(img) | |
| # --------------------------------------------------------------------------- index | |
| def list_images(folder: Path): | |
| if not folder.is_dir(): | |
| print(f"[warn] missing folder: {folder}") | |
| return [] | |
| out = [] | |
| for p in sorted(folder.rglob("*")): | |
| parents = {q.lower() for q in p.relative_to(folder).parts[:-1]} | |
| if p.suffix.lower() in IMG_EXT and not (parents & SKIP_DIRS): | |
| out.append(p) | |
| return out | |
| def build_index(root: Path, max_per_set, seed): | |
| sets = [("REAL", "Real", "real", root / "Real_Test_Set" / "images" / "full" / "rgb")] | |
| synth = root / "Synthetic_Train_Sets" | |
| for g in sorted(p for p in synth.iterdir() if p.is_dir()): | |
| for d in sorted(p for p in g.iterdir() if p.is_dir() and p.name not in SKIP_DATASETS): | |
| sets.append((f"{g.name}/{d.name}", g.name, "synthetic", d)) | |
| rng = np.random.default_rng(seed) | |
| rows = [] | |
| for name, group, domain, folder in sets: | |
| files = list_images(folder) | |
| if max_per_set and len(files) > max_per_set: | |
| files = [files[i] for i in sorted(rng.choice(len(files), max_per_set, replace=False))] | |
| print(f"{name:75s} {len(files):6d} images") | |
| rows += [(name, group, domain, str(f)) for f in files] | |
| df = pd.DataFrame(rows, columns=["dataset", "group", "domain", "path"]) | |
| df.insert(0, "image_id", np.arange(len(df))) | |
| return df | |
| def get_index(a): | |
| out = Path(a.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| f = out / "index.csv" | |
| if f.exists() and not a.overwrite: | |
| return pd.read_csv(f) | |
| df = build_index(Path(a.root), a.max_per_set, a.seed) | |
| df.to_csv(f, index=False) | |
| return df | |
| # --------------------------------------------------------------------------- hashes | |
| def _hash_one(path): | |
| import imagehash | |
| img = Image.open(path).convert("RGB") | |
| img.thumbnail((THUMB, THUMB), Image.LANCZOS) | |
| fn = {"ahash": imagehash.average_hash, "phash": imagehash.phash, | |
| "dhash": imagehash.dhash, "whash": imagehash.whash} | |
| out = {} | |
| for t, sizes in HASH_SIZES.items(): | |
| for s in sizes: | |
| h = imagehash.colorhash(img, binbits=s) if t == "colorhash" else fn[t](img, hash_size=s) | |
| out[f"hash_{t}_{s}"] = h.hash.flatten().astype(np.uint8) | |
| return out | |
| def run_hashes(paths, feat_dir, a): | |
| with ProcessPoolExecutor(a.workers) as ex: | |
| res = list(tqdm(ex.map(_hash_one, paths, chunksize=16), total=len(paths), desc="hashes")) | |
| hex_cols = {} | |
| for key in res[0]: | |
| arr = np.stack([r[key] for r in res]) # (N, n_bits), uint8 bits | |
| np.save(feat_dir / f"{key}.npy", arr) | |
| hex_cols[key] = [np.packbits(r).tobytes().hex() for r in arr] | |
| df = pd.DataFrame(hex_cols) | |
| df.insert(0, "image_id", np.arange(len(paths))) | |
| df.to_csv(feat_dir.parent / "hashes.csv", index=False) | |
| # --------------------------------------------------------------------------- deep encoders | |
| def _tf(size, mean, std, crop): | |
| from torchvision import transforms as T | |
| bic = T.InterpolationMode.BICUBIC | |
| steps = ([T.Resize((size, size), interpolation=bic)] if crop == "none" | |
| else [T.Resize(int(size * 256 / 224), interpolation=bic), T.CenterCrop(size)]) | |
| return T.Compose(steps + [T.ToTensor(), T.Normalize(mean, std)]) | |
| def load_dinov2(size, a): | |
| from transformers import AutoModel | |
| m = AutoModel.from_pretrained(f"facebook/dinov2-{size}").to(a.device).eval() | |
| def fwd(x): | |
| h = m(pixel_values=x).last_hidden_state | |
| return {f"dinov2_{size}_cls": h[:, 0], f"dinov2_{size}_patchmean": h[:, 1:].mean(1)} | |
| return fwd, _tf(224, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), a.crop) | |
| def load_inception(a): | |
| from pytorch_fid.inception import InceptionV3 | |
| from torchvision import transforms as T | |
| m = InceptionV3([InceptionV3.BLOCK_INDEX_BY_DIM[2048]]).to(a.device).eval() | |
| tf = T.Compose([T.Resize((299, 299)), T.ToTensor()]) # model expects [0, 1] | |
| return (lambda x: {"inception_pool3": m(x)[0].squeeze(-1).squeeze(-1)}), tf | |
| def extract(paths, fwd, tf, a): | |
| acc = {} | |
| dl = DataLoader( | |
| ImageDataset(paths, tf), | |
| batch_size=a.batch_size, | |
| num_workers=a.workers, | |
| pin_memory=(a.device.startswith("cuda")), | |
| persistent_workers=(a.workers > 0), | |
| ) | |
| with torch.no_grad(), torch.autocast( | |
| "cuda", | |
| dtype=torch.float16, | |
| enabled=(a.fp16 and a.device.startswith("cuda")), | |
| ): | |
| for x in tqdm(dl, desc="encode"): | |
| x = x.to(a.device, non_blocking=True) | |
| for k, v in fwd(x).items(): | |
| acc.setdefault(k, []).append(v.float().cpu()) | |
| return { | |
| k: torch.cat(v).numpy() | |
| for k, v in acc.items() | |
| } | |
| def save_deep(feat_dir, feats, a): | |
| for k, arr in feats.items(): | |
| np.save(feat_dir / f"{k}.npy", arr) | |
| if a.csv_deep: | |
| df = pd.DataFrame(arr, columns=[f"d{i}" for i in range(arr.shape[1])]) | |
| df.insert(0, "image_id", np.arange(len(arr))) | |
| df.to_csv(feat_dir / f"{k}.csv", index=False) | |
| def stage_features(a): | |
| idx = get_index(a) | |
| paths = idx.path.tolist() | |
| fd = Path(a.out) / "features" | |
| fd.mkdir(exist_ok=True) | |
| if "hash" in a.encoders: | |
| keys = [f"hash_{t}_{s}" for t, ss in HASH_SIZES.items() for s in ss] | |
| if a.overwrite or not all((fd / f"{k}.npy").exists() for k in keys): | |
| run_hashes(paths, fd, a) | |
| jobs = [] | |
| if "dinov2" in a.encoders: | |
| for size in a.dinov2_sizes: | |
| names = [f"dinov2_{size}_cls", f"dinov2_{size}_patchmean"] | |
| jobs.append((names, lambda size=size: load_dinov2(size, a))) | |
| if "inception" in a.encoders: | |
| jobs.append((["inception_pool3"], lambda: load_inception(a))) | |
| for names, loader in jobs: | |
| if not a.overwrite and all((fd / f"{n}.npy").exists() for n in names): | |
| continue | |
| fwd, tf = loader() | |
| save_deep(fd, extract(paths, fwd, tf, a), a) | |
| # --------------------------------------------------------------------------- metrics | |
| def _offd(D): | |
| n = D.shape[0] | |
| return (D.sum() - D.diagonal().sum()) / (n * (n - 1)) | |
| def _mmd_u(Kxx, Kyy, Kxy): | |
| """Unbiased MMD^2 (Gretton et al., 2012).""" | |
| return _offd(Kxx) + _offd(Kyy) - 2 * Kxy.mean() | |
| def _dists(X, Y, kind): | |
| import torch | |
| import torch.nn.functional as F | |
| if kind == "hash": # normalized Hamming distance on bit vectors | |
| d = X.shape[1] | |
| f = lambda A, B: (d - (A @ B.T + (1 - A) @ (1 - B).T)) / d | |
| else: # Euclidean on L2-normalized vectors (monotone in cosine distance) | |
| X, Y = F.normalize(X, dim=1), F.normalize(Y, dim=1) | |
| f = torch.cdist | |
| return f(X, X), f(Y, Y), f(X, Y) | |
| def _generic(Dxx, Dyy, Dxy, kernel, k): | |
| import torch | |
| sig = Dxy.median().clamp_min(1e-8) | |
| # Kernel functions. | |
| if kernel == "gauss": | |
| K = lambda D: torch.exp(-D ** 2 / (2 * sig ** 2)) | |
| else: | |
| K = lambda D: torch.exp(-D / sig) | |
| # Adapt k to the available number of samples. | |
| kx = min(k, Dxx.shape[0] - 1) | |
| ky = min(k, Dyy.shape[0] - 1) | |
| # k-NN radii, excluding each sample itself. | |
| rx = Dxx.topk(kx + 1, largest=False).values[:, -1] | |
| ry = Dyy.topk(ky + 1, largest=False).values[:, -1] | |
| # Determine which cross-domain samples lie within each radius. | |
| inx = Dxy <= rx[:, None] | |
| iny = Dxy <= ry[None, :] | |
| return { | |
| "mean_cross_dist": Dxy.mean(), | |
| "energy": ( | |
| 2 * Dxy.mean() | |
| - _offd(Dxx) | |
| - _offd(Dyy) | |
| ), | |
| "mmd_rbf": _mmd_u( | |
| K(Dxx), | |
| K(Dyy), | |
| K(Dxy), | |
| ), | |
| "precision": inx.any(0).float().mean(), | |
| "recall": iny.any(1).float().mean(), | |
| "density": inx.float().sum() / (kx * Dxy.shape[1]), | |
| "coverage": inx.any(1).float().mean(), | |
| } | |
| def _kid(X, Y): | |
| """Unbiased MMD^2 with cubic polynomial kernel (Binkowski et al., 2018).""" | |
| X, Y = X.double(), Y.double() | |
| d = X.shape[1] | |
| k = lambda A, B: (A @ B.T / d + 1) ** 3 | |
| return _mmd_u(k(X, X), k(Y, Y), k(X, Y)) | |
| def _frechet(x, y): | |
| mu1, mu2 = x.mean(0), y.mean(0) | |
| s1, s2 = np.cov(x, rowvar=False), np.cov(y, rowvar=False) | |
| w, v = np.linalg.eigh(s1) | |
| r1 = (v * np.sqrt(np.clip(w, 0, None))) @ v.T | |
| tr = np.sqrt(np.clip(np.linalg.eigvalsh(r1 @ s2 @ r1), 0, None)).sum() | |
| return float(((mu1 - mu2) ** 2).sum() + np.trace(s1) + np.trace(s2) - 2 * tr) | |
| def _compare(F, kind, xi, yi, a, rng): | |
| """X = reference (real), Y = candidate (synthetic). Returns {metric: (mean, std)}.""" | |
| import torch | |
| import torch.nn.functional as Fn | |
| n, m = len(xi), len(yi) | |
| s = min(n, m, a.subset_size) | |
| reps = 1 if (s == n and s == m) else a.repeats | |
| acc = {} | |
| for _ in range(reps): | |
| X = F[torch.as_tensor(rng.choice(xi, s, replace=False))] | |
| Y = F[torch.as_tensor(rng.choice(yi, s, replace=False))] | |
| res = _generic(*_dists(X, Y, kind), "lap" if kind == "hash" else "gauss", a.k) | |
| if kind == "deep": | |
| res["kid"] = _kid(X, Y) | |
| for key, v in res.items(): | |
| acc.setdefault(key, []).append(float(v)) | |
| out = {k: (np.mean(v), np.std(v)) for k, v in acc.items()} | |
| out["n_used"] = (s, 0.0) | |
| if kind == "deep": # full-sample metrics | |
| X, Y = F[torch.as_tensor(xi)], F[torch.as_tensor(yi)] | |
| Xn, Yn = Fn.normalize(X, dim=1), Fn.normalize(Y, dim=1) | |
| out["centroid_cos"] = (1 - float(Fn.cosine_similarity(Xn.mean(0), Yn.mean(0), dim=0)), np.nan) | |
| out["allpairs_cos"] = (1 - float((Xn @ Yn.T).mean()), np.nan) | |
| out["fd"] = (_frechet(X.cpu().numpy().astype(np.float64), Y.cpu().numpy().astype(np.float64)), np.nan) | |
| return out | |
| def stage_metrics(a): | |
| import torch | |
| out = Path(a.out) | |
| idx = pd.read_csv(out / "index.csv") | |
| rng = np.random.default_rng(a.seed) | |
| real = idx.index[idx.domain == "real"].to_numpy() | |
| half = rng.permutation(real) | |
| pairs = [("REAL_vs_REAL_split", "Baseline", half[: len(half) // 2], half[len(half) // 2:])] | |
| for (name, group), g in idx[idx.domain == "synthetic"].groupby(["dataset", "group"]): | |
| pairs.append((name, group, real, g.index.to_numpy())) | |
| rows = [] | |
| for f in sorted((out / "features").glob("*.npy")): | |
| if a.only and not any(o in f.stem for o in a.only): | |
| continue | |
| kind = "hash" if f.stem.startswith("hash_") else "deep" | |
| F = torch.tensor(np.load(f), dtype=torch.float32, device=a.device) | |
| for name, group, xi, yi in tqdm(pairs, desc=f.stem): | |
| for metric, (mu, sd) in _compare(F, kind, xi, yi, a, rng).items(): | |
| rows.append((f.stem, name, group, len(xi), len(yi), metric, mu, sd)) | |
| cols = ["feature", "dataset", "group", "n_ref", "n_cand", "metric", "mean", "std"] | |
| pd.DataFrame(rows, columns=cols).to_csv(out / "metrics_long.csv", index=False) | |
| # --------------------------------------------------------------------------- reduction | |
| def sample_ids(idx, datasets, n_per_set, seed=0): | |
| rng = np.random.default_rng(seed) | |
| ids = [rng.choice(g.index.values, min(len(g), n_per_set), replace=False) | |
| for name, g in idx[idx.dataset.isin(datasets)].groupby("dataset")] | |
| return np.sort(np.concatenate(ids)) if ids else np.array([], dtype=int) | |
| def reduce_features(X, kind, method, nc=2, pre_dims=50, pre_mode="pca", | |
| perplexity=30.0, n_neighbors=15, min_dist=0.1, seed=0): | |
| """Project (n, d) features to nc dimensions. pre_mode: 'pca' | 'truncate' | 'none'.""" | |
| from sklearn.decomposition import PCA | |
| X = np.asarray(X, dtype=np.float32) | |
| metric = "euclidean" | |
| if kind == "hash": | |
| metric = "hamming" # t-SNE / UMAP operate directly on the bits | |
| else: | |
| X = X / np.linalg.norm(X, axis=1, keepdims=True).clip(1e-12) | |
| if pre_mode != "none" and pre_dims < X.shape[1]: | |
| X = X[:, :pre_dims] if pre_mode == "truncate" else PCA(pre_dims, random_state=seed).fit_transform(X) | |
| method = method.lower().replace("-", "") | |
| if method == "pca": | |
| return PCA(nc, random_state=seed).fit_transform(X) | |
| if method == "tsne": | |
| from sklearn.manifold import TSNE | |
| return TSNE(nc, perplexity=min(perplexity, (len(X) - 1) / 3), init="pca", metric=metric, | |
| learning_rate="auto", random_state=seed).fit_transform(X) | |
| if method == "umap": | |
| import umap | |
| return umap.UMAP( | |
| n_components=nc, | |
| n_neighbors=n_neighbors, | |
| min_dist=min_dist, | |
| metric=metric, | |
| random_state=seed, | |
| ).fit_transform(X) | |
| raise ValueError(method) | |
| def stage_reduce(a): | |
| out = Path(a.out) | |
| rd = out / "reductions" | |
| rd.mkdir(exist_ok=True) | |
| idx = pd.read_csv(out / "index.csv") | |
| ids = sample_ids(idx, idx.dataset.unique(), a.reduce_per_set, a.seed) | |
| for f in sorted((out / "features").glob("*.npy")): | |
| if a.only and not any(o in f.stem for o in a.only): | |
| continue | |
| kind = "hash" if f.stem.startswith("hash_") else "deep" | |
| X = np.load(f, mmap_mode="r")[ids] | |
| for method in a.methods: | |
| for nc in a.dims: | |
| Z = reduce_features(X, kind, method, nc, a.pre_dims, seed=a.seed) | |
| df = pd.DataFrame(Z, columns=[f"c{i + 1}" for i in range(nc)]) | |
| df.insert(0, "image_id", ids) | |
| df.to_csv(rd / f"{f.stem}__{method}_{nc}d.csv", index=False) | |
| print("saved", f.stem, method, nc) | |
| # --------------------------------------------------------------------------- CLI | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("stage", choices=["features", "metrics", "reduce", "all"]) | |
| p.add_argument("--root", default="/media/rtx5090/IASSET") | |
| p.add_argument("--out", default="results") | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--overwrite", action="store_true") | |
| p.add_argument("--only", nargs="*", help="restrict metrics/reduce to features containing these substrings") | |
| g = p.add_argument_group("features") | |
| g.add_argument("--encoders", nargs="+", default=["hash", "dinov2", "inception"]) | |
| g.add_argument("--dinov2-sizes", nargs="+", default=["base"], choices=["small", "base", "large", "giant"]) | |
| g.add_argument("--crop", choices=["center", "none"], default="center", | |
| help="center: resize 256 + center-crop 224; none: squash to 224x224") | |
| g.add_argument("--max-per-set", type=int, default=0, help="0 = all images") | |
| g.add_argument("--batch-size", type=int, default=64) | |
| g.add_argument("--workers", type=int, default=8) | |
| g.add_argument("--device", default="cuda") | |
| g.add_argument("--fp16", action="store_true") | |
| g.add_argument("--csv-deep", action="store_true", help="also write deep features as CSV (large)") | |
| g = p.add_argument_group("metrics") | |
| g.add_argument("--subset-size", type=int, default=1000) | |
| g.add_argument("--repeats", type=int, default=10) | |
| g.add_argument("--k", type=int, default=5) | |
| g = p.add_argument_group("reduce") | |
| g.add_argument("--methods", nargs="+", default=["pca", "tsne", "umap"]) | |
| g.add_argument("--dims", nargs="+", type=int, default=[2, 3]) | |
| g.add_argument("--pre-dims", type=int, default=50) | |
| g.add_argument("--reduce-per-set", type=int, default=500) | |
| a = p.parse_args() | |
| if a.stage in ("features", "all"): | |
| stage_features(a) | |
| if a.stage in ("metrics", "all"): | |
| stage_metrics(a) | |
| if a.stage in ("reduce", "all"): | |
| stage_reduce(a) | |
| if __name__ == "__main__": | |
| main() | |