|
| 1 | +# Copyright 2020 MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +import unittest |
| 13 | + |
| 14 | +import torch |
| 15 | +from parameterized import parameterized |
| 16 | + |
| 17 | +from monai.handlers.mean_dice import MeanDice |
| 18 | + |
| 19 | +TEST_CASE_1 = [{'to_onehot_y': True, 'mutually_exclusive': True}, 0.75] |
| 20 | +TEST_CASE_2 = [{'include_background': False, 'to_onehot_y': False, 'mutually_exclusive': False}, 0.8333333] |
| 21 | + |
| 22 | +TEST_CASE_3 = [{'mutually_exclusive': True, 'add_sigmoid': True}] |
| 23 | + |
| 24 | + |
| 25 | +class TestHandlerMeanDice(unittest.TestCase): |
| 26 | + # TODO test multi node averaged dice |
| 27 | + |
| 28 | + @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) |
| 29 | + def test_compute(self, input_params, expected_avg): |
| 30 | + dice_metric = MeanDice(**input_params) |
| 31 | + |
| 32 | + y_pred = torch.Tensor([[0, 1], [1, 0]]) |
| 33 | + y = torch.ones((2, 1)) |
| 34 | + dice_metric.update([y_pred, y]) |
| 35 | + |
| 36 | + y_pred = torch.Tensor([[0, 1], [1, 0]]) |
| 37 | + y = torch.Tensor([[1.], [0.]]) |
| 38 | + dice_metric.update([y_pred, y]) |
| 39 | + |
| 40 | + avg_dice = dice_metric.compute() |
| 41 | + self.assertAlmostEqual(avg_dice, expected_avg) |
| 42 | + |
| 43 | + @parameterized.expand([TEST_CASE_3]) |
| 44 | + def test_misconfig(self, input_params): |
| 45 | + with self.assertRaisesRegex(ValueError, 'compatib'): |
| 46 | + dice_metric = MeanDice(**input_params) |
| 47 | + |
| 48 | + y_pred = torch.Tensor([[0, 1], [1, 0]]) |
| 49 | + y = torch.ones((2, 1)) |
| 50 | + dice_metric.update([y_pred, y]) |
| 51 | + |
| 52 | + @parameterized.expand([TEST_CASE_1, TEST_CASE_2]) |
| 53 | + def test_shape_mismatch(self, input_params, _expected): |
| 54 | + dice_metric = MeanDice(**input_params) |
| 55 | + with self.assertRaises((AssertionError, ValueError)): |
| 56 | + y_pred = torch.Tensor([[0, 1], [1, 0]]) |
| 57 | + y = torch.ones((2, 3)) |
| 58 | + dice_metric.update([y_pred, y]) |
| 59 | + |
| 60 | + with self.assertRaises((AssertionError, ValueError)): |
| 61 | + y_pred = torch.Tensor([[0, 1], [1, 0]]) |
| 62 | + y = torch.ones((3, 2)) |
| 63 | + dice_metric.update([y_pred, y]) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + unittest.main() |
0 commit comments