Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

classification_metrics.py 2.9 KB

You have to be logged in to leave a comment. Sign In
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  1. from super_gradients.training.utils import convert_to_tensor
  2. import torch
  3. import torchmetrics
  4. from torchmetrics import Metric
  5. def accuracy(output, target, topk=(1,)):
  6. """Computes the precision@k for the specified values of k
  7. :param output: Tensor / Numpy / List
  8. The prediction
  9. :param target: Tensor / Numpy / List
  10. The corresponding lables
  11. :param topk: tuple
  12. The type of accuracy to calculate, e.g. topk=(1,5) returns accuracy for top-1 and top-5"""
  13. # Convert to tensor
  14. output = convert_to_tensor(output)
  15. target = convert_to_tensor(target)
  16. # Get the maximal value of the accuracy measurment and the batch size
  17. maxk = max(topk)
  18. batch_size = target.size(0)
  19. # Get the top k predictions
  20. _, pred = output.topk(maxk, 1, True, True)
  21. pred = pred.t()
  22. # Count the number of correct predictions only for the highest k
  23. correct = pred.eq(target.view(1, -1).expand_as(pred))
  24. res = []
  25. for k in topk:
  26. # Count the number of correct prediction for the different K (the top predictions) values
  27. correct_k = correct[:k].reshape(-1).float().sum(0)
  28. res.append(correct_k.mul_(100.0 / batch_size).item())
  29. return res
  30. class Accuracy(torchmetrics.Accuracy):
  31. def __init__(self, dist_sync_on_step=False):
  32. super().__init__(dist_sync_on_step=dist_sync_on_step)
  33. def update(self, preds: torch.Tensor, target: torch.Tensor):
  34. if target.shape == preds.shape:
  35. target = target.argmax(1) # supports smooth labels
  36. super().update(preds=preds.argmax(1), target=target)
  37. class Top5(Metric):
  38. def __init__(self, dist_sync_on_step=False):
  39. super().__init__(dist_sync_on_step=dist_sync_on_step)
  40. self.add_state("correct", default=torch.tensor(0.), dist_reduce_fx="sum")
  41. self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
  42. def update(self, preds: torch.Tensor, target: torch.Tensor):
  43. if target.shape == preds.shape:
  44. target = target.argmax(1) # supports smooth labels
  45. # Get the maximal value of the accuracy measurment and the batch size
  46. batch_size = target.size(0)
  47. # Get the top k predictions
  48. _, pred = preds.topk(5, 1, True, True)
  49. pred = pred.t()
  50. # Count the number of correct predictions only for the highest 5
  51. correct = pred.eq(target.view(1, -1).expand_as(pred))
  52. correct5 = correct[:5].reshape(-1).float().sum(0)
  53. self.correct += correct5
  54. self.total += batch_size
  55. def compute(self):
  56. return self.correct.float() / self.total
  57. class ToyTestClassificationMetric(Metric):
  58. """
  59. Dummy classification Mettric object returning 0 always (for testing).
  60. """
  61. def __init__(self, dist_sync_on_step=False):
  62. super().__init__(dist_sync_on_step=dist_sync_on_step)
  63. def update(self, preds: torch.Tensor, target: torch.Tensor) -> None:
  64. pass
  65. def compute(self):
  66. return 0
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...