| 27 | |
| 28 | |
| 29 | def measure_perplexity(predicted_indices: torch.Tensor, num_centroids: int) -> Tuple[torch.Tensor, torch.Tensor]: |
| 30 | # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py |
| 31 | # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally |
| 32 | encodings = F.one_hot(predicted_indices, num_centroids).float().reshape(-1, num_centroids) |
| 33 | avg_probs = encodings.mean(0) |
| 34 | perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp() |
| 35 | cluster_use = torch.sum(avg_probs > 0) |
| 36 | return perplexity, cluster_use |