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

test_dice_metric.py 1.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
  1. import pytest
  2. from monai.losses import DiceCELoss
  3. from monai.metrics import DiceMetric
  4. import numpy as np
  5. import torch
  6. n = 5 # w/h size
  7. b = 1 # batch size
  8. sample = torch.zeros((b, 2, n, n)) # BxCxHxW
  9. sample[:, 0, :, :] = 1
  10. sample[:, 0, 2:n, 2:n] = 0
  11. sample[:, 1, 2:n, 2:n] = 1
  12. increments = [(2, 1.0), (3, 0.7401), (4, 0.5)]
  13. increments2 = [(2, 1.0), (3, 0.6154), (4, 0.2)]
  14. @pytest.mark.parametrize("inc,res", increments)
  15. def test_dicemetric_with_background(inc, res):
  16. fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
  17. fake_pred[:, 0, :, :] = 1
  18. fake_pred[:, 0, inc:n, inc:n] = 0
  19. fake_pred[:, 1, inc:n, inc:n] = 1
  20. dice_metric = DiceMetric(include_background=True, reduction="mean")
  21. score, _ = dice_metric(
  22. y_pred=fake_pred,
  23. y=sample,
  24. )
  25. result = torch.tensor([res])
  26. torch.testing.assert_allclose(score, result)
  27. @pytest.mark.parametrize("inc,res", increments2)
  28. def test_dicemetric_without_background(inc, res):
  29. fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
  30. fake_pred[:, 0, :, :] = 1
  31. fake_pred[:, 0, inc:n, inc:n] = 0
  32. fake_pred[:, 1, inc:n, inc:n] = 1
  33. dice_metric = DiceMetric(include_background=False, reduction="mean")
  34. score, _ = dice_metric(
  35. y_pred=fake_pred,
  36. y=sample,
  37. )
  38. result = torch.tensor([res])
  39. torch.testing.assert_allclose(score, result)
  40. def test_dicemetric_all_zeros():
  41. sample = torch.zeros((b, 2, n, n)) # BxCxHxW
  42. sample[:, 0, :, :] = 1
  43. sample[:, 1, :, :] = 0
  44. fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
  45. fake_pred[:, 0, :, :] = 1
  46. fake_pred[:, 0, 4:n, 4:n] = 0
  47. fake_pred[:, 1, 4:n, 4:n] = 1
  48. dice_metric = DiceMetric(include_background=True, reduction="mean")
  49. score, _ = dice_metric(
  50. y_pred=fake_pred,
  51. y=sample,
  52. )
  53. torch.testing.assert_allclose(score, torch.tensor([0.9795918464660645]))
  54. # def test_dicemetric_without_background(x):
  55. # assert x == 1
Tip!

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

Comments

Loading...