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
|
- import pytest
- from monai.losses import DiceCELoss
- from monai.metrics import DiceMetric
- import numpy as np
- import torch
- n = 5 # w/h size
- b = 1 # batch size
- sample = torch.zeros((b, 2, n, n)) # BxCxHxW
- sample[:, 0, :, :] = 1
- sample[:, 0, 2:n, 2:n] = 0
- sample[:, 1, 2:n, 2:n] = 1
- increments = [(2, 1.0), (3, 0.7401), (4, 0.5)]
- increments2 = [(2, 1.0), (3, 0.6154), (4, 0.2)]
- @pytest.mark.parametrize("inc,res", increments)
- def test_dicemetric_with_background(inc, res):
- fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
- fake_pred[:, 0, :, :] = 1
- fake_pred[:, 0, inc:n, inc:n] = 0
- fake_pred[:, 1, inc:n, inc:n] = 1
- dice_metric = DiceMetric(include_background=True, reduction="mean")
- score, _ = dice_metric(
- y_pred=fake_pred,
- y=sample,
- )
- result = torch.tensor([res])
- torch.testing.assert_allclose(score, result)
- @pytest.mark.parametrize("inc,res", increments2)
- def test_dicemetric_without_background(inc, res):
- fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
- fake_pred[:, 0, :, :] = 1
- fake_pred[:, 0, inc:n, inc:n] = 0
- fake_pred[:, 1, inc:n, inc:n] = 1
- dice_metric = DiceMetric(include_background=False, reduction="mean")
- score, _ = dice_metric(
- y_pred=fake_pred,
- y=sample,
- )
- result = torch.tensor([res])
- torch.testing.assert_allclose(score, result)
- def test_dicemetric_all_zeros():
- sample = torch.zeros((b, 2, n, n)) # BxCxHxW
- sample[:, 0, :, :] = 1
- sample[:, 1, :, :] = 0
- fake_pred = torch.zeros((b, 2, n, n)) # BxCxHxW
- fake_pred[:, 0, :, :] = 1
- fake_pred[:, 0, 4:n, 4:n] = 0
- fake_pred[:, 1, 4:n, 4:n] = 1
- dice_metric = DiceMetric(include_background=True, reduction="mean")
- score, _ = dice_metric(
- y_pred=fake_pred,
- y=sample,
- )
- torch.testing.assert_allclose(score, torch.tensor([0.9795918464660645]))
- # def test_dicemetric_without_background(x):
- # assert x == 1
|