Handball officials' cards (Oficial A-F) are learnt and read like shirt numbers
Team officials wear an accreditation card with a letter; B is usually the head coach. A person whose number is a letter A-F (or "Oficial B") gets samples labelled with it, the review accepts the letter, and the model has a letter head next to the digits (labels 0-99, A-F, illegible). Synthetic data paints cards on lanyards too. Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
1 parent
c32012a0cd
commit
706aa8a5df
10 files changed
+122
-38
No files matched your search
@@ -7,6 +7,7 @@ import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { type Box, numberBoxes } from "../jersey/crop.js";
|
||||
import type { JerseyReading } from "../jersey/model.js";
|
||||
import { normLabel } from "../jersey/service.js";
|
||||
|
||||
/** Below this the shirt-number reading is not used for suggestions. */
|
||||
export const JERSEY_MIN_SCORE = 0.7;
|
||||
@@ -255,7 +256,7 @@ export class FaceService {
|
||||
}
|
||||
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(norm);
|
||||
const candidates = (await db.person.findMany({ where: { organizationId: event.organizationId, number: { not: null }, club: { not: null } } }))
|
||||
.filter((p) => String(Number(p.number!.trim())) === read.number)
|
||||
.filter((p) => normLabel(p.number) === read.number)
|
||||
.filter((p) => {
|
||||
const club = norm(p.club!);
|
||||
return teams.some((t) => t && (t.includes(club) || club.includes(t)));
|
||||
|
||||
@@ -18,8 +18,8 @@ export interface JerseyReading {
|
||||
}
|
||||
|
||||
/**
|
||||
* The shirt-number model trained with workers/ml/jersey (ONNX): the torso crop in, a number 0-99 or
|
||||
* "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
|
||||
* The shirt-number model trained with workers/ml/jersey (ONNX): a chest or shorts crop in, a number 0-99, a handball
|
||||
* official's card letter (A-F) or "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
|
||||
*/
|
||||
export class JerseyModel {
|
||||
private constructor(
|
||||
|
||||
@@ -18,6 +18,16 @@ export interface SampleView {
|
||||
|
||||
export const NUMBER = /^\d{1,3}$/;
|
||||
|
||||
/** What a crop can be labelled with: a shirt number, or the letter on a handball official's card (A-F; B is usually the head coach). */
|
||||
export const LABEL = /^(\d{1,3}|[A-F])$/;
|
||||
|
||||
/** "07" and "7" are the same shirt; "b" and "Oficial B" are the same card. Null when it is neither. */
|
||||
export function normLabel(raw: string | null | undefined): string | null {
|
||||
const s = (raw ?? "").trim().replace(/^oficial\s*/i, "").toUpperCase();
|
||||
if (NUMBER.test(s)) return String(Number(s));
|
||||
return LABEL.test(s) ? s : null;
|
||||
}
|
||||
|
||||
/** Bumped when the crops change (2: chest and shorts), so faces collected before get the new ones once. */
|
||||
export const JERSEY_CROPS = 2;
|
||||
|
||||
@@ -62,7 +72,7 @@ export class JerseyService {
|
||||
for (const { region, box } of boxes) {
|
||||
if (have.has(region)) continue;
|
||||
await db.jerseySample.create({
|
||||
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: person!.number!.trim() },
|
||||
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: normLabel(person!.number) ?? person!.number!.trim() },
|
||||
});
|
||||
added++;
|
||||
}
|
||||
@@ -90,10 +100,8 @@ export class JerseyService {
|
||||
}
|
||||
|
||||
async review(sample: JerseySample, userId: string, input: { status: "CONFIRMED" | "ILLEGIBLE" | "SKIPPED" | "PENDING"; label?: string | null | undefined }): Promise<JerseySample> {
|
||||
const raw = input.status === "CONFIRMED" ? (input.label ?? sample.suggested)?.trim() : null;
|
||||
// "07" and "7" are the same shirt.
|
||||
const label = raw && NUMBER.test(raw) ? String(Number(raw)) : raw;
|
||||
if (input.status === "CONFIRMED" && (!label || !NUMBER.test(label))) throw new Error("label_required");
|
||||
const label = input.status === "CONFIRMED" ? normLabel(input.label ?? sample.suggested) : null;
|
||||
if (input.status === "CONFIRMED" && !label) throw new Error("label_required");
|
||||
return this.deps.db.jerseySample.update({
|
||||
where: { id: sample.id },
|
||||
data: { status: input.status, label: label ?? null, reviewedById: input.status === "PENDING" ? null : userId, reviewedAt: input.status === "PENDING" ? null : new Date() },
|
||||
@@ -129,7 +137,7 @@ export class JerseyService {
|
||||
return {
|
||||
version: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
classes: "0-99 and 'illegible'",
|
||||
classes: "0-99, A-F (officials' cards) and 'illegible'",
|
||||
samples: samples.map((s) => ({ id: s.id, region: s.region, label: s.status === "ILLEGIBLE" ? "illegible" : s.label!, crop: this.cropUrl(s.id) })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -296,7 +296,7 @@ describe("faces", () => {
|
||||
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { collected: number; samples: { id: string; suggested: string; crop: string; person: string }[] };
|
||||
expect(list.collected).toBe(4); // chest and shorts of two faces
|
||||
expect(list.samples.map((x) => (x as unknown as { region: string }).region).sort()).toEqual(["CHEST", "CHEST", "SHORTS", "SHORTS"]);
|
||||
expect(list.samples[0]).toMatchObject({ suggested: "07", person: "Miguel Silva (VSC)" });
|
||||
expect(list.samples[0]).toMatchObject({ suggested: "7", person: "Miguel Silva (VSC)" });
|
||||
const crop = await ctx.app.inject({ method: "GET", url: list.samples[0]!.crop });
|
||||
expect(crop.statusCode).toBe(200);
|
||||
expect((await sharp(crop.rawPayload).metadata()).height).toBeLessThanOrEqual(256);
|
||||
@@ -309,6 +309,13 @@ describe("faces", () => {
|
||||
const dataset = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/dataset`, headers: bearer(token) })).json() as { samples: { label: string }[] };
|
||||
expect(dataset.samples.map((s) => s.label).sort()).toEqual(["7", "illegible"]);
|
||||
|
||||
// A handball official's card: the letter is a label like a number.
|
||||
const card = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "b" } });
|
||||
expect(card.json()).toMatchObject({ status: "CONFIRMED", label: "B" });
|
||||
const bad = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[3]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "Z" } });
|
||||
expect(bad.statusCode).toBe(400);
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "PENDING" } });
|
||||
|
||||
// Starting over: every answer is dropped, the samples are to review again.
|
||||
const reset = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/jersey/reset`, headers: bearer(token) });
|
||||
expect(reset.json()).toEqual({ reset: 2 });
|
||||
|
||||
@@ -24,3 +24,16 @@ describe("shirt-number crops", () => {
|
||||
expect(numberBoxes(low, W, H).map((b) => b.region)).toEqual(["CHEST"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("labels", () => {
|
||||
it("reads shirt numbers and handball officials' cards the same way", async () => {
|
||||
const { normLabel } = await import("../src/jersey/service.js");
|
||||
expect(normLabel("07")).toBe("7");
|
||||
expect(normLabel(" 10 ")).toBe("10");
|
||||
expect(normLabel("b")).toBe("B");
|
||||
expect(normLabel("Oficial B")).toBe("B");
|
||||
expect(normLabel("G")).toBeNull();
|
||||
expect(normLabel("1234")).toBeNull();
|
||||
expect(normLabel(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -380,7 +380,7 @@ export const t = {
|
||||
numbers: {
|
||||
title: "Números das camisolas",
|
||||
counts: (pending: number, ok: number, bad: number) => `por rever ${pending} · certos ${ok} · ilegíveis ${bad}`,
|
||||
keys: "⏎ certo · dígitos + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
|
||||
keys: "⏎ certo · dígitos (ou A–F, oficiais) + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
|
||||
cropAlt: "Recorte do jogador",
|
||||
region: { CHEST: "peito", SHORTS: "calção" } as Record<"CHEST" | "SHORTS", string>,
|
||||
squadSays: (n: string) => `o plantel diz ${n}`,
|
||||
@@ -392,7 +392,7 @@ export const t = {
|
||||
empty: "Nada por rever. Confirma grupos em Caras (com o número no plantel) e aparecem aqui os recortes.",
|
||||
collected: (n: number) => `${n} recortes novos a partir das caras confirmadas.`,
|
||||
perNumber: "Exemplos por número",
|
||||
help: "Cada recorte é o peito ou o calção de alguém já identificado pela cara (no futebol o número da frente está no calção; no andebol, no peito); o número vem do plantel. Aqui ensinas a ler o número, não a reconhecer o jogador: só é \"Certo\" se o número se lê inteiro no recorte. Número tapado, cortado, só meio visível ou sem número: \"Não se lê\", mesmo que o jogador esteja certo. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
|
||||
help: "Cada recorte é o peito ou o calção de alguém já identificado pela cara (no futebol o número da frente está no calção; no andebol, no peito); o número vem do plantel. Aqui ensinas a ler o número, não a reconhecer o jogador: só é \"Certo\" se o número se lê inteiro no recorte. Número tapado, cortado, só meio visível ou sem número: \"Não se lê\", mesmo que o jogador esteja certo. No andebol, os oficiais da equipa têm um cartão ao pescoço com uma letra (A a F; o B é normalmente o treinador principal): escreve a letra como se fosse o número. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
|
||||
reset: "Recomeçar o ensino",
|
||||
resetConfirm: (n: number) => `Apagar as ${n} respostas e rever tudo de novo`,
|
||||
resetCancel: "Cancelar",
|
||||
|
||||
@@ -74,7 +74,11 @@ export function NumbersPage() {
|
||||
if (isTyping(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;
|
||||
if (/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
setTyped((x) => (x + e.key).slice(-3));
|
||||
setTyped((x) => (/^\d*$/.test(x) ? x + e.key : e.key).slice(-3));
|
||||
} else if (/^[a-f]$/i.test(e.key)) {
|
||||
// A handball official's card (Oficial A..F): one letter, never mixed with digits.
|
||||
e.preventDefault();
|
||||
setTyped(e.key.toUpperCase());
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
void answer("CONFIRMED", typed || undefined);
|
||||
@@ -135,9 +139,13 @@ export function NumbersPage() {
|
||||
<input
|
||||
aria-label={t.numbers.other}
|
||||
placeholder={t.numbers.other}
|
||||
inputMode="numeric"
|
||||
inputMode="text"
|
||||
value={typed}
|
||||
onChange={(e) => setTyped(e.target.value.replace(/\D/g, "").slice(0, 3))}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value.toUpperCase();
|
||||
const letter = /[A-F]/.exec(v)?.[0];
|
||||
setTyped(letter ?? v.replace(/\D/g, "").slice(0, 3));
|
||||
}}
|
||||
onKeyDown={(e) => e.key === "Enter" && void answer("CONFIRMED", typed || undefined)}
|
||||
className="h-9 w-28 border border-black bg-[#161617] px-2 text-center font-mono text-[15px] text-ink"
|
||||
/>
|
||||
|
||||
@@ -10,6 +10,8 @@ The loop:
|
||||
1. **Collect.** Every face in a group confirmed as a squad player who has a number becomes two samples, both
|
||||
labelled with the squad's number: the chest (where handball kits carry the front number) and the shorts (where
|
||||
football kits carry it; Liga Portugal shirts have none on the chest).
|
||||
Handball team officials wear an accreditation card with a letter (Oficial A to F; B is usually the head coach). Give
|
||||
an official the letter as their number ("B") and their cards are learnt and read like shirt numbers.
|
||||
2. **Check.** In the app, go to **Caras → Números das camisolas**. The keys are:
|
||||
- ⏎ the number is right;
|
||||
- digits then ⏎ to correct it;
|
||||
|
||||
@@ -7,7 +7,7 @@ Each sample is a torso-like crop with a number painted on it: on a real crop (so
|
||||
look real) or on a plain shirt colour. The number is drawn in a sporty font, in a colour that stands out, sometimes
|
||||
outlined, then warped like cloth: tilted, in perspective, rippled, blurred. It is written to <out>/<id>.jpg and listed in
|
||||
<out>/dataset.json, in the same format as the dataset from the app (label = the number, or "illegible" for shirts
|
||||
painted without one). Mix it with the real dataset in train.py (--extra); the check keeps using real crops only.
|
||||
painted without one); now and then the crop gets a team official's card with a letter A-F instead (handball). Mix it with the real dataset in train.py (--extra); the check keeps using real crops only.
|
||||
|
||||
Fonts: any .ttf/.otf/.woff in --fonts. Free sporty ones (Oswald, Anton, Bebas Neue, Teko, Saira Condensed, ...)
|
||||
come from npm: `npm pack @fontsource/oswald` and so on.
|
||||
@@ -97,6 +97,21 @@ def _perspective(src, dst):
|
||||
return np.linalg.solve(a, b).tolist()
|
||||
|
||||
|
||||
def badge(letter: str, font_path: Path, rng: random.Random) -> Image.Image:
|
||||
"""A team official's accreditation card (handball): a pale card with a big letter, on a lanyard."""
|
||||
cw = int(H * rng.uniform(0.22, 0.34))
|
||||
ch = int(cw * rng.uniform(1.3, 1.6))
|
||||
card = Image.new("RGBA", (cw, ch), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(card)
|
||||
paper = tuple(rng.randint(225, 255) for _ in range(3))
|
||||
d.rounded_rectangle([0, 0, cw - 1, ch - 1], radius=max(2, cw // 12), fill=paper + (255,), outline=(120, 120, 120, 255))
|
||||
d.rectangle([0, 0, cw, int(ch * rng.uniform(0.18, 0.3))], fill=tuple(rng.randint(0, 200) for _ in range(3)) + (255,))
|
||||
ink = rng.choice([(0, 0, 0), (20, 20, 60), (60, 0, 0)])
|
||||
glyph = number_layer(letter, font_path, int(ch * rng.uniform(0.32, 0.45)), ink, None, rng)
|
||||
card.paste(glyph, ((cw - glyph.width) // 2, int(ch * 0.62) - glyph.height // 2), glyph)
|
||||
return card.rotate(rng.uniform(-12, 12), resample=Image.BICUBIC, expand=True)
|
||||
|
||||
|
||||
def sample(rng: random.Random, backgrounds: list[Path], fonts: list[Path], with_number: bool):
|
||||
if backgrounds and rng.random() < 0.6:
|
||||
bg = Image.open(rng.choice(backgrounds)).convert("RGB")
|
||||
@@ -106,6 +121,16 @@ def sample(rng: random.Random, backgrounds: list[Path], fonts: list[Path], with_
|
||||
w = bg.width
|
||||
if not with_number:
|
||||
return bg, "illegible"
|
||||
if rng.random() < 0.08: # an official's card instead of a shirt number
|
||||
letter = rng.choice("ABCDEF")
|
||||
card = badge(letter, rng.choice(fonts), rng)
|
||||
x = int((w - card.width) / 2 + rng.uniform(-0.2, 0.2) * w)
|
||||
x = max(0, min(w - card.width, x))
|
||||
y = int(H * rng.uniform(0.15, 0.6))
|
||||
d = ImageDraw.Draw(bg)
|
||||
d.line([(x + card.width // 2, 0), (x + card.width // 2, y)], fill=tuple(rng.randint(0, 255) for _ in range(3)), width=3)
|
||||
bg.paste(card, (x, y), card)
|
||||
return bg, letter
|
||||
n = rng.choice([rng.randint(1, 30), rng.randint(1, 30), rng.randint(0, 99)])
|
||||
region = bg.crop((w // 3, H // 4, 2 * w // 3, H // 2)).resize((1, 1)).getpixel((0, 0))
|
||||
fill = contrasting(region, rng)
|
||||
|
||||
+42
-22
@@ -3,10 +3,12 @@
|
||||
|
||||
python train.py --dataset jersey-dataset-2026-10-12.json --api https://api.photoreport.pt --out models/jersey-v1
|
||||
|
||||
The model looks at the torso crop under a face and reads it digit by digit: is there a legible number, what is the
|
||||
tens digit (or none), what is the units digit. Reading digits instead of whole numbers means every "20" also teaches
|
||||
the model what a 2 and a 0 look like, so it needs far fewer examples per number. The exported model still answers
|
||||
one probability per number 0-99 plus "illegible" (the worker does not need to know how it reads).
|
||||
The model looks at a crop under a face (chest or shorts) and reads it digit by digit: is there a legible number (or a
|
||||
team official's badge letter), what is the tens digit (or none), what is the units digit. Reading digits instead of
|
||||
whole numbers means every "20" also teaches the model what a 2 and a 0 look like, so it needs far fewer examples per
|
||||
number. Handball officials wear a card on a lanyard with a letter, A to F (B is usually the head coach): that letter
|
||||
is read the same way. The exported model still answers one probability per label: 0-99, A-F, "illegible" (the worker
|
||||
does not need to know how it reads).
|
||||
|
||||
It runs on the Mac's GPU (MPS) when there is one, else CUDA, else the CPU. The output folder gets `jersey.onnx`
|
||||
(what the worker runs), `labels.json` and `metrics.json` (accuracy on crops kept out of training).
|
||||
@@ -29,7 +31,9 @@ from torch.utils.data import DataLoader, Dataset
|
||||
from torchvision import models, transforms
|
||||
|
||||
SIZE = 160
|
||||
LABELS = [str(n) for n in range(100)] + ["illegible"]
|
||||
NUMBERS = [str(n) for n in range(100)]
|
||||
LETTERS = list("ABCDEF") # handball team officials' badges ("Oficial A".."F")
|
||||
LABELS = NUMBERS + LETTERS + ["illegible"]
|
||||
MEAN, STD = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
|
||||
|
||||
|
||||
@@ -92,17 +96,27 @@ ILLEGIBLE = len(LABELS) - 1
|
||||
IGNORE = -100
|
||||
|
||||
|
||||
def targets(y: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Class index -> (legible 0/1, tens 0=none or 1+digit, units digit); digits are ignored for illegible crops."""
|
||||
legible = (y != ILLEGIBLE).long()
|
||||
n = torch.where(legible.bool(), y, torch.zeros_like(y))
|
||||
KIND_ILLEGIBLE, KIND_NUMBER, KIND_LETTER = 0, 1, 2
|
||||
|
||||
|
||||
def targets(y: torch.Tensor):
|
||||
"""Class index -> (kind, tens 0=none or 1+digit, units digit, letter); the parts that don't apply are ignored."""
|
||||
is_number = y < len(NUMBERS)
|
||||
is_letter = (y >= len(NUMBERS)) & (y != ILLEGIBLE)
|
||||
kind = torch.full_like(y, KIND_ILLEGIBLE)
|
||||
kind = torch.where(is_number, torch.full_like(y, KIND_NUMBER), kind)
|
||||
kind = torch.where(is_letter, torch.full_like(y, KIND_LETTER), kind)
|
||||
n = torch.where(is_number, y, torch.zeros_like(y))
|
||||
tens = torch.where(n >= 10, 1 + n // 10, torch.zeros_like(n))
|
||||
units = n % 10
|
||||
return legible, torch.where(legible.bool(), tens, IGNORE), torch.where(legible.bool(), units, IGNORE)
|
||||
letter = torch.where(is_letter, y - len(NUMBERS), torch.zeros_like(y))
|
||||
ignore = torch.full_like(y, IGNORE)
|
||||
return kind, torch.where(is_number, tens, ignore), torch.where(is_number, units, ignore), torch.where(is_letter, letter, ignore)
|
||||
|
||||
|
||||
class DigitReader(nn.Module):
|
||||
"""ResNet18 with three small heads: legible?, tens digit (or none), units digit."""
|
||||
"""ResNet18 with four small heads: what is there (nothing legible, a number, a badge letter), tens digit (or
|
||||
none), units digit, letter."""
|
||||
|
||||
def __init__(self, pretrained: bool):
|
||||
super().__init__()
|
||||
@@ -110,17 +124,18 @@ class DigitReader(nn.Module):
|
||||
m.fc = nn.Identity()
|
||||
self.backbone = m
|
||||
self.drop = nn.Dropout(0.3)
|
||||
self.legible = nn.Linear(512, 2)
|
||||
self.kind = nn.Linear(512, 3)
|
||||
self.tens = nn.Linear(512, 11)
|
||||
self.units = nn.Linear(512, 10)
|
||||
self.letter = nn.Linear(512, len(LETTERS))
|
||||
|
||||
def forward(self, x):
|
||||
f = self.drop(self.backbone(x))
|
||||
return self.legible(f), self.tens(f), self.units(f)
|
||||
return self.kind(f), self.tens(f), self.units(f), self.letter(f)
|
||||
|
||||
|
||||
class NumberProbs(nn.Module):
|
||||
"""For export: digit probabilities -> one probability per label (0..99, illegible), the format the worker reads."""
|
||||
"""For export: head probabilities -> one probability per label (0..99, A..F, illegible), the format the worker reads."""
|
||||
|
||||
def __init__(self, reader: DigitReader):
|
||||
super().__init__()
|
||||
@@ -134,17 +149,18 @@ class NumberProbs(nn.Module):
|
||||
self.register_buffer("tens_mask", mask)
|
||||
|
||||
def forward(self, x):
|
||||
legible, tens, units = self.reader(x)
|
||||
p_leg = torch.softmax(legible, 1)
|
||||
kind, tens, units, letter = self.reader(x)
|
||||
p_kind = torch.softmax(kind, 1)
|
||||
p_tens = torch.softmax(tens, 1) * self.tens_mask
|
||||
p_tens = p_tens / p_tens.sum(1, keepdim=True)
|
||||
p_units = torch.softmax(units, 1)
|
||||
numbers = p_leg[:, 1:2] * p_tens[:, self.tens_idx] * p_units[:, self.units_idx]
|
||||
return torch.cat([numbers, p_leg[:, 0:1]], 1)
|
||||
numbers = p_kind[:, KIND_NUMBER : KIND_NUMBER + 1] * p_tens[:, self.tens_idx] * p_units[:, self.units_idx]
|
||||
letters = p_kind[:, KIND_LETTER : KIND_LETTER + 1] * torch.softmax(letter, 1)
|
||||
return torch.cat([numbers, letters, p_kind[:, KIND_ILLEGIBLE : KIND_ILLEGIBLE + 1]], 1)
|
||||
|
||||
|
||||
def evaluate(model, loader, dev):
|
||||
"""Accuracy of the final answer (number or illegible), and of the number alone on legible crops."""
|
||||
"""Accuracy of the final answer (number, letter or illegible), and of the label alone on legible crops."""
|
||||
model.eval()
|
||||
probs = NumberProbs(model).to(dev).eval()
|
||||
ok = total = num_ok = num_total = 0
|
||||
@@ -194,10 +210,14 @@ def main():
|
||||
model = DigitReader(not args.no_pretrained).to(dev)
|
||||
ce = nn.CrossEntropyLoss(ignore_index=IGNORE, label_smoothing=0.05)
|
||||
|
||||
def part(logits, target):
|
||||
# A batch with nothing of this kind (no letters, say) adds nothing, instead of NaN.
|
||||
return ce(logits, target) if (target != IGNORE).any() else logits.sum() * 0
|
||||
|
||||
def loss_fn(out, y):
|
||||
legible, tens, units = targets(y)
|
||||
lo_leg, lo_tens, lo_units = out
|
||||
return ce(lo_leg, legible) + ce(lo_tens, tens) + ce(lo_units, units)
|
||||
kind, tens, units, letter = targets(y)
|
||||
lo_kind, lo_tens, lo_units, lo_letter = out
|
||||
return ce(lo_kind, kind) + part(lo_tens, tens) + part(lo_units, units) + part(lo_letter, letter)
|
||||
|
||||
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
|
||||
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=1e-3, total_steps=args.epochs * max(1, (len(train) + args.batch - 1) // args.batch))
|
||||
|
||||
Reference in new issue
Block a user