Spaces:
Sleeping
Sleeping
Download src/handwriting/prototypes.py from lzpiece/IntelligentHandwrittenCGS: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/spaces/lzpiece/IntelligentHandwrittenCGS/resolve/main/src/handwriting/prototypes.py
- Command line
-
hf download hf://spaces/lzpiece/IntelligentHandwrittenCGS/src/handwriting/prototypes.py
-
curl -L -o prototypes.py https://huggingface.co/spaces/lzpiece/IntelligentHandwrittenCGS/resolve/main/src/handwriting/prototypes.py
1.54 kB
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import torch | |
| class Prototypes: | |
| vectors: torch.Tensor | |
| def device(self) -> torch.device: | |
| return self.vectors.device | |
| 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) | |