TExcelTAD
Home › ML Projects: 15 End-to-End Builds › Project 12: Person Re-Identification

Project 12: Person Re-Identification

A one-day trade fair has photographers' cameras in every hall. Visitors who want the photos they appear in can opt in at a kiosk at the entrance: the kiosk camera takes two crops, the visitor gets a random token, and during the day the service looks for them in the hall cameras. Everyone else, the large majority, must stay unknown: matching a stranger to an enrolled visitor would send one person's photo to another. At the end of the day, or earlier on request, the enrolment is deleted. Level: advanced. Main skills: metric learning with a triplet loss, open-set evaluation, choosing a threshold on validation identities, deletion and retention built into the service.

The re-identification project of the CV course is closed-set: every query person is in the gallery, and the question is how high the right match ranks (CMC, mAP), even with distractors. Here the question changes to "is this person enrolled at all, and if so who?", which needs a threshold and two rates instead of a ranking, and the gallery holds only people who agreed to be in it. The method also changes: a small network trained with the batch-hard triplet loss of person re-identification, on separate training identities. Read that lesson for the losses and the ranking metrics; the open-set rates come from face recognition.

Note: Matching people by their appearance across cameras is processing of personal data, and features that single out a person can count as biometric data under the GDPR; processed to uniquely identify someone, they are special-category data, which needs explicit consent or another Article 9 condition. The EU AI Act bans real-time remote biometric identification in public spaces for law enforcement (with narrow exceptions) and lists other remote biometric identification as high risk in Annex III (obligations from 2 December 2027 after the Digital Omnibus, Regulation (EU) 2026/1744; verification that only confirms a person is who they claim is excluded); check whether a re-ID service falls under those rules before building one, with a lawyer. This design limits the risk: opt-in only, a random token instead of a name, no images stored, unknown people not logged, deletion on request and at the end of the day (privacy, consent and licensing, governance). All people here are drawn in code.

Goal and success criteria

Fixed before any result, for 20 enrolled visitors among 200 strangers:

Requirement Metric Target Measured on
Strangers stay unknown FPIR: share of stranger crops matched to someone at most 1 % test strangers, threshold fixed on validation
Enrolled visitors are found DIR: share of their hall-camera crops matched to the right token and above the threshold at least 0.6 test visitors, same threshold
Deletion works an identify call after DELETE "unknown" service test
Nothing kept about strangers stored data after a query from a stranger none service test

The two rates (from face recognition), for a threshold tt on the cosine similarity ss of a query to its best enrolled template:

DIR(t)=#{enrolled queries with best match correct and s≥t}#{enrolled queries},FPIR(t)=#{stranger queries with s≥t}#{stranger queries}\text{DIR}(t) = \frac{\#\{\text{enrolled queries with best match correct and } s \ge t\}}{\#\{\text{enrolled queries}\}}, \qquad \text{FPIR}(t) = \frac{\#\{\text{stranger queries with } s \ge t\}}{\#\{\text{stranger queries}\}}

FPIR is the privacy risk and comes first; DIR is the service quality.

The data

make_people draws 64 x 32 crops of synthetic visitors. Unlike the CV course's pedestrians, the clothes come from small palettes (8 shirt and 6 trouser colours, with a little variation), so many people wear the same colours and differ only in details: 40 % have a striped shirt, 40 % carry a bag, hair tones vary. People walk either way (the crop is mirrored), the light varies by up to 25 %, and three cameras differ: the kiosk camera A is neutral, hall camera B is warm with a brightening tone curve, hall camera C is cold with a darkening one.

The identities are split four ways, and no person is in two groups (split strategies):

Group Identities Used for
training 0 to 99, 6 crops each (2 per camera) learning the embedding
validation 100 to 119 enrolled, 120 to 219 strangers choosing the threshold
test 300 to 319 enrolled, 400 to 599 strangers the final numbers, once
extra 400 to 479 enrolled later, 500 to 599 as strangers the gallery-growth experiment

The baselines are the striped colour histograms of person re-identification, raw and after grey-world normalisation; the threshold of each is the one that gives FPIR 1 % on the validation strangers.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

SHIRTS = np.array([[200, 40, 40], [40, 90, 200], [40, 150, 60], [230, 200, 50], [240, 240, 235], [35, 35, 40], [150, 60, 170], [240, 140, 40]])
TROUSERS = np.array([[30, 40, 90], [40, 40, 45], [120, 100, 70], [170, 170, 165], [70, 90, 60], [20, 30, 50]])
CAMS = {"A": ([1.0, 1.0, 1.0], 1.0), "B": ([1.2, 1.0, 0.75], 0.8), "C": ([0.8, 0.95, 1.2], 1.25)}

def make_look(rng):
    """An identity: shirt and trouser colour from small palettes (many people share them), shirt
    stripes or not, a bag or not, hair tone."""
    s, t = int(rng.integers(8)), int(rng.integers(6))
    return dict(s=s, t=t, shirt=SHIRTS[s] + rng.integers(-15, 16, 3), trousers=TROUSERS[t] + rng.integers(-15, 16, 3),
                stripes=SHIRTS[rng.integers(8)] if rng.random() < 0.4 else None,
                bag=rng.integers(40, 220, 3) if rng.random() < 0.4 else None, hair=int(rng.integers(20, 160)))

def make_crop(rng, look, cam, h=64, w=32):
    """A 64 x 32 RGB crop of the identity seen by camera A (enrolment kiosk), B or C."""
    img = rng.normal(100, 18, (h, w, 3))
    dx = int(rng.integers(-3, 4))
    img[2:7, 12 + dx:20 + dx] = look["hair"]
    img[6:15, 12 + dx:20 + dx] = [200, 160, 130]
    img[15:37, 8 + dx:24 + dx] = look["shirt"]
    if look["stripes"] is not None:
        img[17:37:5, 8 + dx:24 + dx] = look["stripes"]; img[18:37:5, 8 + dx:24 + dx] = look["stripes"]
    img[37:62, 10 + dx:22 + dx] = look["trousers"]
    if look["bag"] is not None:
        img[28:42, 22 + dx:28 + dx] = look["bag"]
    if rng.random() < 0.5:
        img = img[:, ::-1]                                    # walking the other way
    gain, gamma = CAMS[cam]
    img = (img * rng.uniform(0.75, 1.25) * np.array(gain)).clip(0, 255)
    img = 255 * (img / 255) ** gamma + rng.normal(0, 7, (h, w, 3))
    return img.clip(0, 255).astype(np.uint8)

def look_of(i):
    return make_look(np.random.default_rng(1000 + i))      # the look of identity i depends only on i

def make_people(seed, ids, n_per_cam):
    """Crops of the given identities: n_per_cam = {camera: crops per person}. Returns images, ids, cameras."""
    rng = np.random.default_rng(seed)
    X, y, c = [], [], []
    for i in ids:
        look = look_of(i)
        for cam, n in n_per_cam.items():
            for _ in range(n):
                X.append(make_crop(rng, look, cam)); y.append(i); c.append(cam)
    return np.array(X), np.array(y), np.array(c)

def grey_world(img):
    """Scale each channel to the same mean: undoes a camera's colour gain, not its tone curve."""
    f = img.astype(float); m = f.reshape(-1, 3).mean(0)
    return (f * m.mean() / m).clip(0, 255).astype(np.uint8)

def hsv_stripes(img, bins=(12, 4)):
    """Colour histograms of head, torso and legs (the baseline of the CV person re-ID lesson)."""
    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    f = [np.sqrt(cv2.calcHist([np.ascontiguousarray(hsv[a:b])], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel() / ((b - a) * img.shape[1])) for a, b in [(0, 15), (15, 37), (37, 64)]]
    f = np.concatenate(f)
    return f / np.linalg.norm(f)

def open_set(G, g_ids, Q, q_ids, thr):
    """Cosine similarity of every query to every enrolled template. A query is accepted if its best
    score >= thr. DIR: enrolled queries accepted with the right identity; FPIR: strangers accepted."""
    S = Q @ G.T
    best, who = S.max(1), g_ids[S.argmax(1)]
    known = np.isin(q_ids, g_ids)
    dir_ = np.mean((best[known] >= thr) & (who[known] == q_ids[known]))
    fpir = np.mean(best[~known] >= thr)
    return float(dir_), float(fpir)

def threshold_at(G, g_ids, Q, q_ids, fpir=0.01):
    """The smallest threshold whose FPIR on these strangers is at most `fpir`."""
    S = Q @ G.T
    s = np.sort(S.max(1)[~np.isin(q_ids, g_ids)])[::-1]
    k = int(np.floor(fpir * len(s)))
    return float(s[k]) + 1e-6

def templates(F, y):
    """One template per enrolled person: the normalised mean of their enrolment features."""
    ids = np.unique(y)
    T = np.array([F[y == i].mean(0) for i in ids])
    return T / np.linalg.norm(T, axis=1, keepdims=True), ids
import matplotlib.pyplot as plt

Xtr, ytr, ctr = make_people(0, range(100), {"A": 2, "B": 2, "C": 2})
VAL = make_people(1, range(100, 120), {"A": 2}), make_people(2, range(100, 220), {"B": 2, "C": 2})
TEST = make_people(3, range(300, 320), {"A": 2}), make_people(4, [*range(300, 320), *range(400, 600)], {"B": 2, "C": 2})
for name, (Xe, ye, _), (Xq, yq, _) in [("validation", *VAL), ("test", *TEST)]:
    known = np.isin(yq, ye)
    print(f"{name:10s}: {len(np.unique(ye))} enrolled people ({len(Xe)} kiosk crops), queries: {known.sum()} crops of enrolled people, "
          f"{(~known).sum()} of {len(np.unique(yq[~known]))} strangers")
print(f"training  : {len(np.unique(ytr))} people, {len(Xtr)} crops from cameras A, B and C")
same = sum(look_of(i)["s"] == look_of(j)["s"] and look_of(i)["t"] == look_of(j)["t"] for i in range(400, 600) for j in range(300, 320))
print(f"test stranger/enrolled pairs with the same shirt and trouser colour: {same} of {200 * 20}")

print("features              threshold  val DIR / FPIR    test DIR / FPIR   test rank-1 (closed set)")
for name, feat in [("HSV stripes", lambda X: np.array([hsv_stripes(x) for x in X])),
                   ("grey-world + HSV", lambda X: np.array([hsv_stripes(grey_world(x)) for x in X]))]:
    ((Xe, ye, _), (Xq, yq, _)) = VAL
    G, gi = templates(feat(Xe), ye); Q = feat(Xq)
    thr = threshold_at(G, gi, Q, yq, fpir=0.01)               # fixed on validation identities
    v = open_set(G, gi, Q, yq, thr)
    ((Xe, ye, _), (Xq, yq, _)) = TEST
    G, gi = templates(feat(Xe), ye); Q = feat(Xq)
    t = open_set(G, gi, Q, yq, thr)
    known = np.isin(yq, gi)
    r1 = np.mean(gi[(Q[known] @ G.T).argmax(1)] == yq[known])
    print(f"{name:20s}  {thr:.3f}      {v[0]:.3f} / {v[1]:.4f}    {t[0]:.3f} / {t[1]:.4f}    {r1:.3f}")

fig, ax = plt.subplots(1, 6, figsize=(7, 2.6))
(Xe, ye, ce), (Xq, yq, cq) = TEST
show = [(Xe[0], "300, kiosk A"), (Xq[0], "300, camera B"), (Xq[2], "300, camera C")]
twin = next(j for j in range(400, 600) if look_of(j)["s"] == look_of(300)["s"] and look_of(j)["t"] == look_of(300)["t"])
show += [(Xq[np.flatnonzero(yq == twin)[0]], f"{twin}, stranger B"), (Xq[np.flatnonzero(yq == 301)[0]], "301, camera B"), (Xe[2], "301, kiosk A")]
for a, (img, title) in zip(ax, show):
    a.imshow(img); a.set_title(title, fontsize=7); a.axis("off")
plt.tight_layout()
validation: 20 enrolled people (40 kiosk crops), queries: 80 crops of enrolled people, 400 of 100 strangers
test      : 20 enrolled people (40 kiosk crops), queries: 80 crops of enrolled people, 800 of 200 strangers
training  : 100 people, 600 crops from cameras A, B and C
test stranger/enrolled pairs with the same shirt and trouser colour: 69 of 4000
features              threshold  val DIR / FPIR    test DIR / FPIR   test rank-1 (closed set)
HSV stripes           0.851      0.000 / 0.0100    0.000 / 0.0000    0.588
grey-world + HSV      0.953      0.325 / 0.0100    0.200 / 0.0225    0.912

The figure shows the problem: visitor 300's white shirt turns peach in camera B and blue in camera C, and stranger 428 has the same palette colours for shirt and trousers (with stripes and a bag on top). 69 of the 4,000 stranger and enrolled pairs share both shirt and trouser colour. The raw histograms cannot see past the camera colour casts: closed-set rank-1 is only 0.588, and at the threshold that keeps FPIR at 1 % on validation they identify nobody (DIR 0.000). Grey-world normalisation lifts rank-1 to 0.912, which looks good, but in the open set it finds only 0.200 of the enrolled crops, and its threshold does not transfer: test FPIR is 2.25 %, more than twice the target. Rank-1 does not predict open-set performance: it only asks whether the right person ranks first, not whether the scores of strangers stay below those of real matches.

Step 2: a re-ID embedding trained with batch-hard triplets (recorded)

The network is small: three convolution blocks, pooled into 4 horizontal stripes (the idea of part-based re-ID models), projected to a 32-dimensional unit vector. Training uses only identities 0 to 99, in P x K batches (16 identities, 4 crops each) with the batch-hard triplet loss and margin 0.3, 400 Adam steps; see contrastive and triplet losses for the loss and training a CNN for the loop. This example imports torch, so it is recorded (CPU, Docker, about 10 s); the generator is the same code as above, so the crops are identical.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

SHIRTS = np.array([[200, 40, 40], [40, 90, 200], [40, 150, 60], [230, 200, 50], [240, 240, 235], [35, 35, 40], [150, 60, 170], [240, 140, 40]])
TROUSERS = np.array([[30, 40, 90], [40, 40, 45], [120, 100, 70], [170, 170, 165], [70, 90, 60], [20, 30, 50]])
CAMS = {"A": ([1.0, 1.0, 1.0], 1.0), "B": ([1.2, 1.0, 0.75], 0.8), "C": ([0.8, 0.95, 1.2], 1.25)}

def make_look(rng):
    """An identity: shirt and trouser colour from small palettes (many people share them), shirt
    stripes or not, a bag or not, hair tone."""
    s, t = int(rng.integers(8)), int(rng.integers(6))
    return dict(s=s, t=t, shirt=SHIRTS[s] + rng.integers(-15, 16, 3), trousers=TROUSERS[t] + rng.integers(-15, 16, 3),
                stripes=SHIRTS[rng.integers(8)] if rng.random() < 0.4 else None,
                bag=rng.integers(40, 220, 3) if rng.random() < 0.4 else None, hair=int(rng.integers(20, 160)))

def make_crop(rng, look, cam, h=64, w=32):
    """A 64 x 32 RGB crop of the identity seen by camera A (enrolment kiosk), B or C."""
    img = rng.normal(100, 18, (h, w, 3))
    dx = int(rng.integers(-3, 4))
    img[2:7, 12 + dx:20 + dx] = look["hair"]
    img[6:15, 12 + dx:20 + dx] = [200, 160, 130]
    img[15:37, 8 + dx:24 + dx] = look["shirt"]
    if look["stripes"] is not None:
        img[17:37:5, 8 + dx:24 + dx] = look["stripes"]; img[18:37:5, 8 + dx:24 + dx] = look["stripes"]
    img[37:62, 10 + dx:22 + dx] = look["trousers"]
    if look["bag"] is not None:
        img[28:42, 22 + dx:28 + dx] = look["bag"]
    if rng.random() < 0.5:
        img = img[:, ::-1]                                    # walking the other way
    gain, gamma = CAMS[cam]
    img = (img * rng.uniform(0.75, 1.25) * np.array(gain)).clip(0, 255)
    img = 255 * (img / 255) ** gamma + rng.normal(0, 7, (h, w, 3))
    return img.clip(0, 255).astype(np.uint8)

def look_of(i):
    return make_look(np.random.default_rng(1000 + i))      # the look of identity i depends only on i

def make_people(seed, ids, n_per_cam):
    """Crops of the given identities: n_per_cam = {camera: crops per person}. Returns images, ids, cameras."""
    rng = np.random.default_rng(seed)
    X, y, c = [], [], []
    for i in ids:
        look = look_of(i)
        for cam, n in n_per_cam.items():
            for _ in range(n):
                X.append(make_crop(rng, look, cam)); y.append(i); c.append(cam)
    return np.array(X), np.array(y), np.array(c)

def grey_world(img):
    """Scale each channel to the same mean: undoes a camera's colour gain, not its tone curve."""
    f = img.astype(float); m = f.reshape(-1, 3).mean(0)
    return (f * m.mean() / m).clip(0, 255).astype(np.uint8)

def hsv_stripes(img, bins=(12, 4)):
    """Colour histograms of head, torso and legs (the baseline of the CV person re-ID lesson)."""
    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    f = [np.sqrt(cv2.calcHist([np.ascontiguousarray(hsv[a:b])], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel() / ((b - a) * img.shape[1])) for a, b in [(0, 15), (15, 37), (37, 64)]]
    f = np.concatenate(f)
    return f / np.linalg.norm(f)

def open_set(G, g_ids, Q, q_ids, thr):
    """Cosine similarity of every query to every enrolled template. A query is accepted if its best
    score >= thr. DIR: enrolled queries accepted with the right identity; FPIR: strangers accepted."""
    S = Q @ G.T
    best, who = S.max(1), g_ids[S.argmax(1)]
    known = np.isin(q_ids, g_ids)
    dir_ = np.mean((best[known] >= thr) & (who[known] == q_ids[known]))
    fpir = np.mean(best[~known] >= thr)
    return float(dir_), float(fpir)

def threshold_at(G, g_ids, Q, q_ids, fpir=0.01):
    """The smallest threshold whose FPIR on these strangers is at most `fpir`."""
    S = Q @ G.T
    s = np.sort(S.max(1)[~np.isin(q_ids, g_ids)])[::-1]
    k = int(np.floor(fpir * len(s)))
    return float(s[k]) + 1e-6

def templates(F, y):
    """One template per enrolled person: the normalised mean of their enrolment features."""
    ids = np.unique(y)
    T = np.array([F[y == i].mean(0) for i in ids])
    return T / np.linalg.norm(T, axis=1, keepdims=True), ids
import torch
from torch import nn

torch.manual_seed(0)
Xtr, ytr, _ = make_people(0, range(100), {"A": 2, "B": 2, "C": 2})          # training identities only
VAL = make_people(1, range(100, 120), {"A": 2}), make_people(2, range(100, 220), {"B": 2, "C": 2})
TEST = make_people(3, range(300, 320), {"A": 2}), make_people(4, [*range(300, 320), *range(400, 600)], {"B": 2, "C": 2})

class ReIDNet(nn.Module):
    """Three conv blocks, pooled into 4 horizontal stripes, projected to a 32-d unit vector."""
    def __init__(self, d=32):
        super().__init__()
        blk = lambda i, o: nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU(), nn.MaxPool2d(2))
        self.f = nn.Sequential(blk(3, 16), blk(16, 32), blk(32, 64), nn.AdaptiveAvgPool2d((4, 1)), nn.Flatten(), nn.Linear(256, d))
    def forward(self, x):
        return nn.functional.normalize(self.f(x), dim=1)

def batch_hard(E, y, margin=0.3):
    """Batch-hard triplet loss: hardest positive and hardest negative of every anchor in the batch."""
    D = torch.cdist(E, E); same = y[:, None] == y[None]
    return torch.relu(margin + (D * same).max(1).values - (D + 1e3 * same).min(1).values).mean()

tens = lambda X: torch.tensor(X.transpose(0, 3, 1, 2) / 255.0, dtype=torch.float32)
net, g = ReIDNet(), np.random.default_rng(0)
opt = torch.optim.Adam(net.parameters(), lr=3e-3)
Xt, yt = tens(Xtr), torch.tensor(ytr)
for step in range(1, 401):                                   # P x K = 16 identities x 4 crops per batch
    idx = np.concatenate([g.choice(np.flatnonzero(ytr == i), 4, replace=False) for i in g.choice(100, 16, replace=False)])
    net.train(); loss = batch_hard(net(Xt[idx]), yt[idx])
    opt.zero_grad(); loss.backward(); opt.step()
    if step in (1, 100, 400):
        print(f"step {step:3d}: batch-hard loss {loss.item():.3f}")
net.eval()

def cnn(X):
    with torch.no_grad():
        return net(tens(X)).numpy()
print("features              threshold  val DIR / FPIR    test DIR / FPIR   test rank-1 (closed set)")
for name, feat in [("grey-world + HSV", lambda X: np.array([hsv_stripes(grey_world(x)) for x in X])), ("triplet CNN", cnn)]:
    ((Xe, ye, _), (Xq, yq, _)) = VAL
    G, gi = templates(feat(Xe), ye); Q = feat(Xq)
    thr = threshold_at(G, gi, Q, yq, fpir=0.01)               # fixed on validation identities
    v = open_set(G, gi, Q, yq, thr)
    ((Xe, ye, _), (Xq, yq, _)) = TEST
    G, gi = templates(feat(Xe), ye); Q = feat(Xq)
    t = open_set(G, gi, Q, yq, thr)
    known = np.isin(yq, gi)
    r1 = np.mean(gi[(Q[known] @ G.T).argmax(1)] == yq[known])
    print(f"{name:20s}  {thr:.3f}      {v[0]:.3f} / {v[1]:.4f}    {t[0]:.3f} / {t[1]:.4f}    {r1:.3f}")
step   1: batch-hard loss 0.691
step 100: batch-hard loss 0.011
step 400: batch-hard loss 0.012
features              threshold  val DIR / FPIR    test DIR / FPIR   test rank-1 (closed set)
grey-world + HSV      0.953      0.325 / 0.0100    0.200 / 0.0225    0.912
triplet CNN           0.985      0.812 / 0.0100    0.662 / 0.0013    0.963

The batch-hard loss falls from 0.691 to about 0.01 within 100 steps. With the same protocol as the baselines, the CNN reaches DIR 0.812 on validation and 0.662 on test at FPIR 0.13 % (1 of 800 stranger crops accepted): both targets are met. Rank-1 is 0.963, only a little above grey-world's 0.912, but the open-set rates are in another league, because the triplet loss pulls crops of one person together and pushes different people apart by a margin, which is exactly what a threshold needs. Grey-world's row is repeated here from step 1 (same data, same numbers).

Note the drop from validation (0.812) to test (0.662): 20 enrolled people with 4 query crops each is a small sample, and the visitors in a different group have different looks. Report it as it is, with the sample size; a pilot would enrol a few hundred volunteers.

Step 3: the operating point, a growing gallery and the errors (recorded)

The service will run for a day with more visitors opting in as it goes. Three questions: how DIR trades against FPIR when the validation target changes, what happens to FPIR at a fixed threshold when the gallery grows from 20 to 100 people, and which errors remain. The model is retrained with the same seeds (the recorded examples do not share files).

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

SHIRTS = np.array([[200, 40, 40], [40, 90, 200], [40, 150, 60], [230, 200, 50], [240, 240, 235], [35, 35, 40], [150, 60, 170], [240, 140, 40]])
TROUSERS = np.array([[30, 40, 90], [40, 40, 45], [120, 100, 70], [170, 170, 165], [70, 90, 60], [20, 30, 50]])
CAMS = {"A": ([1.0, 1.0, 1.0], 1.0), "B": ([1.2, 1.0, 0.75], 0.8), "C": ([0.8, 0.95, 1.2], 1.25)}

def make_look(rng):
    """An identity: shirt and trouser colour from small palettes (many people share them), shirt
    stripes or not, a bag or not, hair tone."""
    s, t = int(rng.integers(8)), int(rng.integers(6))
    return dict(s=s, t=t, shirt=SHIRTS[s] + rng.integers(-15, 16, 3), trousers=TROUSERS[t] + rng.integers(-15, 16, 3),
                stripes=SHIRTS[rng.integers(8)] if rng.random() < 0.4 else None,
                bag=rng.integers(40, 220, 3) if rng.random() < 0.4 else None, hair=int(rng.integers(20, 160)))

def make_crop(rng, look, cam, h=64, w=32):
    """A 64 x 32 RGB crop of the identity seen by camera A (enrolment kiosk), B or C."""
    img = rng.normal(100, 18, (h, w, 3))
    dx = int(rng.integers(-3, 4))
    img[2:7, 12 + dx:20 + dx] = look["hair"]
    img[6:15, 12 + dx:20 + dx] = [200, 160, 130]
    img[15:37, 8 + dx:24 + dx] = look["shirt"]
    if look["stripes"] is not None:
        img[17:37:5, 8 + dx:24 + dx] = look["stripes"]; img[18:37:5, 8 + dx:24 + dx] = look["stripes"]
    img[37:62, 10 + dx:22 + dx] = look["trousers"]
    if look["bag"] is not None:
        img[28:42, 22 + dx:28 + dx] = look["bag"]
    if rng.random() < 0.5:
        img = img[:, ::-1]                                    # walking the other way
    gain, gamma = CAMS[cam]
    img = (img * rng.uniform(0.75, 1.25) * np.array(gain)).clip(0, 255)
    img = 255 * (img / 255) ** gamma + rng.normal(0, 7, (h, w, 3))
    return img.clip(0, 255).astype(np.uint8)

def look_of(i):
    return make_look(np.random.default_rng(1000 + i))      # the look of identity i depends only on i

def make_people(seed, ids, n_per_cam):
    """Crops of the given identities: n_per_cam = {camera: crops per person}. Returns images, ids, cameras."""
    rng = np.random.default_rng(seed)
    X, y, c = [], [], []
    for i in ids:
        look = look_of(i)
        for cam, n in n_per_cam.items():
            for _ in range(n):
                X.append(make_crop(rng, look, cam)); y.append(i); c.append(cam)
    return np.array(X), np.array(y), np.array(c)

def grey_world(img):
    """Scale each channel to the same mean: undoes a camera's colour gain, not its tone curve."""
    f = img.astype(float); m = f.reshape(-1, 3).mean(0)
    return (f * m.mean() / m).clip(0, 255).astype(np.uint8)

def hsv_stripes(img, bins=(12, 4)):
    """Colour histograms of head, torso and legs (the baseline of the CV person re-ID lesson)."""
    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    f = [np.sqrt(cv2.calcHist([np.ascontiguousarray(hsv[a:b])], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel() / ((b - a) * img.shape[1])) for a, b in [(0, 15), (15, 37), (37, 64)]]
    f = np.concatenate(f)
    return f / np.linalg.norm(f)

def open_set(G, g_ids, Q, q_ids, thr):
    """Cosine similarity of every query to every enrolled template. A query is accepted if its best
    score >= thr. DIR: enrolled queries accepted with the right identity; FPIR: strangers accepted."""
    S = Q @ G.T
    best, who = S.max(1), g_ids[S.argmax(1)]
    known = np.isin(q_ids, g_ids)
    dir_ = np.mean((best[known] >= thr) & (who[known] == q_ids[known]))
    fpir = np.mean(best[~known] >= thr)
    return float(dir_), float(fpir)

def threshold_at(G, g_ids, Q, q_ids, fpir=0.01):
    """The smallest threshold whose FPIR on these strangers is at most `fpir`."""
    S = Q @ G.T
    s = np.sort(S.max(1)[~np.isin(q_ids, g_ids)])[::-1]
    k = int(np.floor(fpir * len(s)))
    return float(s[k]) + 1e-6

def templates(F, y):
    """One template per enrolled person: the normalised mean of their enrolment features."""
    ids = np.unique(y)
    T = np.array([F[y == i].mean(0) for i in ids])
    return T / np.linalg.norm(T, axis=1, keepdims=True), ids
import torch
from torch import nn

torch.manual_seed(0)
Xtr, ytr, _ = make_people(0, range(100), {"A": 2, "B": 2, "C": 2})          # training identities only
VAL = make_people(1, range(100, 120), {"A": 2}), make_people(2, range(100, 220), {"B": 2, "C": 2})
TEST = make_people(3, range(300, 320), {"A": 2}), make_people(4, [*range(300, 320), *range(400, 600)], {"B": 2, "C": 2})

class ReIDNet(nn.Module):
    """Three conv blocks, pooled into 4 horizontal stripes, projected to a 32-d unit vector."""
    def __init__(self, d=32):
        super().__init__()
        blk = lambda i, o: nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU(), nn.MaxPool2d(2))
        self.f = nn.Sequential(blk(3, 16), blk(16, 32), blk(32, 64), nn.AdaptiveAvgPool2d((4, 1)), nn.Flatten(), nn.Linear(256, d))
    def forward(self, x):
        return nn.functional.normalize(self.f(x), dim=1)

def batch_hard(E, y, margin=0.3):
    """Batch-hard triplet loss: hardest positive and hardest negative of every anchor in the batch."""
    D = torch.cdist(E, E); same = y[:, None] == y[None]
    return torch.relu(margin + (D * same).max(1).values - (D + 1e3 * same).min(1).values).mean()

tens = lambda X: torch.tensor(X.transpose(0, 3, 1, 2) / 255.0, dtype=torch.float32)
net, g = ReIDNet(), np.random.default_rng(0)
opt = torch.optim.Adam(net.parameters(), lr=3e-3)
Xt, yt = tens(Xtr), torch.tensor(ytr)
for step in range(1, 401):                                   # P x K = 16 identities x 4 crops per batch
    idx = np.concatenate([g.choice(np.flatnonzero(ytr == i), 4, replace=False) for i in g.choice(100, 16, replace=False)])
    net.train(); loss = batch_hard(net(Xt[idx]), yt[idx])
    opt.zero_grad(); loss.backward(); opt.step()
    if step in (1, 100, 400):
        print(f"step {step:3d}: batch-hard loss {loss.item():.3f}")
net.eval()

def cnn(X):
    with torch.no_grad():
        return net(tens(X)).numpy()
(Xe, ye, _), (Xq, yq, _) = VAL
Gv, gv = templates(cnn(Xe), ye); Qv = cnn(Xq)
(Xe, ye, _), (Xq, yq, _) = TEST
Gt, gt = templates(cnn(Xe), ye); Qt = cnn(Xq)
print("FPIR target  threshold  test DIR  test FPIR")
for target in (0.005, 0.01, 0.05):
    thr = threshold_at(Gv, gv, Qv, VAL[1][1], fpir=target)          # chosen on validation
    d, f = open_set(Gt, gt, Qt, yq, thr)
    print(f"  {target:5.3f}      {thr:.3f}      {d:.3f}     {f:.4f}")
thr = threshold_at(Gv, gv, Qv, VAL[1][1], fpir=0.01)

# The gallery grows: more people opt in (identities 400+), strangers are 500-599 only
Xs, ys, _ = make_people(5, range(500, 600), {"B": 2, "C": 2}); Qs = cnn(Xs)
known = np.isin(yq, gt)
for n_extra in (0, 30, 80):
    Xx, yx, _ = make_people(6, range(400, 400 + n_extra), {"A": 2})
    Gx, gx = templates(cnn(Xx), yx) if n_extra else (np.zeros((0, 32)), np.array([], int))
    G, gi = np.vstack([Gt, Gx]), np.concatenate([gt, gx])
    Sk = Qt[known] @ G.T
    d = float(np.mean((Sk.max(1) >= thr) & (gi[Sk.argmax(1)] == yq[known])))
    f = float(np.mean((Qs @ G.T).max(1) >= thr))
    print(f"enrolled {len(gi):3d}: DIR {d:.3f}, FPIR {f:.4f} ({int(round(f * len(ys)))} of {len(ys)} stranger crops accepted)")

# Who gets accepted wrongly? Compare the stranger's look with the enrolled person it was matched to
S = Qt @ Gt.T
for q in np.flatnonzero(~known & (S.max(1) >= thr)):
    a, b = look_of(yq[q]), look_of(gt[S[q].argmax()])
    print(f"false accept: stranger {yq[q]} -> enrolled {gt[S[q].argmax()]}, score {S[q].max():.3f}; same shirt colour {a['s'] == b['s']}, "
          f"same trousers {a['t'] == b['t']}, stripes {a['stripes'] is not None}/{b['stripes'] is not None}, bag {a['bag'] is not None}/{b['bag'] is not None}")
# And which enrolled queries are rejected or confused?
right = gt[S.argmax(1)] == yq
print(f"enrolled crops: {int(known.sum())}; identified {int((known & right & (S.max(1) >= thr)).sum())}, "
      f"right person but below the threshold {int((known & right & (S.max(1) < thr)).sum())}, wrong person first {int((known & ~right).sum())}")
step   1: batch-hard loss 0.691
step 100: batch-hard loss 0.011
step 400: batch-hard loss 0.012
FPIR target  threshold  test DIR  test FPIR
  0.005      0.986      0.650     0.0013
  0.010      0.985      0.662     0.0013
  0.050      0.973      0.875     0.0063
enrolled  20: DIR 0.662, FPIR 0.0000 (0 of 400 stranger crops accepted)
enrolled  50: DIR 0.662, FPIR 0.0050 (2 of 400 stranger crops accepted)
enrolled 100: DIR 0.662, FPIR 0.0225 (9 of 400 stranger crops accepted)
false accept: stranger 484 -> enrolled 300, score 0.990; same shirt colour True, same trousers True, stripes False/False, bag False/False
enrolled crops: 80; identified 53, right person but below the threshold 24, wrong person first 3

Operating point. A looser target on validation buys DIR: at the 5 % validation threshold the test DIR is 0.875. But the test FPIR there is only 0.63 %, not 5 %: the FPIR estimates are noisy because the stranger crops are not independent. A stranger who looks like an enrolled visitor produces a false accept from all four of their crops, so the effective sample size is closer to 100 stranger identities than 400 crops. Estimating a 1 % rate well needs thousands of stranger identities.

Gallery growth. At the fixed threshold, with 20 enrolled visitors none of the 400 crops of strangers 500 to 599 is accepted; with 50 it is 2 (0.5 %), with 100 it is 9 (2.25 %), over the target. Every enrolled template is one more chance for a stranger to find a lookalike, so FPIR grows roughly in proportion to the gallery size (FPIR≈N⋅FAR\text{FPIR} \approx N \cdot \text{FAR} for a small per-comparison FAR, as in face recognition). The threshold must be recalibrated for the gallery size the service will really have, or the gallery capped. DIR does not change (0.662), because the enrolled visitors' own scores do not depend on who else is enrolled.

Errors. The one false accept on the test set is the predictable one: stranger 484 matched visitor 300 with a score of 0.990, and they have the same shirt colour, the same trouser colour, no stripes and no bag. Nothing in a 64 x 32 crop separates them. Of the 80 crops of enrolled visitors, 53 are identified, 24 have the right person first but below the threshold, and only 3 have the wrong person first: the remaining loss is the price of the strict threshold, not of confusion. For a photo service that is the right trade: a missed photo is a disappointment, a wrong photo is a privacy incident. Ask the error analysis question for each group: would more training data, a larger crop, or a second cue (time and place, see spatio-temporal constraints) fix it?

The trade-off has the shape of the verification lab of face recognition: positives are the enrolled visitors' scores, negatives the strangers', and the strangers are the large majority. Set a small share of positives and move the threshold:

05010005scorecountScores by true classpositive →← negativenegativepositivepredicted +predicted −actual posactual neg27TP23FN11FP939TNprecision 0.711 recall 0.540 F1 0.6140.00.51.00.00.51.0false positive rateTPRROC curveAUC 0.956- - chance0.00.51.00.00.51.0recallprecisionPrecision-recallAP 0.683- - chance

The lab's scores are the textbook model (strangers ~ N(0, 1), enrolled ~ N(d, 1)), not this project's CNN, but the shape of the decision is the same. With 5 % enrolled queries, d=2.5d = 2.5 and the threshold at 2.3, 11 of 950 strangers are accepted (false positive rate 0.012) while only 27 of 50 enrolled queries are found (recall 0.540): the operating point sits at the far left of the ROC curve, where the curve is steep and every small step of the threshold trades many found visitors for a few strangers. Move the threshold right to see the FPIR fall to 0 and DIR follow it down; raise dd, a better embedding, to see both improve at once.

Step 4: the service, with deletion built in

The service has three endpoints: POST /enrolments (consent and kiosk crops in, a random token out), POST /identify (a crop in, a token or nothing out) and DELETE /enrolments/{token}. The rules are in the code, not in a policy document:

  • consent must be literally true, so an enrolment without an opt-in fails validation with a 422;
  • the kiosk crops are turned into one template and discarded; the gallery stores a template, a token and an expiry, no name and no image;
  • a query that does not match is answered and forgotten; the audit log records that a query happened and whether it matched, never what was seen;
  • deleting a token removes the template, so the next query of that person is unknown. Because the embedding network was trained on other people (identities 0 to 99), deletion needs no retraining: the enrolled person's data was never in the model. This is a strong argument for the design, and it should be stated in the data protection impact assessment.

The service runs in the browser with the grey-world histogram features of step 1, because PyTorch is not available there; in production embed would run the CNN of step 2, for example exported to ONNX (ONNX export), with the threshold recalibrated for it. The API is the same.

python · try it yourself
import numpy as np
import cv2
cv2.setLogLevel(0)

SHIRTS = np.array([[200, 40, 40], [40, 90, 200], [40, 150, 60], [230, 200, 50], [240, 240, 235], [35, 35, 40], [150, 60, 170], [240, 140, 40]])
TROUSERS = np.array([[30, 40, 90], [40, 40, 45], [120, 100, 70], [170, 170, 165], [70, 90, 60], [20, 30, 50]])
CAMS = {"A": ([1.0, 1.0, 1.0], 1.0), "B": ([1.2, 1.0, 0.75], 0.8), "C": ([0.8, 0.95, 1.2], 1.25)}

def make_look(rng):
    """An identity: shirt and trouser colour from small palettes (many people share them), shirt
    stripes or not, a bag or not, hair tone."""
    s, t = int(rng.integers(8)), int(rng.integers(6))
    return dict(s=s, t=t, shirt=SHIRTS[s] + rng.integers(-15, 16, 3), trousers=TROUSERS[t] + rng.integers(-15, 16, 3),
                stripes=SHIRTS[rng.integers(8)] if rng.random() < 0.4 else None,
                bag=rng.integers(40, 220, 3) if rng.random() < 0.4 else None, hair=int(rng.integers(20, 160)))

def make_crop(rng, look, cam, h=64, w=32):
    """A 64 x 32 RGB crop of the identity seen by camera A (enrolment kiosk), B or C."""
    img = rng.normal(100, 18, (h, w, 3))
    dx = int(rng.integers(-3, 4))
    img[2:7, 12 + dx:20 + dx] = look["hair"]
    img[6:15, 12 + dx:20 + dx] = [200, 160, 130]
    img[15:37, 8 + dx:24 + dx] = look["shirt"]
    if look["stripes"] is not None:
        img[17:37:5, 8 + dx:24 + dx] = look["stripes"]; img[18:37:5, 8 + dx:24 + dx] = look["stripes"]
    img[37:62, 10 + dx:22 + dx] = look["trousers"]
    if look["bag"] is not None:
        img[28:42, 22 + dx:28 + dx] = look["bag"]
    if rng.random() < 0.5:
        img = img[:, ::-1]                                    # walking the other way
    gain, gamma = CAMS[cam]
    img = (img * rng.uniform(0.75, 1.25) * np.array(gain)).clip(0, 255)
    img = 255 * (img / 255) ** gamma + rng.normal(0, 7, (h, w, 3))
    return img.clip(0, 255).astype(np.uint8)

def look_of(i):
    return make_look(np.random.default_rng(1000 + i))      # the look of identity i depends only on i

def make_people(seed, ids, n_per_cam):
    """Crops of the given identities: n_per_cam = {camera: crops per person}. Returns images, ids, cameras."""
    rng = np.random.default_rng(seed)
    X, y, c = [], [], []
    for i in ids:
        look = look_of(i)
        for cam, n in n_per_cam.items():
            for _ in range(n):
                X.append(make_crop(rng, look, cam)); y.append(i); c.append(cam)
    return np.array(X), np.array(y), np.array(c)

def grey_world(img):
    """Scale each channel to the same mean: undoes a camera's colour gain, not its tone curve."""
    f = img.astype(float); m = f.reshape(-1, 3).mean(0)
    return (f * m.mean() / m).clip(0, 255).astype(np.uint8)

def hsv_stripes(img, bins=(12, 4)):
    """Colour histograms of head, torso and legs (the baseline of the CV person re-ID lesson)."""
    hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    f = [np.sqrt(cv2.calcHist([np.ascontiguousarray(hsv[a:b])], [0, 1], None, list(bins), [0, 180, 0, 256]).ravel() / ((b - a) * img.shape[1])) for a, b in [(0, 15), (15, 37), (37, 64)]]
    f = np.concatenate(f)
    return f / np.linalg.norm(f)

def open_set(G, g_ids, Q, q_ids, thr):
    """Cosine similarity of every query to every enrolled template. A query is accepted if its best
    score >= thr. DIR: enrolled queries accepted with the right identity; FPIR: strangers accepted."""
    S = Q @ G.T
    best, who = S.max(1), g_ids[S.argmax(1)]
    known = np.isin(q_ids, g_ids)
    dir_ = np.mean((best[known] >= thr) & (who[known] == q_ids[known]))
    fpir = np.mean(best[~known] >= thr)
    return float(dir_), float(fpir)

def threshold_at(G, g_ids, Q, q_ids, fpir=0.01):
    """The smallest threshold whose FPIR on these strangers is at most `fpir`."""
    S = Q @ G.T
    s = np.sort(S.max(1)[~np.isin(q_ids, g_ids)])[::-1]
    k = int(np.floor(fpir * len(s)))
    return float(s[k]) + 1e-6

def templates(F, y):
    """One template per enrolled person: the normalised mean of their enrolment features."""
    ids = np.unique(y)
    T = np.array([F[y == i].mean(0) for i in ids])
    return T / np.linalg.norm(T, axis=1, keepdims=True), ids
import asyncio, base64, secrets
import httpx
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, ConfigDict
from typing import Literal

THRESHOLD = 0.953                    # grey-world + HSV at FPIR 1 % on the validation identities (step 1)
encode = lambda img: base64.b64encode(img.tobytes()).decode()
decode = lambda s: np.frombuffer(base64.b64decode(s), np.uint8).reshape(64, 32, 3)
embed = lambda img: hsv_stripes(grey_world(img))            # production: the triplet CNN, exported to ONNX

class Enrolment(BaseModel):
    model_config = ConfigDict(extra="forbid")
    consent: Literal[True]                                  # no enrolment without an explicit opt-in
    crops: list[str]                                        # kiosk crops, base64; used once, never stored

class Query(BaseModel):
    model_config = ConfigDict(extra="forbid")
    crop: str

app = FastAPI(title="find-my-photos")
GALLERY: dict[str, dict] = {}                               # random token -> template and expiry, no name, no image
AUDIT: list[dict] = []                                      # what happened, never what was seen

@app.post("/enrolments", status_code=201)
async def enrol(e: Enrolment):
    F = np.array([embed(decode(c)) for c in e.crops])
    token = secrets.token_hex(4)
    GALLERY[token] = {"template": F.mean(0) / np.linalg.norm(F.mean(0)), "expires": "end of event day"}
    AUDIT.append({"op": "enrol", "token": token})
    return {"token": token}

@app.post("/identify")
async def identify(q: Query):
    if not GALLERY:
        return {"match": None}
    tokens = list(GALLERY)
    s = np.array([GALLERY[t]["template"] for t in tokens]) @ embed(decode(q.crop))
    k = int(s.argmax())
    hit = tokens[k] if s[k] >= THRESHOLD else None          # below the threshold: unknown, nothing is kept
    AUDIT.append({"op": "identify", "matched": hit is not None})
    return {"match": hit, "score": round(float(s[k]), 3)}

@app.delete("/enrolments/{token}", status_code=204)
async def delete(token: str):
    if GALLERY.pop(token, None) is None:
        raise HTTPException(404, "unknown token")
    AUDIT.append({"op": "delete", "token": token})

async def main():
    (Xe, ye, _), (Xq, yq, _) = make_people(3, range(300, 303), {"A": 2}), make_people(4, [300, 301, 302, 400, 401], {"B": 2})
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as c:
        r = await c.post("/enrolments", json={"consent": False, "crops": [encode(Xe[0])]})
        print("enrol without consent ->", r.status_code)
        tok = {}
        for i in (300, 301, 302):
            r = await c.post("/enrolments", json={"consent": True, "crops": [encode(x) for x in Xe[ye == i]]})
            tok[r.json()["token"]] = i
        print(f"enrolled {len(GALLERY)} visitors; the gallery stores per visitor: {sorted(next(iter(GALLERY.values())))}")
        async def ask(i):
            r = (await c.post("/identify", json={"crop": encode(Xq[yq == i][0])})).json()
            who = "unknown" if r["match"] is None else f"person {tok[r['match']]}"
            print(f"  camera B crop of person {i}: {who} (best score {r['score']})")
        for i in (300, 301, 302, 400, 401):
            await ask(i)
        t300 = next(t for t, i in tok.items() if i == 300)
        print("person 300 asks to be deleted ->", (await c.delete(f"/enrolments/{t300}")).status_code)
        await ask(300)
        print("delete again ->", (await c.delete(f"/enrolments/{t300}")).status_code)
    print("audit log:", [a["op"] + ("" if "matched" not in a else " (match)" if a["matched"] else " (unknown)") for a in AUDIT])

asyncio.run(main())
enrol without consent -> 422
enrolled 3 visitors; the gallery stores per visitor: ['expires', 'template']
  camera B crop of person 300: person 300 (best score 0.966)
  camera B crop of person 301: unknown (best score 0.924)
  camera B crop of person 302: unknown (best score 0.887)
  camera B crop of person 400: unknown (best score 0.868)
  camera B crop of person 401: unknown (best score 0.797)
person 300 asks to be deleted -> 204
  camera B crop of person 300: unknown (best score 0.801)
delete again -> 404
audit log: ['enrol', 'enrol', 'enrol', 'identify (match)', 'identify (unknown)', 'identify (unknown)', 'identify (unknown)', 'identify (unknown)', 'delete', 'identify (unknown)']

Every rule shows up in the output. The enrolment without consent is rejected (422) before any code of the service runs. The gallery holds a template and an expiry per visitor, nothing else. The camera-B crop of visitor 300 is matched (score 0.966 above 0.953), the two strangers stay unknown (0.868 and 0.797), and so, unfortunately, do visitors 301 and 302 (0.924 and 0.887): with the weak histogram features the strict threshold misses most enrolled visitors, exactly the DIR of 0.200 of step 1, which is why production needs the CNN. After visitor 300 asks to be deleted, the same crop is unknown (best score 0.801, now against someone else's template), and a second delete gets a 404. The audit log tells an auditor what the service did, and nothing about what it saw.

Extensions

  • Larger crops and a stronger backbone. Fine-tune a pretrained ResNet-18 with the same loss (partial fine-tuning) and compare DIR at the same FPIR; the CV project showed that ImageNet features alone are not enough.
  • Re-ranking and time. Use the camera layout and time stamps to drop impossible matches before thresholding.
  • Calibrated scores. Turn similarities into probabilities on validation data (calibration) so the threshold has a meaning that survives a model update.
  • Monitoring. Track the daily share of queries above the threshold and the score distribution of the best matches; a change means new cameras, new light or a different crowd (data drift).
  • Security. Tokens must not be guessable, the identify endpoint must be rate-limited, and templates are personal data at rest (ML security).

Write-up template

text
Purpose and legal basis: what the service does, consent flow, DPIA, signage, who may query
Data: identities per split (training / validation / test), cameras, what the generator or pilot lacks
Model: architecture, loss, sampling, training identities only
Threshold: target FPIR, chosen on validation; gallery size it was calibrated for
Results (test, once): DIR and FPIR with the number of identities and crops; rank-1 for comparison
Errors: false accepts (lookalikes?), misses (below threshold vs wrong person)
Data lifecycle: what is stored, retention, deletion on request, audit log contents
Limitations: clothing changes, uniforms, crowds, small samples

Practice

  1. Why are the threshold and the test numbers computed on different enrolled people and strangers, and not on the training identities?
Answer

The network was trained to separate identities 0 to 99, so their scores are better than those of new people; a threshold chosen on them would be too loose for real visitors. Validation identities are new to the model and stand in for future visitors; test identities are used once to report the result (data leakage).

  1. The fair expects 400 visitors to opt in. What do you change before the day, and how do you check it?
Answer

At 100 enrolled the FPIR was already 2.25 % at the threshold calibrated for 20. Recalibrate on validation with a gallery of about 400 enrolled identities (and many more stranger identities than 100, since the estimate is noisy), accept the lower DIR that the stricter threshold brings, and measure DIR and FPIR again at that gallery size. Alternatively split the gallery, for example by the hall and the time the visitor enrolled.

  1. A visitor asks to be deleted at 14:00. Which data about them still exists after DELETE, and is that acceptable?
Answer

The template is gone, and the kiosk crops were never stored. The audit log keeps "enrol" and "delete" entries with the token, and "identify" entries without any reference to the person. The model weights contain nothing about them because they were not a training identity. Photos already delivered to them are theirs. Whether the token in the audit log may be kept is a retention question for the DPIA; it can be dropped at the end of the day too.

  1. In step 3, change the margin of the triplet loss to 0.1 and to 0.5 and compare DIR at the 1 % threshold. What would you expect, and why should the choice be made on validation?
Answer

A larger margin pushes impostors further away, which helps the open set, until it becomes too hard to satisfy and training gets noisy; the best value depends on the data. Run it to see. The margin is a hyperparameter, so it is chosen on validation DIR at the validation threshold; the test set is used once for the chosen model.

Test yourself

Grey-world histograms reach a test rank-1 of 0.912, the triplet CNN 0.963. Why is the CNN still the only acceptable model?

  1. Rank-1 is computed wrongly for histograms
  2. Open-set use needs strangers' scores to stay below real matches: at FPIR 1 % on validation, grey-world identifies 0.200 of enrolled crops on test with an FPIR of 2.25 %, the CNN 0.662 at 0.13 %
  3. The CNN is faster
  4. Histograms cannot be stored

At a fixed threshold, the gallery grows from 20 to 100 enrolled visitors. What happens to FPIR on the same strangers?

  1. It stays at 0
  2. It rises, from 0 to 2.25 % here, because every template is one more chance for a lookalike
  3. It falls, because the model sees more people
  4. DIR rises with it

Why can an enrolled visitor be deleted without retraining the model?

  1. Deep networks forget automatically
  2. The embedding was trained on other identities (0 to 99); the visitor exists only as a template in the gallery, which DELETE removes
  3. Because the template is encrypted
  4. Retraining is needed, but only at night

The validation threshold for FPIR 5 % gave a test FPIR of only 0.63 %. What does that show?

  1. The test set is easier, so report 0.63 %
  2. FPIR estimates are noisy: a lookalike stranger fails with all their crops, so the effective sample is about the number of stranger identities, and a 1 % rate needs many thousands of them to estimate well
  3. The model overfitted the validation set
  4. The threshold was computed on the test set

Which of these does the service store after a stranger's crop is queried and not matched?

  1. The crop, for retraining
  2. The crop's embedding, to detect repeat visitors
  3. Only an audit entry saying a query happened and did not match
  4. The stranger's token