56 lines
2.1 KiB
Python
56 lines
2.1 KiB
Python
import argparse
|
|
import os
|
|
import numpy as np
|
|
from PIL import Image
|
|
from kb.embedder import Embedder
|
|
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--data_dir", required=True) # crops_dataset (contient train/ et val/)
|
|
ap.add_argument("--backbone", default="efficientnet")
|
|
ap.add_argument("--weights", default=None)
|
|
ap.add_argument("--max_per_class", type=int, default=40)
|
|
args = ap.parse_args()
|
|
emb = Embedder(args.backbone, weights=args.weights)
|
|
|
|
|
|
def load(split):
|
|
root = os.path.join(args.data_dir, split)
|
|
vecs, labels = [], []
|
|
for c in sorted(os.listdir(root)):
|
|
folder = os.path.join(root, c)
|
|
if not os.path.isdir(folder) or c.startswith("_"):
|
|
continue
|
|
files = [f for f in sorted(os.listdir(folder))
|
|
if f.lower().endswith((".jpg", ".jpeg", ".png"))][:args.max_per_class]
|
|
if not files:
|
|
continue
|
|
v = emb.encode([Image.open(os.path.join(folder, f)).convert("RGB") for f in files])
|
|
vecs.append(v)
|
|
labels += [c] * len(v)
|
|
print(f" {split}/{c}: {len(v)}")
|
|
return np.vstack(vecs), np.array(labels)
|
|
|
|
|
|
print("Encodage du train...")
|
|
Xtr, ytr = load("train")
|
|
print("Encodage du val...")
|
|
Xva, yva = load("val")
|
|
S = Xva @ Xtr.T
|
|
|
|
pos, unk, correct = [], [], 0
|
|
for i in range(len(Xva)):
|
|
same = ytr == yva[i]
|
|
pos.append(S[i][same].max() if same.any() else -1) # produit connu
|
|
unk.append(S[i][~same].max()) # si sa classe était inconnue
|
|
correct += ytr[S[i].argmax()] == yva[i]
|
|
pos, unk = np.array(pos), np.array(unk)
|
|
|
|
print(f"\nAccuracy top-1 (1-NN) : {correct / len(Xva):.3f}")
|
|
print(f"Produit connu : médiane {np.median(pos):.2f}, p10 {np.percentile(pos, 10):.2f}")
|
|
print(f"Produit inconnu : médiane {np.median(unk):.2f}, p90 {np.percentile(unk, 90):.2f}")
|
|
best_t, best_s = 0, 0
|
|
for t in np.linspace(0.3, 0.95, 66):
|
|
s = ((pos >= t).mean() + (unk < t).mean()) / 2
|
|
if s > best_s:
|
|
best_t, best_s = t, s
|
|
print(f"Seuil connu/inconnu suggéré : {best_t:.2f} (exactitude équilibrée {best_s:.3f})") |