File size: 1,537 Bytes
618ca1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import torch


@dataclass(frozen=True)
class Prototypes:
    vectors: torch.Tensor

    @property
    def device(self) -> torch.device:
        return self.vectors.device


@torch.no_grad()
def build_class_prototypes(
    model: torch.nn.Module,
    loader,
    device: torch.device,
    num_classes: int = 10,
) -> Prototypes:
    model.eval()
    sums = None
    counts = torch.zeros(num_classes, device=device)

    for x, y in loader:
        x = x.to(device)
        y = y.to(device)
        feats = model.forward_features(x)
        if sums is None:
            sums = torch.zeros(num_classes, feats.size(1), device=device)

        onehot = torch.zeros(x.size(0), num_classes, device=device)
        onehot.scatter_(1, y.view(-1, 1), 1.0)
        sums += onehot.t().matmul(feats)
        counts += onehot.sum(dim=0)

    prototypes = sums / counts.clamp_min(1.0).view(-1, 1)
    prototypes = torch.nn.functional.normalize(prototypes, dim=1)
    return Prototypes(vectors=prototypes)


def save_prototypes(prototypes: Prototypes, path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    torch.save({"prototypes": prototypes.vectors.cpu()}, path)


def load_prototypes(path: Path, device: torch.device) -> Prototypes:
    payload = torch.load(path, map_location=device)
    vectors = payload["prototypes"].to(device)
    vectors = torch.nn.functional.normalize(vectors, dim=1)
    return Prototypes(vectors=vectors)