evaladem 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
evaladem/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """evaladem: ADEM, the Anticipated Downstream Effect Metric. Training-free prediction of whether adding a candidate
2
+ image set to a trusted training set will improve a downstream model.
3
+
4
+ from evaladem import evaluate
5
+ r = evaluate("trusted/", "candidate/", output="evaladem_output")
6
+ r["adem"], r["add"] # the set score; True: add the candidate set
7
+
8
+ from evaladem import ADEM, represent
9
+ m = ADEM().fit(represent(trusted_images), trusted_labels)
10
+ m.set_score(represent(candidate_images), candidate_labels)["adem"]
11
+ m.image_scores(represent(candidate_images), candidate_labels)["phi"] # per image
12
+ """
13
+ __version__ = "0.1.0"
14
+
15
+ from .core import ADEM # noqa: E402
16
+ from .encoders import represent, represent_files # noqa: E402
17
+ from .data import load_folder, load_image # noqa: E402
18
+ from .api import evaluate # noqa: E402
19
+
20
+ __all__ = ["ADEM", "represent", "represent_files", "load_folder", "load_image", "evaluate", "__version__"]
evaladem/api.py ADDED
@@ -0,0 +1,79 @@
1
+ """evaluate(): score a candidate image folder against a trusted image folder, and optionally write the per-image
2
+ scores and the cleaned pool (the candidate images with phi(d) > 0, the paper's pool-cleaning rule)."""
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+ from . import __version__
13
+ from .core import ADEM, check_trusted
14
+ from .data import list_folder
15
+ from .encoders import default_device, represent_files
16
+
17
+
18
+ def evaluate(trusted, candidate, output=None, device=None, batch=64, pool=True, overwrite=False, log=print):
19
+ """ADEM(candidate, trusted). Returns a dict: ``adem`` (the set score), ``add`` (adem > 0), the set-score parts,
20
+ ``kept`` (the number of candidate images with phi(d) > 0) and ``images`` (one dict per candidate image: file,
21
+ label, r, q, u, phi, kept). With ``output``, also writes ``scores.csv``, ``summary.json`` and, unless
22
+ ``pool=False``, ``cleaned_pool/<label>/...`` (copies of the kept images); a non-empty ``output`` is refused unless
23
+ ``overwrite=True``, which replaces an earlier run's results there."""
24
+ log = log or (lambda *a, **k: None)
25
+ tr, cd = list_folder(trusted), list_folder(candidate)
26
+ yT, yD = np.array([c for _, c in tr]), np.array([c for _, c in cd])
27
+ check_trusted(yT) # before the encoders run
28
+ out = Path(output) if output is not None else None
29
+ if out is not None and out.exists() and any(out.iterdir()) and not overwrite:
30
+ raise FileExistsError(f"{out} exists and is not empty (choose another output folder, or --overwrite)")
31
+ unknown = sorted(set(yD) - set(yT))
32
+ log(f"trusted: {len(tr)} images, {len(set(yT))} classes ({trusted})")
33
+ log(f"candidate: {len(cd)} images, {len(set(yD))} classes ({candidate})")
34
+ if unknown:
35
+ log(f" note: candidate classes not in the trusted set count as wrong labels: {', '.join(unknown)}")
36
+ device = device or default_device()
37
+ log(f"working... (embedding {len(tr) + len(cd)} images on {device})")
38
+
39
+ def step(name):
40
+ return lambda i, n: log(f" {name}: {i}/{n}")
41
+
42
+ ZT = represent_files([f for f, _ in tr], batch=batch, device=device, progress=step("trusted"))
43
+ ZD = represent_files([f for f, _ in cd], batch=batch, device=device, progress=step("candidate"))
44
+ m = ADEM().fit(ZT, yT)
45
+ s = m.image_scores(ZD, yD)
46
+ res = m.set_score(ZD, yD, scores=s)
47
+ res["add"] = res["adem"] > 0
48
+ kept = s["phi"] > 0
49
+ root = Path(candidate)
50
+ res["images"] = [{"file": str(f), "label": c, "r": float(r), "q": float(q), "u": float(u), "phi": float(p),
51
+ "kept": bool(k)}
52
+ for (f, c), r, q, u, p, k in zip(cd, s["r"], s["q"], s["u"], s["phi"], kept)]
53
+ res["kept"] = int(kept.sum())
54
+ if out is not None:
55
+ out.mkdir(parents=True, exist_ok=True)
56
+ shutil.rmtree(out / "cleaned_pool", ignore_errors=True) # an earlier run's pool (overwrite=True)
57
+ with open(out / "scores.csv", "w", newline="") as fh:
58
+ w = csv.writer(fh)
59
+ w.writerow(["file", "label", "r_task_relevance", "q_label_correctness", "u_uniqueness", "phi_utility",
60
+ "kept"])
61
+ for d in res["images"]:
62
+ w.writerow([d["file"], d["label"], f"{d['r']:.6f}", f"{d['q']:.6f}", f"{d['u']:.6f}",
63
+ f"{d['phi']:.6f}", int(d["kept"])])
64
+ summary = {k: v for k, v in res.items() if k != "images"}
65
+ summary.update({"evaladem": __version__, "trusted": str(trusted), "candidate": str(candidate),
66
+ "trusted_images": len(tr), "candidate_images": len(cd),
67
+ "settings": {"k": m.k, "alpha": m.alpha, "theta": m.theta, "mu": m.mu,
68
+ "h_fraction": m.h_fraction, "prior_correction": m.prior_correction},
69
+ "fitted_on_T": {"probe_C": m.C_probe, "temperature": m.tau, "h": m.h,
70
+ "lambda_T": m.lambda_T}})
71
+ (out / "summary.json").write_text(json.dumps(summary, indent=2))
72
+ if pool:
73
+ dst = out / "cleaned_pool"
74
+ for (f, _), k in zip(cd, kept):
75
+ if k:
76
+ t = dst / f.relative_to(root)
77
+ t.parent.mkdir(parents=True, exist_ok=True)
78
+ shutil.copy2(f, t)
79
+ return res
evaladem/cli.py ADDED
@@ -0,0 +1,53 @@
1
+ """evaladem --trusted DIR --candidate DIR [--output DIR]: will adding the candidate images help a model trained on the
2
+ trusted images? Prints ADEM(candidate, trusted) and its decision, and writes the per-image scores and the cleaned pool
3
+ (the candidate images with phi(d) > 0)."""
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+
12
+
13
+ def main(argv=None):
14
+ ap = argparse.ArgumentParser(
15
+ prog="evaladem",
16
+ description="Training-free prediction of whether adding a candidate image set to a trusted training set "
17
+ "will improve a model trained on it (ADEM). Both folders hold one sub-folder per class.")
18
+ ap.add_argument("--trusted", required=True, help="trusted (correctly labeled) images: TRUSTED/<class>/<image>")
19
+ ap.add_argument("--candidate", required=True, help="candidate images: CANDIDATE/<class>/<image>")
20
+ ap.add_argument("--output", default="evaladem_output",
21
+ help="folder for scores.csv, summary.json and cleaned_pool/ (default: %(default)s)")
22
+ ap.add_argument("--no-pool", action="store_true", help="do not copy the kept images to OUTPUT/cleaned_pool")
23
+ ap.add_argument("--overwrite", action="store_true",
24
+ help="write into a non-empty output folder, replacing an earlier run's results")
25
+ ap.add_argument("--device", help="torch device, e.g. cuda, cuda:1 or cpu (default: cuda if available)")
26
+ ap.add_argument("--batch", type=int, default=64, help="images per encoder batch (default: %(default)s)")
27
+ ap.add_argument("--version", action="version", version=f"evaladem {__version__}")
28
+ a = ap.parse_args(argv)
29
+ if a.batch < 1:
30
+ ap.error("--batch must be at least 1")
31
+ from .api import evaluate
32
+
33
+ try:
34
+ r = evaluate(a.trusted, a.candidate, output=a.output, device=a.device, batch=a.batch,
35
+ pool=not a.no_pool, overwrite=a.overwrite)
36
+ except (OSError, ValueError) as e: # a missing or unreadable folder or image, a non-empty output, too small a T
37
+ print(f"evaladem: {e}", file=sys.stderr)
38
+ return 2
39
+ n, out = len(r["images"]), Path(a.output)
40
+ print(f"\nADEM = {r['adem']:+.4f} -> {'add the candidate set' if r['add'] else 'do not add the candidate set'}")
41
+ print(f" worth {max(r['new_correct_images'], 0.0):.1f} new, correctly labeled images; "
42
+ f"{r['expected_wrong_labels']:.1f} expected wrong labels (share of correct labels {r['lambda']:.0%}); "
43
+ f"{100 * r['task_irrelevant_share']:.0f}% task-irrelevant")
44
+ if a.no_pool:
45
+ print(f" {r['kept']} of {n} candidate images have phi(d) > 0")
46
+ else:
47
+ print(f"cleaned pool: the {r['kept']} of {n} candidate images with phi(d) > 0 -> {out / 'cleaned_pool'}")
48
+ print(f"per-image scores -> {out / 'scores.csv'}; set score and settings -> {out / 'summary.json'}")
49
+ return 0
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
evaladem/core.py ADDED
@@ -0,0 +1,199 @@
1
+ """ADEM, the Anticipated Downstream Effect Metric: will adding a candidate image set D to a trusted set T improve a
2
+ model trained on T? Training-free; every quantity is computed against T alone. Notation as in the paper.
3
+
4
+ Each candidate image d (label y(d)) gets three image-level properties:
5
+
6
+ r(d) task relevance min(1, p(d) / alpha), p(d) the conformal p-value of its mean similarity to its k nearest
7
+ trusted images, ranked among the trusted images' own leave-one-out values (Eqs. 4-6)
8
+ q(d) label correctness the probability that its label is right (Eq. 8): a linear probe on T's low-pass views
9
+ gives l(d) (with T's class prior removed, Eq. 7), and the share of correct labels lambda
10
+ of D is estimated by EM (Eq. 9); a single image uses lambda_T, T's own estimate
11
+ u(d) uniqueness (1 - kappa_max(d)) / m(d): the part of d not covered by T, shared among its near-copies
12
+ in D (Eqs. 10-12)
13
+
14
+ and an image utility in units of one new, correctly labeled image (Eq. 13):
15
+
16
+ phi(d) = r q u - theta r (1 - q) - mu (1 - r), theta = 3, mu = 1/2
17
+
18
+ The set score sums each part per class c (Eq. 14):
19
+
20
+ ADEM(D, T) = (1 / C) sum_c [ log(1 + Phi_c1 / N_c^T) - (Phi_c2 + Phi_c3) / (N_c^T + N_c^D) ]
21
+
22
+ with Phi_c1 = sum of r q u, Phi_c2 = theta * sum of r (1 - q), Phi_c3 = mu * sum of (1 - r) over D's images of
23
+ class c. ADEM > 0: add D; ADEM <= 0: do not add. A candidate whose label T does not have gets l(d) = 0 (so q = 0
24
+ and u = 0) and counts in the set score as a wrong label, spread over the classes.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import numpy as np
29
+
30
+ CLIP_DIM, DINO_DIM = 512, 384
31
+ # Z = [clip raw, dino raw, clip low-pass, dino low-pass] (Eq. 2); the label probe reads the last VIEWS columns, the
32
+ # low-pass views
33
+ VIEWS = CLIP_DIM + DINO_DIM
34
+
35
+
36
+ def unit(Z):
37
+ """Rows scaled to unit length."""
38
+ Z = np.asarray(Z, np.float32)
39
+ return Z / np.maximum(np.linalg.norm(Z, axis=1, keepdims=True), 1e-12)
40
+
41
+
42
+ def check_trusted(y):
43
+ """Raise ValueError unless the trusted labels y have at least two classes and at least two images per class."""
44
+ _, n = np.unique(np.asarray(y), return_counts=True)
45
+ if len(n) < 2 or n.min() < 2:
46
+ raise ValueError("the trusted set needs at least two classes and at least two images per class")
47
+
48
+
49
+ def _topk_mean(S, k):
50
+ """Row-wise mean of the k largest entries, ignoring -inf (a leave-one-out hole)."""
51
+ k = int(min(max(k, 1), S.shape[1]))
52
+ top = -np.partition(-S, k - 1, axis=1)[:, :k]
53
+ fin = np.isfinite(top)
54
+ return np.where(fin, top, 0).sum(1) / np.maximum(fin.sum(1), 1)
55
+
56
+
57
+ def _log_softmax(X):
58
+ X = X - X.max(1, keepdims=True)
59
+ return X - np.log(np.exp(X).sum(1, keepdims=True))
60
+
61
+
62
+ def _logits(model, X):
63
+ """Class logits of a fitted scikit-learn linear model (a two-class model returns one column)."""
64
+ s = model.decision_function(X)
65
+ return np.c_[-s / 2, s / 2] if s.ndim == 1 else s
66
+
67
+
68
+ class ADEM:
69
+ """``fit`` on the trusted set T, then ``image_scores`` / ``set_score`` for any candidate set D.
70
+
71
+ Z are ADEM representations (``evaladem.represent``, or any rows whose last ``probe_dims`` columns are what the
72
+ label probe should read); y are labels of any hashable type.
73
+
74
+ k trusted neighbours of task relevance (Eq. 4)
75
+ alpha task-relevance tolerance (Eq. 6)
76
+ theta, mu costs of a wrong label and of a task-irrelevant image, in new correctly labeled images (Eq. 13)
77
+ h_fraction the kernel scale h as a fraction of T's median same-class nearest-neighbour distance (Eq. 10)
78
+ prior_correction remove T's class prior from the probe (Eq. 7); no effect on a class-balanced T
79
+ probe_dims the label probe reads the last ``probe_dims`` columns of Z (the low-pass views); None: all
80
+ """
81
+
82
+ def __init__(self, k=10, alpha=0.05, theta=3.0, mu=0.5, h_fraction=0.25, prior_correction=True,
83
+ probe_dims=VIEWS):
84
+ self.k, self.alpha, self.theta, self.mu, self.h_fraction = k, alpha, theta, mu, h_fraction
85
+ self.prior_correction, self.probe_dims = prior_correction, probe_dims
86
+
87
+ def _probe_view(self, Z):
88
+ return unit(Z[:, -self.probe_dims:]) if self.probe_dims else Z
89
+
90
+ # --------------------------------------------------------------------------------------------------- fit
91
+ def fit(self, Z, y):
92
+ """Everything that depends only on T: the probe, its temperature, the reference values of task relevance,
93
+ the kernel scale h and lambda_T."""
94
+ from sklearn.linear_model import LogisticRegression
95
+ from sklearn.model_selection import StratifiedKFold
96
+
97
+ check_trusted(y)
98
+ self.Z, self.y = unit(Z), np.asarray(y)
99
+ self.X = self._probe_view(self.Z)
100
+ self.classes = np.unique(self.y)
101
+ self.N = np.array([(self.y == c).sum() for c in self.classes], float)
102
+ S = self.Z @ self.Z.T
103
+ np.fill_diagonal(S, -np.inf) # leave-one-out: each trusted image against the rest of T
104
+ col = np.searchsorted(self.classes, self.y)
105
+ taus = np.geomspace(1e-3, 30.0, 90)
106
+ # regularisation strength and temperature: out-of-fold likelihood of T's labels, stratified folds
107
+ # (five, or as many as the smallest class has images)
108
+ folds = StratifiedKFold(int(min(5, self.N.min())), shuffle=True, random_state=0)
109
+ best = (-np.inf, None, None)
110
+ for C in (0.3, 1.0, 3.0, 10.0, 30.0):
111
+ oof = np.zeros((len(self.y), len(self.classes)))
112
+ for tr, te in folds.split(self.X, self.y):
113
+ oof[te] = _logits(LogisticRegression(C=C, max_iter=3000).fit(self.X[tr], self.y[tr]), self.X[te])
114
+ ll = max((_log_softmax(oof / t)[np.arange(len(col)), col].mean(), t) for t in taus)
115
+ if ll[0] > best[0]:
116
+ best = (ll[0], C, oof)
117
+ _, self.C_probe, logits = best
118
+ self.probe = LogisticRegression(C=self.C_probe, max_iter=3000).fit(self.X, self.y)
119
+ ll = [_log_softmax(logits / t)[np.arange(len(col)), col].mean() for t in taus]
120
+ self.tau = float(taus[int(np.argmax(ll))])
121
+ # task relevance: one reference value per trusted image, S(t, T \ t) (Eq. 4, leave-one-out)
122
+ self.reference = np.sort(_topk_mean(S, self.k))
123
+ # uniqueness: h, a quarter of the median distance of a trusted image to its nearest same-class trusted image
124
+ same = self.y[:, None] == self.y[None, :]
125
+ nn = np.where(same, S, -np.inf).max(1)
126
+ self.h = self.h_fraction * float(np.median(1 - nn[np.isfinite(nn)]))
127
+ # lambda_T: the share of correct labels of T itself, by the same EM on its out-of-fold probabilities
128
+ p = np.exp(_log_softmax(logits / self.tau))[np.arange(len(col)), col]
129
+ self.lambda_T = self._em(p, np.ones(len(p)))
130
+ return self
131
+
132
+ def label_probs(self, Z):
133
+ """P(class | image) of the probe, T's class prior removed (Eq. 7)."""
134
+ prior = np.log(self.N / self.N.sum()) if self.prior_correction else 0.0
135
+ return np.exp(_log_softmax(_logits(self.probe, self._probe_view(unit(Z))) / self.tau - prior))
136
+
137
+ def _em(self, l, r, start=0.5, pseudo=2.0):
138
+ """The share of correct labels lambda (Eq. 9): EM from 1/2, each image weighted by r, one imaginary correct
139
+ and one imaginary wrong label."""
140
+ wrong = (1 - l) / max(len(self.classes) - 1, 1)
141
+ lam = start
142
+ for _ in range(500):
143
+ q = lam * l / np.maximum(lam * l + (1 - lam) * wrong, 1e-12)
144
+ new = ((r * q).sum() + pseudo * start) / (r.sum() + pseudo)
145
+ if abs(new - lam) < 1e-7:
146
+ break
147
+ lam = new
148
+ return float(lam)
149
+
150
+ # ---------------------------------------------------------------------------------------- image scores
151
+ def image_scores(self, Z, y, alone=False):
152
+ """r, q, u and phi of every candidate image, with D = all rows of Z. ``alone=True`` scores each image as the
153
+ only candidate: lambda = lambda_T and m(d) = 1."""
154
+ Z, y = unit(Z), np.asarray(y)
155
+ n, C = len(Z), len(self.classes)
156
+ A = Z @ self.Z.T
157
+ # task relevance (Eqs. 4-6)
158
+ p = (1 + np.searchsorted(self.reference, _topk_mean(A, self.k), "right")) / (len(self.reference) + 1)
159
+ r = np.minimum(1.0, p / self.alpha)
160
+ # label correctness (Eqs. 7-9)
161
+ col = np.searchsorted(self.classes, y).clip(0, C - 1)
162
+ known = self.classes[col] == y
163
+ l = np.where(known, self.label_probs(Z)[np.arange(n), col], 0.0)
164
+ lam = self.lambda_T if (alone or n == 0) else self._em(l, r)
165
+ wrong = (1 - l) / max(C - 1, 1)
166
+ q = lam * l / np.maximum(lam * l + (1 - lam) * wrong, 1e-12)
167
+ # uniqueness (Eqs. 10-12), within each class
168
+ u = np.zeros(n)
169
+ for c in np.unique(y[known]):
170
+ i = np.flatnonzero(known & (y == c))
171
+ kappa_max = np.exp(-(1 - A[i][:, self.y == c].max(1)) / self.h)
172
+ m = np.ones(len(i))
173
+ for s in range(0, 0 if alone else len(i), 2048): # soft count of near-copies in D, itself included
174
+ m[s:s + 2048] = np.exp(-(1 - Z[i[s:s + 2048]] @ Z[i].T) / self.h).sum(1)
175
+ u[i] = (1 - kappa_max) / m
176
+ phi1, phi2, phi3 = r * q * u, self.theta * r * (1 - q), self.mu * (1 - r)
177
+ return {"r": r, "q": q, "u": u, "phi": phi1 - phi2 - phi3, "phi1": phi1, "phi2": phi2, "phi3": phi3,
178
+ "l": l, "p": p, "known_label": known, "lambda": float(lam)}
179
+
180
+ # -------------------------------------------------------------------------------------------- set score
181
+ def set_score(self, Z, y, scores=None):
182
+ """ADEM(D, T) (Eq. 14) and its parts. > 0: adding D should help."""
183
+ s = scores or self.image_scores(Z, y)
184
+ y = np.asarray(y)
185
+ r, q, u = s["r"], s["q"], s["u"]
186
+ cls = [y == c for c in self.classes]
187
+ n_D = np.array([m.sum() for m in cls], float)
188
+ new = np.array([(r * q * u)[m].sum() for m in cls]) # Phi_c1
189
+ wrong = np.array([(r * (1 - q))[m].sum() for m in cls]) # Phi_c2 / theta
190
+ off = np.array([(1 - r)[m].sum() for m in cls]) # Phi_c3 / mu
191
+ stray = (~s["known_label"]).sum() / len(self.classes) # labels T does not have, spread over the classes
192
+ gain = np.log1p(new / self.N)
193
+ harm = (self.theta * (wrong + stray) + self.mu * off) / (self.N + n_D + stray)
194
+ return {"adem": float(np.mean(gain - harm)), "gain": float(gain.mean()), "harm": float(harm.mean()),
195
+ "new_correct_images": float(new.sum()),
196
+ "expected_wrong_labels": float(wrong.sum() + stray * len(n_D)),
197
+ "task_irrelevant_share": float(np.mean(1 - r)) if len(r) else 0.0,
198
+ "lambda": s["lambda"], "uniqueness_mean": float(u.mean()) if len(u) else 0.0,
199
+ "per_class": {str(c): float(g - h) for c, g, h in zip(self.classes, gain, harm)}}
evaladem/data.py ADDED
@@ -0,0 +1,56 @@
1
+ """Reading an image folder in the usual one-sub-folder-per-class layout:
2
+
3
+ trusted/ candidate/
4
+ cat/ a.jpg ... cat/ x.png ...
5
+ dog/ b.jpg ... dog/ y.png ...
6
+
7
+ The sub-folder name is the label. Each image is decoded to RGB (EXIF orientation applied), centre-cropped to a square
8
+ (as the benchmark's images are) and, if larger than ``max_side`` pixels, resized to it (bicubic) to bound time and
9
+ memory; ADEM's encoders see every image at 224 x 224 in the end.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp", ".gif"}
18
+ MAX_SIDE = 448
19
+
20
+
21
+ def load_image(path, max_side=MAX_SIDE):
22
+ """One image file as a square uint8 RGB array (W, W, 3), W <= max_side."""
23
+ from PIL import Image, ImageOps
24
+
25
+ with Image.open(path) as im:
26
+ im = ImageOps.exif_transpose(im).convert("RGB")
27
+ w, h = im.size
28
+ s = min(w, h)
29
+ im = im.crop(((w - s) // 2, (h - s) // 2, (w - s) // 2 + s, (h - s) // 2 + s))
30
+ if s > max_side:
31
+ im = im.resize((max_side, max_side), Image.BICUBIC)
32
+ return np.asarray(im, np.uint8)
33
+
34
+
35
+ def list_folder(path):
36
+ """(file, label) of every image under ``path``/<label>/, sorted; files directly in ``path``, and hidden files and
37
+ folders (names starting with "."), are ignored."""
38
+ root = Path(path)
39
+ if not root.is_dir():
40
+ raise FileNotFoundError(f"{path}: not a folder")
41
+ items = []
42
+ for d in sorted(p for p in root.iterdir() if p.is_dir() and not p.name.startswith(".")):
43
+ for f in sorted(d.rglob("*")):
44
+ hidden = any(part.startswith(".") for part in f.relative_to(d).parts)
45
+ if f.is_file() and f.suffix.lower() in EXTENSIONS and not hidden:
46
+ items.append((f, d.name))
47
+ if not items:
48
+ raise ValueError(f"{path}: no images found in its class sub-folders (expected {path}/<class>/<image>)")
49
+ return items
50
+
51
+
52
+ def load_folder(path, max_side=MAX_SIDE):
53
+ """images (list of square uint8 arrays), labels (array of str), files (list of Path). Holds every image in
54
+ memory; ``evaluate`` and the command line read the files in chunks instead."""
55
+ items = list_folder(path)
56
+ return [load_image(f, max_side) for f, _ in items], np.array([c for _, c in items]), [f for f, _ in items]
evaladem/encoders.py ADDED
@@ -0,0 +1,90 @@
1
+ """ADEM's image representation (Eq. 2): CLIP ViT-B/32 (512-d projected image embedding) and DINOv2 ViT-S/14 (384-d
2
+ CLS token), each on the image as it is and through a Gaussian low-pass filter (standard deviation W/32, kernel size
3
+ 2 ceil(3W/32) + 1, for an image of width W), every embedding scaled to unit length, the four concatenated and scaled
4
+ by 1/2. Images are resized to 224 x 224 (bicubic) for the encoders, after the filter, and embedded in full FP32 with
5
+ TF32 off, so that the scores agree across GPUs.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from .core import CLIP_DIM, DINO_DIM, unit
12
+
13
+ ENCODERS = { # name -> (Hugging Face id, input mean, input std)
14
+ "clip": ("openai/clip-vit-base-patch32", (0.4815, 0.4578, 0.4082), (0.2686, 0.2613, 0.2758)),
15
+ "dino": ("facebook/dinov2-small", (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
16
+ }
17
+ _MODELS = {}
18
+
19
+
20
+ def default_device():
21
+ import torch
22
+
23
+ return "cuda" if torch.cuda.is_available() else "cpu"
24
+
25
+
26
+ def embed(images, encoder="clip", lowpass=False, batch=64, device=None):
27
+ """Unit-length embeddings of square uint8 images (n, W, W, 3), all of the same size, by one frozen encoder."""
28
+ import torch
29
+ import torch.nn.functional as F
30
+ from torchvision.transforms.functional import gaussian_blur
31
+
32
+ device = device or default_device()
33
+ name, mean, std = ENCODERS[encoder]
34
+ if (encoder, device) not in _MODELS:
35
+ import transformers
36
+ from transformers import AutoModel, CLIPVisionModelWithProjection
37
+
38
+ # the CLIP checkpoint also holds the text tower, which the image tower does not load: quiet that report
39
+ transformers.logging.set_verbosity_error()
40
+ transformers.utils.logging.disable_progress_bar()
41
+ cls = CLIPVisionModelWithProjection if encoder == "clip" else AutoModel
42
+ _MODELS[encoder, device] = cls.from_pretrained(name).float().to(device).eval()
43
+ model = _MODELS[encoder, device]
44
+ mean = torch.tensor(mean, device=device).view(1, 3, 1, 1)
45
+ std = torch.tensor(std, device=device).view(1, 3, 1, 1)
46
+ out = []
47
+ tf32 = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32
48
+ torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = False # restored below
49
+ try:
50
+ with torch.no_grad():
51
+ for i in range(0, len(images), batch):
52
+ x = torch.as_tensor(np.ascontiguousarray(images[i:i + batch]), device=device)
53
+ x = x.permute(0, 3, 1, 2).contiguous().float() / 255
54
+ if lowpass:
55
+ sigma = x.shape[-1] / 32
56
+ x = gaussian_blur(x, 2 * int(np.ceil(3 * sigma)) + 1, sigma)
57
+ x = F.interpolate(x, size=224, mode="bicubic", align_corners=False).clamp(0, 1)
58
+ o = model(pixel_values=(x - mean) / std)
59
+ out.append((o.image_embeds if encoder == "clip" else o.pooler_output).float().cpu().numpy())
60
+ finally:
61
+ torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = tf32
62
+ dim = CLIP_DIM if encoder == "clip" else DINO_DIM
63
+ return unit(np.concatenate(out)) if out else np.zeros((0, dim), np.float32)
64
+
65
+
66
+ def represent(images, batch=64, device=None):
67
+ """ADEM representations (n, 1792) of square uint8 images (a list of (W, W, 3) arrays, or one (n, W, W, 3)
68
+ array); images of different sizes are embedded in groups of equal size, and the rows come back in the order
69
+ given."""
70
+ groups = {}
71
+ for i, im in enumerate(images):
72
+ groups.setdefault(im.shape, []).append(i)
73
+ Z = np.zeros((len(images), 2 * (CLIP_DIM + DINO_DIM)), np.float32)
74
+ for idx in groups.values():
75
+ x = np.stack([images[i] for i in idx])
76
+ Z[idx] = np.concatenate([embed(x, e, lowpass=lp, batch=batch, device=device)
77
+ for lp in (False, True) for e in ("clip", "dino")], 1)
78
+ return unit(Z)
79
+
80
+
81
+ def represent_files(files, batch=64, device=None, chunk=512, progress=None):
82
+ """ADEM representations of image files (``evaladem.data.load_image``), read ``chunk`` at a time."""
83
+ from .data import load_image
84
+
85
+ Z = np.zeros((len(files), 2 * (CLIP_DIM + DINO_DIM)), np.float32)
86
+ for s in range(0, len(files), chunk):
87
+ Z[s:s + chunk] = represent([load_image(f) for f in files[s:s + chunk]], batch=batch, device=device)
88
+ if progress:
89
+ progress(min(s + chunk, len(files)), len(files))
90
+ return Z
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: evaladem
3
+ Version: 0.1.0
4
+ Summary: ADEM: training-free prediction of whether adding a candidate image set to a trusted training set will improve a downstream model
5
+ Author: Ümit Mert Çağlar, Alptekin Temizel
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://caglarmert.github.io/ADEM.html
8
+ Project-URL: Repository, https://github.com/caglarmert/ADEM
9
+ Project-URL: Issues, https://github.com/caglarmert/ADEM/issues
10
+ Keywords: data valuation,data quality,synthetic data,dataset curation,computer vision
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Classifier: Topic :: Scientific/Engineering :: Image Recognition
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.23
19
+ Requires-Dist: scikit-learn>=1.2
20
+ Requires-Dist: pillow>=9.0
21
+ Requires-Dist: torch>=2.0
22
+ Requires-Dist: torchvision>=0.15
23
+ Requires-Dist: transformers>=4.36
24
+ Dynamic: license-file
25
+
26
+ # ADEM: To Add or Not to Add
27
+
28
+ **[Project page](https://caglarmert.github.io/ADEM.html)** (paper and citation) · **[Code on GitHub](https://github.com/caglarmert/ADEM)**
29
+
30
+ **ADEM**, the Anticipated Downstream Effect Metric, predicts whether adding a set of new images to a small, correctly
31
+ labeled training set will improve a model trained on it, **without training any model**. It scores each candidate
32
+ image on task relevance, label correctness and uniqueness against the trusted set, and combines them into one signed
33
+ set-level score: above zero, add the candidate set; at or below zero, don't.
34
+
35
+ On 1151 candidate sets from 46 image classification, semantic segmentation and object detection tasks, ADEM ranks the
36
+ candidate sets with a mean Spearman correlation of 0.85 with the gain measured by training, against 0.63 for the
37
+ strongest of 20 existing metrics, and is the best metric on all 46 tasks.
38
+
39
+ `evaladem` is the implementation of ADEM; its code is on [GitHub](https://github.com/caglarmert/ADEM).
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install evaladem
45
+ ```
46
+
47
+ or, from this repository:
48
+
49
+ ```bash
50
+ pip install git+https://github.com/caglarmert/ADEM.git
51
+ ```
52
+
53
+ Python 3.9 or newer. The first run downloads the two frozen encoders ADEM uses, CLIP ViT-B/32 and DINOv2 ViT-S/14, from
54
+ Hugging Face (about 700 MB). A GPU is used when available; the CPU works too, more slowly.
55
+
56
+ ## Use
57
+
58
+ Both folders hold one sub-folder per class; the sub-folder name is the label.
59
+
60
+ ```
61
+ trusted/ candidate/
62
+ cat/ 0001.jpg ... cat/ web_17.png ...
63
+ dog/ 0002.jpg ... dog/ gen_04.png ...
64
+ ```
65
+
66
+ ```bash
67
+ evaladem --trusted trusted/ --candidate candidate/
68
+ ```
69
+
70
+ For example, on the paper's Oxford-IIIT Pets test bed (370 trusted images, 37 classes) with 500 new, correctly
71
+ labeled images:
72
+
73
+ ```
74
+ trusted: 370 images, 37 classes (trusted/)
75
+ candidate: 500 images, 37 classes (candidate/)
76
+ working... (embedding 870 images on cuda)
77
+ trusted: 370/370
78
+ candidate: 500/500
79
+
80
+ ADEM = +0.7498 -> add the candidate set
81
+ worth 423.0 new, correctly labeled images; 1.1 expected wrong labels (share of correct labels 100%); 1% task-irrelevant
82
+ cleaned pool: the 494 of 500 candidate images with phi(d) > 0 -> evaladem_output/cleaned_pool
83
+ per-image scores -> evaladem_output/scores.csv; set score and settings -> evaladem_output/summary.json
84
+ ```
85
+
86
+ The same 500 images with half of their labels wrong score −0.3025 (do not add), and a copy of the trusted set
87
+ −0.0008.
88
+
89
+ Output folder (`--output`, default `evaladem_output`):
90
+
91
+ | file | content |
92
+ |---|---|
93
+ | `cleaned_pool/<class>/...` | copies of the candidate images with image utility φ(d) > 0, the images ADEM expects to help (skip with `--no-pool`) |
94
+ | `scores.csv` | per candidate image: task relevance r, label correctness q, uniqueness u and utility φ |
95
+ | `summary.json` | the set score and its parts, the settings and the values fitted on the trusted set |
96
+
97
+ Other options: `--device cuda|cpu`, `--batch N`, `--overwrite` (write into a non-empty output folder, replacing an
98
+ earlier run's results).
99
+
100
+ ## Reading the score
101
+
102
+ * **ADEM > 0**: adding the candidate set is expected to improve the model; **ADEM ≤ 0**: it is not. The score is
103
+ signed and has a meaningful zero (an exact copy of the trusted set scores about zero), but it is not a probability
104
+ or a percentage. Its ranking of candidate sets is more reliable than its zero point.
105
+ * **φ(d)** is in units of one new, correctly labeled image: about +1 for a new, correctly labeled, task-relevant
106
+ image, 0 for a copy of a trusted image, about −3 for a wrong label and −0.5 for a task-irrelevant image.
107
+ * Candidate classes that the trusted set does not have count as wrong labels.
108
+
109
+ ## Python
110
+
111
+ ```python
112
+ from evaladem import evaluate
113
+ r = evaluate("trusted/", "candidate/", output="evaladem_output")
114
+ r["adem"], r["add"], r["images"][0] # set score, decision, per-image scores
115
+
116
+ from evaladem import ADEM, represent # on your own uint8 images (n, W, W, 3) and labels
117
+ m = ADEM().fit(represent(x_trusted), y_trusted)
118
+ m.set_score(represent(x_candidate), y_candidate)["adem"]
119
+ m.image_scores(represent(x_candidate), y_candidate)["phi"]
120
+ ```
121
+
122
+ ## What it computes
123
+
124
+ Each image is centre-cropped to a square (and resized to at most 448 px), embedded by CLIP ViT-B/32 and DINOv2
125
+ ViT-S/14 on the image as it is and through a Gaussian low-pass filter (standard deviation W/32), and the four unit
126
+ embeddings are concatenated. Against the trusted set T alone, each candidate image d gets
127
+
128
+ * **r(d), task relevance**: its mean similarity to its k = 10 nearest trusted images, ranked among the trusted
129
+ images' own leave-one-out values (a conformal p-value p), r = min(1, p / 0.05);
130
+ * **q(d), label correctness**: a logistic-regression probe on T's low-pass embeddings (regularisation and
131
+ temperature by cross-validation on T, T's class prior removed), combined with the share of correct labels of the
132
+ candidate set, estimated by expectation-maximisation;
133
+ * **u(d), uniqueness**: the part of d not covered by T, shared among its near-copies in the candidate set;
134
+
135
+ and the utility φ(d) = r q u − 3 r (1 − q) − ½ (1 − r). The set score averages over the classes
136
+ log(1 + Φ<sub>c,1</sub> / N<sub>c</sub><sup>T</sup>) − (Φ<sub>c,2</sub> + Φ<sub>c,3</sub>) / (N<sub>c</sub><sup>T</sup> + N<sub>c</sub><sup>D</sup>),
137
+ where the Φ are the three parts of φ summed over the candidate images of class c. The settings k = 10, α = 0.05,
138
+ θ = 3, µ = ½ and the quarter in h are fixed, as in the paper; everything else (the probe, its regularisation and
139
+ temperature, the reference values of task relevance, h and T's own share of correct labels) is computed from T alone.
140
+
141
+ ## Requirements of the trusted set
142
+
143
+ At least two classes and at least two images per class; it should be correctly labeled and drawn like the data the
144
+ model will be tested on. For segmentation or detection data, put each image in the folder of its primary class, as
145
+ the paper does: the majority pixel class (background excluded on object-centric data) or the majority box class.
146
+
147
+ ## Citation
148
+
149
+ The paper and its BibTeX entry are on the [project page](https://caglarmert.github.io/ADEM.html).
150
+
151
+ ## License
152
+
153
+ evaladem is released under the MIT License (see `LICENSE`).
154
+
155
+ The encoder weights are not part of this package: they are downloaded from Hugging Face at first use and are covered
156
+ by their own licenses, CLIP ViT-B/32 (`openai/clip-vit-base-patch32`, OpenAI, MIT License) and DINOv2 ViT-S/14
157
+ (`facebook/dinov2-small`, Meta, Apache License 2.0).
@@ -0,0 +1,12 @@
1
+ evaladem/__init__.py,sha256=pRuDpkbzD7VefmSLHNK_mfpLFI1XzbOx2unN0maUd_Q,962
2
+ evaladem/api.py,sha256=-73yjs6PY2ycalhjU-vccKT1o9LuD3Ke9ili3_0kZXo,4358
3
+ evaladem/cli.py,sha256=J17oNgaYrcMCRUmdytr0n39v9Isol_Bi0uYrUACX17M,2957
4
+ evaladem/core.py,sha256=Iq7ax7NSCaBMbsrfaV5_68Xe1d5ONnRNPMJ1M9CL2Nw,10963
5
+ evaladem/data.py,sha256=QBL4T73gqx3CzPBetBNzkHya81asfAzHwJLJ5UuLd64,2380
6
+ evaladem/encoders.py,sha256=EmUcxJ543NYVuAhlfctO8SrQufuqFVcS8LPJBBDtu-k,4418
7
+ evaladem-0.1.0.dist-info/licenses/LICENSE,sha256=LT6BnD2q5tQFyxojKmvvMhJIQ9DOKtqZo6oiucjwSuw,1097
8
+ evaladem-0.1.0.dist-info/METADATA,sha256=53seQBA5swahf03P-hMSbRwa9pgpGZs0RRfV2_NbEak,7573
9
+ evaladem-0.1.0.dist-info/WHEEL,sha256=YLJXdYXQ2FQ0Uqn2J-6iEIC-3iOey8lH3xCtvFLkd8Q,91
10
+ evaladem-0.1.0.dist-info/entry_points.txt,sha256=V2mkg3nujUpF3YEyd36Mm2o0Ngkn1P9O_6PcQoADmy8,47
11
+ evaladem-0.1.0.dist-info/top_level.txt,sha256=YoCdwHJ-CqfSm4Uj80uVj4Hg7cDi5fKAD-g42tbB8Fk,9
12
+ evaladem-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (81.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ evaladem = evaladem.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ümit Mert Çağlar and Alptekin Temizel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ evaladem