From 3a48ead8e3de4d3a54e34641de72d158f97f6b8c Mon Sep 17 00:00:00 2001 From: Han Wang Date: Thu, 18 Apr 2024 14:15:00 +0100 Subject: [PATCH 1/5] Merge similar test components with parameterized Signed-off-by: Han Wang --- tests/test_affine_transform.py | 27 +-- tests/test_compute_f_beta.py | 46 ++-- tests/test_global_mutual_information_loss.py | 34 +-- tests/test_hausdorff_loss.py | 30 ++- tests/test_median_filter.py | 30 ++- tests/test_multi_scale.py | 24 ++- tests/test_optional_import.py | 27 +-- tests/test_perceptual_loss.py | 8 +- tests/test_prepare_batch_default.py | 82 ++----- tests/test_rand_affine.py | 7 +- tests/test_rand_affined.py | 9 +- tests/test_tversky_loss.py | 15 +- ...est_ultrasound_confidence_map_transform.py | 204 +++++++----------- tests/test_vit.py | 86 ++------ tests/test_vitautoenc.py | 94 ++------ 15 files changed, 251 insertions(+), 472 deletions(-) diff --git a/tests/test_affine_transform.py b/tests/test_affine_transform.py index 6ea036bce8..f8af583e87 100644 --- a/tests/test_affine_transform.py +++ b/tests/test_affine_transform.py @@ -133,28 +133,17 @@ def test_to_norm_affine_ill(self, affine, src_size, dst_size, align_corners): class TestAffineTransform(unittest.TestCase): - def test_affine_shift(self): - affine = torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]) + @parameterized.expand([ + ("shift", torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]), + ("shift_1", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]), + [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]]), + ("shift_2", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), + [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]]), + ]) + def test_affine_transforms(self, name, affine, expected): image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]]) out = AffineTransform(align_corners=False)(image, affine) out = out.detach().cpu().numpy() - expected = [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]] - np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol) - - def test_affine_shift_1(self): - affine = torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]) - image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]]) - out = AffineTransform(align_corners=False)(image, affine) - out = out.detach().cpu().numpy() - expected = [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]] - np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol) - - def test_affine_shift_2(self): - affine = torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]) - image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]]) - out = AffineTransform(align_corners=False)(image, affine) - out = out.detach().cpu().numpy() - expected = [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]] np.testing.assert_allclose(out, expected, atol=1e-5, rtol=_rtol) def test_zoom(self): diff --git a/tests/test_compute_f_beta.py b/tests/test_compute_f_beta.py index 85997577cf..421a52823f 100644 --- a/tests/test_compute_f_beta.py +++ b/tests/test_compute_f_beta.py @@ -15,6 +15,7 @@ import numpy as np import torch +from parameterized import parameterized from monai.metrics import FBetaScore from tests.utils import assert_allclose @@ -33,26 +34,31 @@ def test_expecting_success_and_device(self): assert_allclose(result, torch.Tensor([0.714286]), atol=1e-6, rtol=1e-6) np.testing.assert_equal(result.device, y_pred.device) - def test_expecting_success2(self): - metric = FBetaScore(beta=0.5) - metric( - y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]) - ) - assert_allclose(metric.aggregate()[0], torch.Tensor([0.609756]), atol=1e-6, rtol=1e-6) - - def test_expecting_success3(self): - metric = FBetaScore(beta=2) - metric( - y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]) - ) - assert_allclose(metric.aggregate()[0], torch.Tensor([0.862069]), atol=1e-6, rtol=1e-6) - - def test_denominator_is_zero(self): - metric = FBetaScore(beta=2) - metric( - y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=torch.Tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) - ) - assert_allclose(metric.aggregate()[0], torch.Tensor([0.0]), atol=1e-6, rtol=1e-6) + @parameterized.expand( + [ + ( + "success_beta_0_5", + FBetaScore(beta=0.5), + torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), + torch.Tensor([0.609756]), + ), + ( + "success_beta_2", + FBetaScore(beta=2), + torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), + torch.Tensor([0.862069]), + ), + ( + "denominator_zero", + FBetaScore(beta=2), + torch.Tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]), + torch.Tensor([0.0]), + ), + ] + ) + def test_success_and_zero(self, name, metric, y, expected_score): + metric(y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=y) + assert_allclose(metric.aggregate()[0], expected_score, atol=1e-6, rtol=1e-6) def test_number_of_dimensions_less_than_2_should_raise_error(self): metric = FBetaScore() diff --git a/tests/test_global_mutual_information_loss.py b/tests/test_global_mutual_information_loss.py index 36a1978c93..26b218ca14 100644 --- a/tests/test_global_mutual_information_loss.py +++ b/tests/test_global_mutual_information_loss.py @@ -15,6 +15,7 @@ import numpy as np import torch +from parameterized import parameterized from monai import transforms from monai.losses.image_dissimilarity import GlobalMutualInformationLoss @@ -116,24 +117,27 @@ def transformation(translate_params=(0.0, 0.0, 0.0), rotate_params=(0.0, 0.0, 0. class TestGlobalMutualInformationLossIll(unittest.TestCase): - def test_ill_shape(self): + @parameterized.expand([ + ("mismatched_simple_dims", torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), + ("mismatched_advanced_dims", torch.ones((1, 3, 3), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), + # You can add more test cases as needed + ]) + def test_ill_shape(self, name, input1, input2): loss = GlobalMutualInformationLoss() - with self.assertRaisesRegex(ValueError, ""): - loss.forward(torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float, device=device)) - with self.assertRaisesRegex(ValueError, ""): - loss.forward(torch.ones((1, 3, 3), dtype=torch.float), torch.ones((1, 3), dtype=torch.float, device=device)) - - def test_ill_opts(self): + with self.assertRaises(ValueError): + loss.forward(input1, input2) + + @parameterized.expand([ + ("num_bins_zero", 0, "mean", ValueError, ""), + ("num_bins_negative", -1, "mean", ValueError, ""), + ("reduction_unknown", 64, "unknown", ValueError, ""), + ("reduction_none", 64, None, ValueError, ""), + ]) + def test_ill_opts(self, name, num_bins, reduction, expected_exception, expected_message): pred = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) target = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) - with self.assertRaisesRegex(ValueError, ""): - GlobalMutualInformationLoss(num_bins=0)(pred, target) - with self.assertRaisesRegex(ValueError, ""): - GlobalMutualInformationLoss(num_bins=-1)(pred, target) - with self.assertRaisesRegex(ValueError, ""): - GlobalMutualInformationLoss(reduction="unknown")(pred, target) - with self.assertRaisesRegex(ValueError, ""): - GlobalMutualInformationLoss(reduction=None)(pred, target) + with self.assertRaisesRegex(expected_exception, expected_message): + GlobalMutualInformationLoss(num_bins=num_bins, reduction=reduction)(pred, target) if __name__ == "__main__": diff --git a/tests/test_hausdorff_loss.py b/tests/test_hausdorff_loss.py index f279d45b14..15f00a7440 100644 --- a/tests/test_hausdorff_loss.py +++ b/tests/test_hausdorff_loss.py @@ -219,17 +219,16 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): HausdorffDTLoss(reduction=None)(chn_input, chn_target) - def test_input_warnings(self): + @parameterized.expand([ + (False, False, False), + (False, True, False), + (False, False, True), + ]) + def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) with self.assertWarns(Warning): - loss = HausdorffDTLoss(include_background=False) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = HausdorffDTLoss(softmax=True) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = HausdorffDTLoss(to_onehot_y=True) + loss = HausdorffDTLoss(include_background=include_background, softmax=softmax, to_onehot_y=to_onehot_y) loss.forward(chn_input, chn_target) @@ -256,17 +255,16 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): LogHausdorffDTLoss(reduction=None)(chn_input, chn_target) - def test_input_warnings(self): + @parameterized.expand([ + (False, False, False), + (False, True, False), + (False, False, True), + ]) + def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) with self.assertWarns(Warning): - loss = LogHausdorffDTLoss(include_background=False) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = LogHausdorffDTLoss(softmax=True) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = LogHausdorffDTLoss(to_onehot_y=True) + loss = LogHausdorffDTLoss(include_background=include_background, softmax=softmax, to_onehot_y=to_onehot_y) loss.forward(chn_input, chn_target) diff --git a/tests/test_median_filter.py b/tests/test_median_filter.py index 1f5e623260..96ddb74056 100644 --- a/tests/test_median_filter.py +++ b/tests/test_median_filter.py @@ -15,27 +15,25 @@ import numpy as np import torch +from parameterized import parameterized from monai.networks.layers import MedianFilter class MedianFilterTestCase(unittest.TestCase): - - def test_3d_big(self): - a = torch.ones(1, 1, 2, 3, 5) - g = MedianFilter([1, 2, 4]).to(torch.device("cpu:0")) - - expected = a.numpy() - out = g(a).cpu().numpy() - np.testing.assert_allclose(out, expected, rtol=1e-5) - - def test_3d(self): - a = torch.ones(1, 1, 4, 3, 4) - g = MedianFilter(1).to(torch.device("cpu:0")) - - expected = a.numpy() - out = g(a).cpu().numpy() - np.testing.assert_allclose(out, expected, rtol=1e-5) + @parameterized.expand( + [ + ("3d_big", torch.ones(1, 1, 2, 3, 5), MedianFilter([1, 2, 4])), + ("3d", torch.ones(1, 1, 4, 3, 4), MedianFilter(1)), + ] + ) + def test_3d(self, name, input_tensor, filter): + filter = filter.to(torch.device("cpu:0")) + + expected = input_tensor.numpy() + output = filter(input_tensor).cpu().numpy() + + np.testing.assert_allclose(output, expected, rtol=1e-5) def test_3d_radii(self): a = torch.ones(1, 1, 4, 3, 2) diff --git a/tests/test_multi_scale.py b/tests/test_multi_scale.py index 6681f266a8..930bf9d5e1 100644 --- a/tests/test_multi_scale.py +++ b/tests/test_multi_scale.py @@ -58,17 +58,19 @@ def test_shape(self, input_param, input_data, expected_val): result = MultiScaleLoss(**input_param).forward(**input_data) np.testing.assert_allclose(result.detach().cpu().numpy(), expected_val, rtol=1e-5) - def test_ill_opts(self): - with self.assertRaisesRegex(ValueError, ""): - MultiScaleLoss(loss=dice_loss, kernel="none") - with self.assertRaisesRegex(ValueError, ""): - MultiScaleLoss(loss=dice_loss, scales=[-1])( - torch.ones((1, 1, 3), device=device), torch.ones((1, 1, 3), device=device) - ) - with self.assertRaisesRegex(ValueError, ""): - MultiScaleLoss(loss=dice_loss, scales=[-1], reduction="none")( - torch.ones((1, 1, 3), device=device), torch.ones((1, 1, 3), device=device) - ) + @parameterized.expand([ + ("kernel_none", {"loss": dice_loss, "kernel": "none"}, None, None), + ("scales_negative", {"loss": dice_loss, "scales": [-1]}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), + ("scales_negative_reduction_none", {"loss": dice_loss, "scales": [-1], "reduction": "none"}, + torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), + ]) + def test_ill_opts(self, name, kwargs, input, target): + if input is None and target is None: + with self.assertRaisesRegex(ValueError, ""): + MultiScaleLoss(**kwargs) + else: + with self.assertRaisesRegex(ValueError, ""): + MultiScaleLoss(**kwargs)(input, target) def test_script(self): input_param, input_data, expected_val = TEST_CASES[0] diff --git a/tests/test_optional_import.py b/tests/test_optional_import.py index e7e1c03fd0..2f640f88d0 100644 --- a/tests/test_optional_import.py +++ b/tests/test_optional_import.py @@ -13,22 +13,20 @@ import unittest +from parameterized import parameterized + from monai.utils import OptionalImportError, exact_version, optional_import class TestOptionalImport(unittest.TestCase): - def test_default(self): - my_module, flag = optional_import("not_a_module") + @parameterized.expand(["not_a_module", "torch.randint"]) + def test_default(self, import_module): + my_module, flag = optional_import(import_module) self.assertFalse(flag) with self.assertRaises(OptionalImportError): my_module.test - my_module, flag = optional_import("torch.randint") - with self.assertRaises(OptionalImportError): - self.assertFalse(flag) - print(my_module.test) - def test_import_valid(self): my_module, flag = optional_import("torch") self.assertTrue(flag) @@ -47,18 +45,9 @@ def test_import_wrong_number(self): self.assertTrue(flag) print(my_module.randint(1, 2, (1, 2))) - def test_import_good_number(self): - my_module, flag = optional_import("torch", "0") - my_module.nn - self.assertTrue(flag) - print(my_module.randint(1, 2, (1, 2))) - - my_module, flag = optional_import("torch", "0.0.0.1") - my_module.nn - self.assertTrue(flag) - print(my_module.randint(1, 2, (1, 2))) - - my_module, flag = optional_import("torch", "1.1.0") + @parameterized.expand(["0", "0.0.0.1", "1.1.0"]) + def test_import_good_number(self, version_number): + my_module, flag = optional_import("torch", version_number) my_module.nn self.assertTrue(flag) print(my_module.randint(1, 2, (1, 2))) diff --git a/tests/test_perceptual_loss.py b/tests/test_perceptual_loss.py index 02232e6f8d..37cfbdae10 100644 --- a/tests/test_perceptual_loss.py +++ b/tests/test_perceptual_loss.py @@ -85,12 +85,10 @@ def test_1d(self): with self.assertRaises(NotImplementedError): PerceptualLoss(spatial_dims=1) - def test_medicalnet_on_2d_data(self): + @parameterized.expand(["medicalnet_resnet10_23datasets", "medicalnet_resnet50_23datasets"]) + def test_medicalnet_on_2d_data(self, network_type): with self.assertRaises(ValueError): - PerceptualLoss(spatial_dims=2, network_type="medicalnet_resnet10_23datasets") - - with self.assertRaises(ValueError): - PerceptualLoss(spatial_dims=2, network_type="medicalnet_resnet50_23datasets") + PerceptualLoss(spatial_dims=2, network_type=network_type) if __name__ == "__main__": diff --git a/tests/test_prepare_batch_default.py b/tests/test_prepare_batch_default.py index d5a5fbf57e..aa68960679 100644 --- a/tests/test_prepare_batch_default.py +++ b/tests/test_prepare_batch_default.py @@ -14,6 +14,7 @@ import unittest import torch +from parameterized import parameterized from monai.engines import PrepareBatchDefault, SupervisedEvaluator from tests.utils import assert_allclose @@ -27,9 +28,8 @@ def forward(self, x: torch.Tensor): class TestPrepareBatchDefault(unittest.TestCase): - def test_dict_content(self): - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - dataloader = [ + @parameterized.expand([ + ("dict_content", [ { "image": torch.tensor([1, 2]), "label": torch.tensor([3, 4]), @@ -37,75 +37,33 @@ def test_dict_content(self): "extra2": 16, "extra3": "test", } - ] - # set up engine - evaluator = SupervisedEvaluator( - device=device, - val_data_loader=dataloader, - epoch_length=1, - network=TestNet(), - non_blocking=False, - prepare_batch=PrepareBatchDefault(), - decollate=False, - mode="eval", - ) - evaluator.run() - output = evaluator.state.output - assert_allclose(output["image"], torch.tensor([1, 2], device=device)) - assert_allclose(output["label"], torch.tensor([3, 4], device=device)) - - def test_tensor_content(self): + ], TestNet(), True), + ("tensor_content", [torch.tensor([1, 2])], torch.nn.Identity(), True), + ("pair_content", [(torch.tensor([1, 2]), torch.tensor([3, 4]))], torch.nn.Identity(), True), + ("empty_data", [], TestNet(), False), + ]) + def test_prepare_batch(self, name, dataloader, network, should_run): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - dataloader = [torch.tensor([1, 2])] - - # set up engine evaluator = SupervisedEvaluator( device=device, val_data_loader=dataloader, - epoch_length=1, - network=torch.nn.Identity(), + epoch_length=len(dataloader) if should_run else 0, + network=network, non_blocking=False, prepare_batch=PrepareBatchDefault(), decollate=False, - mode="eval", + mode="eval" if should_run else "train", ) evaluator.run() - output = evaluator.state.output - assert_allclose(output["image"], torch.tensor([1, 2], device=device)) - self.assertTrue(output["label"] is None) - def test_pair_content(self): - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - dataloader = [(torch.tensor([1, 2]), torch.tensor([3, 4]))] - - # set up engine - evaluator = SupervisedEvaluator( - device=device, - val_data_loader=dataloader, - epoch_length=1, - network=torch.nn.Identity(), - non_blocking=False, - prepare_batch=PrepareBatchDefault(), - decollate=False, - mode="eval", - ) - evaluator.run() - output = evaluator.state.output - assert_allclose(output["image"], torch.tensor([1, 2], device=device)) - assert_allclose(output["label"], torch.tensor([3, 4], device=device)) - - def test_empty_data(self): - dataloader = [] - evaluator = SupervisedEvaluator( - val_data_loader=dataloader, - device=torch.device("cpu"), - epoch_length=0, - network=TestNet(), - non_blocking=False, - prepare_batch=PrepareBatchDefault(), - decollate=False, - ) - evaluator.run() + if should_run: + output = evaluator.state.output + if name == "dict_content" or name == "pair_content": + assert_allclose(output["image"], torch.tensor([1, 2], device=device)) + assert_allclose(output["label"], torch.tensor([3, 4], device=device)) + elif name == "tensor_content": + assert_allclose(output["image"], torch.tensor([1, 2], device=device)) + self.assertTrue(output["label"] is None) if __name__ == "__main__": diff --git a/tests/test_rand_affine.py b/tests/test_rand_affine.py index 23e3fd148c..2c827b7426 100644 --- a/tests/test_rand_affine.py +++ b/tests/test_rand_affine.py @@ -152,11 +152,10 @@ def test_rand_affine(self, input_param, input_data, expected_val): self.assertTrue(g._cached_grid is not None) assert_allclose(result, expected_val, rtol=_rtol, atol=1e-4, type_test="tensor") - def test_ill_cache(self): + @parameterized.expand([(None,), ((1, 1, -1),)]) + def test_ill_cache(self, spatial_size): with self.assertWarns(UserWarning): - RandAffine(cache_grid=True) - with self.assertWarns(UserWarning): - RandAffine(cache_grid=True, spatial_size=(1, 1, -1)) + RandAffine(cache_grid=True, spatial_size=spatial_size) @parameterized.expand(TEST_CASES_SKIPPED_CONSISTENCY) def test_skipped_transform_consistency(self, im, in_dtype): diff --git a/tests/test_rand_affined.py b/tests/test_rand_affined.py index 32fde8dc0f..950058a9e9 100644 --- a/tests/test_rand_affined.py +++ b/tests/test_rand_affined.py @@ -272,13 +272,10 @@ def test_rand_affined(self, input_param, input_data, expected_val, track_meta): self.assertEqual(len(v.applied_operations), 0) self.assertTupleEqual(v.shape, input_data[k].shape) - def test_ill_cache(self): + @parameterized.expand([(None,), ((2, -1),)]) # spatial size is None # spatial size is dynamic + def test_ill_cache(self, spatial_size): with self.assertWarns(UserWarning): - # spatial size is None - RandAffined(device=device, spatial_size=None, prob=1.0, cache_grid=True, keys=("img", "seg")) - with self.assertWarns(UserWarning): - # spatial size is dynamic - RandAffined(device=device, spatial_size=(2, -1), prob=1.0, cache_grid=True, keys=("img", "seg")) + RandAffined(device=device, spatial_size=spatial_size, prob=1.0, cache_grid=True, keys=("img", "seg")) if __name__ == "__main__": diff --git a/tests/test_tversky_loss.py b/tests/test_tversky_loss.py index efe1f2cdf3..1c1310c316 100644 --- a/tests/test_tversky_loss.py +++ b/tests/test_tversky_loss.py @@ -165,17 +165,16 @@ def test_ill_shape(self): with self.assertRaisesRegex(ValueError, ""): TverskyLoss(reduction=None)(chn_input, chn_target) - def test_input_warnings(self): + @parameterized.expand([ + (False, False, False), + (False, True, False), + (False, False, True), + ]) + def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 3)) chn_target = torch.ones((1, 1, 3)) with self.assertWarns(Warning): - loss = TverskyLoss(include_background=False) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = TverskyLoss(softmax=True) - loss.forward(chn_input, chn_target) - with self.assertWarns(Warning): - loss = TverskyLoss(to_onehot_y=True) + loss = TverskyLoss(include_background=include_background, softmax=softmax, to_onehot_y=to_onehot_y) loss.forward(chn_input, chn_target) def test_script(self): diff --git a/tests/test_ultrasound_confidence_map_transform.py b/tests/test_ultrasound_confidence_map_transform.py index f672961700..0528640e84 100644 --- a/tests/test_ultrasound_confidence_map_transform.py +++ b/tests/test_ultrasound_confidence_map_transform.py @@ -15,6 +15,7 @@ import numpy as np import torch +from parameterized import parameterized from monai.transforms import UltrasoundConfidenceMapTransform from tests.utils import assert_allclose @@ -535,162 +536,107 @@ def test_parameters(self): with self.assertRaises(ValueError): UltrasoundConfidenceMapTransform(sink_mode="unknown") - def test_rgb(self): + @parameterized.expand([ + ("all", SINK_ALL_OUTPUT), + ("mid", SINK_MID_OUTPUT), + ("min", SINK_MIN_OUTPUT), + ("mask", SINK_MASK_OUTPUT, True), + ]) + def test_ultrasound_confidence_map_transform(self, sink_mode, expected_output, use_mask=False): # RGB image input_img_rgb = np.expand_dims(np.repeat(self.input_img_np, 3, axis=0), axis=0) input_img_rgb_torch = torch.from_numpy(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="all") - result_torch = transform(input_img_rgb_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_ALL_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_ALL_OUTPUT, rtol=1e-4, atol=1e-4) + transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) - transform = UltrasoundConfidenceMapTransform(sink_mode="mid") - result_torch = transform(input_img_rgb_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MID_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MID_OUTPUT, rtol=1e-4, atol=1e-4) + if use_mask: + result_torch = transform(input_img_rgb_torch, self.input_mask_torch) + result_np = transform(input_img_rgb, self.input_mask_np) + else: + result_torch = transform(input_img_rgb_torch) + result_np = transform(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="min") - result_torch = transform(input_img_rgb_torch) self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MIN_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) + assert_allclose(result_torch, torch.tensor(expected_output), rtol=1e-4, atol=1e-4) self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MIN_OUTPUT, rtol=1e-4, atol=1e-4) - - transform = UltrasoundConfidenceMapTransform(sink_mode="mask") - result_torch = transform(input_img_rgb_torch, self.input_mask_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MASK_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb, self.input_mask_np) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MASK_OUTPUT, rtol=1e-4, atol=1e-4) - - def test_multi_channel_2d(self): - # 2D multi-channel image + assert_allclose(result_np, expected_output, rtol=1e-4, atol=1e-4) + + @parameterized.expand([ + ("all", SINK_ALL_OUTPUT), + ("mid", SINK_MID_OUTPUT), + ("min", SINK_MIN_OUTPUT), + ("mask", SINK_MASK_OUTPUT, True), # Adding a flag for mask cases + ]) + def test_multi_channel_2d(self, sink_mode, expected_output, use_mask=False): input_img_rgb = np.expand_dims(np.repeat(self.input_img_np, 17, axis=0), axis=0) input_img_rgb_torch = torch.from_numpy(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="all") - result_torch = transform(input_img_rgb_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_ALL_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_ALL_OUTPUT, rtol=1e-4, atol=1e-4) - - transform = UltrasoundConfidenceMapTransform(sink_mode="mid") - result_torch = transform(input_img_rgb_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MID_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MID_OUTPUT, rtol=1e-4, atol=1e-4) + transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) - transform = UltrasoundConfidenceMapTransform(sink_mode="min") - result_torch = transform(input_img_rgb_torch) - self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MIN_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb) - self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MIN_OUTPUT, rtol=1e-4, atol=1e-4) + if use_mask: + result_torch = transform(input_img_rgb_torch, self.input_mask_torch) + result_np = transform(input_img_rgb, self.input_mask_np) + else: + result_torch = transform(input_img_rgb_torch) + result_np = transform(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="mask") - result_torch = transform(input_img_rgb_torch, self.input_mask_torch) self.assertIsInstance(result_torch, torch.Tensor) - assert_allclose(result_torch, torch.tensor(SINK_MASK_OUTPUT), rtol=1e-4, atol=1e-4) - result_np = transform(input_img_rgb, self.input_mask_np) + assert_allclose(result_torch, torch.tensor(expected_output), rtol=1e-4, atol=1e-4) self.assertIsInstance(result_np, np.ndarray) - assert_allclose(result_np, SINK_MASK_OUTPUT, rtol=1e-4, atol=1e-4) - - def test_non_one_first_dim(self): - # Image without first dimension as 1 + assert_allclose(result_np, expected_output, rtol=1e-4, atol=1e-4) + + @parameterized.expand([ + ("all",), + ("mid",), + ("min",), + ("mask",), + ]) + def test_non_one_first_dim(self, sink_mode): + transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) input_img_rgb = np.repeat(self.input_img_np, 3, axis=0) input_img_rgb_torch = torch.from_numpy(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="all") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb) - - transform = UltrasoundConfidenceMapTransform(sink_mode="mid") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb) - - transform = UltrasoundConfidenceMapTransform(sink_mode="min") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb) - - transform = UltrasoundConfidenceMapTransform(sink_mode="mask") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch, self.input_mask_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb, self.input_mask_np) - - def test_no_first_dim(self): - # Image without first dimension + if sink_mode == "mask": + with self.assertRaises(ValueError): + transform(input_img_rgb_torch, self.input_mask_torch) + with self.assertRaises(ValueError): + transform(input_img_rgb, self.input_mask_np) + else: + with self.assertRaises(ValueError): + transform(input_img_rgb_torch) + with self.assertRaises(ValueError): + transform(input_img_rgb) + + @parameterized.expand([ + ("all",), + ("mid",), + ("min",), + ("mask",) + ]) + def test_no_first_dim(self, sink_mode): input_img_rgb = self.input_img_np[0] input_img_rgb_torch = torch.from_numpy(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="all") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb) + transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) - transform = UltrasoundConfidenceMapTransform(sink_mode="mid") with self.assertRaises(ValueError): transform(input_img_rgb_torch) with self.assertRaises(ValueError): transform(input_img_rgb) - transform = UltrasoundConfidenceMapTransform(sink_mode="min") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb) - - transform = UltrasoundConfidenceMapTransform(sink_mode="mask") - with self.assertRaises(ValueError): - transform(input_img_rgb_torch, self.input_mask_torch) - with self.assertRaises(ValueError): - transform(input_img_rgb, self.input_mask_np) - - def test_sink_all(self): - transform = UltrasoundConfidenceMapTransform(sink_mode="all") - - # This should not raise an exception for torch tensor - result_torch = transform(self.input_img_torch) - self.assertIsInstance(result_torch, torch.Tensor) - - # This should not raise an exception for numpy array - result_np = transform(self.input_img_np) - self.assertIsInstance(result_np, np.ndarray) - - def test_sink_mid(self): - transform = UltrasoundConfidenceMapTransform(sink_mode="mid") - - # This should not raise an exception for torch tensor - result_torch = transform(self.input_img_torch) - self.assertIsInstance(result_torch, torch.Tensor) - - # This should not raise an exception for numpy array - result_np = transform(self.input_img_np) - self.assertIsInstance(result_np, np.ndarray) - - def test_sink_min(self): - transform = UltrasoundConfidenceMapTransform(sink_mode="min") + if sink_mode == "mask": + with self.assertRaises(ValueError): + transform(input_img_rgb_torch, self.input_mask_torch) + with self.assertRaises(ValueError): + transform(input_img_rgb, self.input_mask_np) + + @parameterized.expand([ + ("all",), + ("mid",), + ("min",), + ]) + def test_sink_mode(self, mode): + transform = UltrasoundConfidenceMapTransform(sink_mode=mode) # This should not raise an exception for torch tensor result_torch = transform(self.input_img_torch) diff --git a/tests/test_vit.py b/tests/test_vit.py index a84883cba0..f30e04a2fc 100644 --- a/tests/test_vit.py +++ b/tests/test_vit.py @@ -69,75 +69,27 @@ def test_shape(self, input_param, input_shape, expected_shape): result, _ = net(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) - def test_ill_arg(self): + @parameterized.expand([ + (1, (128, 128, 128), (16, 16, 16), 128, 3072, 12, 12, "conv", False, 5.0), + (1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", False, 0.3), + (1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", False, 0.3), + (1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", True, 0.3), + (4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", False, 0.3), + ]) + def test_ill_arg(self, in_channels, img_size, patch_size, hidden_size, mlp_dim, num_layers, num_heads, pos_embed, + classification, dropout_rate): with self.assertRaises(ValueError): ViT( - in_channels=1, - img_size=(128, 128, 128), - patch_size=(16, 16, 16), - hidden_size=128, - mlp_dim=3072, - num_layers=12, - num_heads=12, - pos_embed="conv", - classification=False, - dropout_rate=5.0, - ) - - with self.assertRaises(ValueError): - ViT( - in_channels=1, - img_size=(32, 32, 32), - patch_size=(64, 64, 64), - hidden_size=512, - mlp_dim=3072, - num_layers=12, - num_heads=8, - pos_embed="perceptron", - classification=False, - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViT( - in_channels=1, - img_size=(96, 96, 96), - patch_size=(8, 8, 8), - hidden_size=512, - mlp_dim=3072, - num_layers=12, - num_heads=14, - pos_embed="conv", - classification=False, - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViT( - in_channels=1, - img_size=(97, 97, 97), - patch_size=(4, 4, 4), - hidden_size=768, - mlp_dim=3072, - num_layers=12, - num_heads=8, - pos_embed="perceptron", - classification=True, - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViT( - in_channels=4, - img_size=(96, 96, 96), - patch_size=(16, 16, 16), - hidden_size=768, - mlp_dim=3072, - num_layers=12, - num_heads=12, - pos_embed="perc", - classification=False, - dropout_rate=0.3, + in_channels=in_channels, + img_size=img_size, + patch_size=patch_size, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + num_layers=num_layers, + num_heads=num_heads, + pos_embed=pos_embed, + classification=classification, + dropout_rate=dropout_rate, ) @parameterized.expand(TEST_CASE_Vit) diff --git a/tests/test_vitautoenc.py b/tests/test_vitautoenc.py index cc3d493bb3..a54cba524a 100644 --- a/tests/test_vitautoenc.py +++ b/tests/test_vitautoenc.py @@ -82,83 +82,27 @@ def test_shape(self, input_param, input_shape, expected_shape): result, _ = net(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) - def test_ill_arg(self): + @parameterized.expand([ + ("img_size_too_large_for_patch_size", 1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", 0.3), + ("num_heads_out_of_bound", 1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", 0.3), + ("img_size_not_divisible_by_patch_size", 1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", 0.3), + ("invalid_pos_embed", 4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", 0.3), + ("patch_size_not_divisible", 4, (96, 96, 96), (9, 9, 9), 768, 3072, 12, 12, "perc", 0.3), + # Add more test cases as needed + ]) + def test_ill_arg(self, name, in_channels, img_size, patch_size, hidden_size, mlp_dim, num_layers, num_heads, + pos_embed, dropout_rate): with self.assertRaises(ValueError): ViTAutoEnc( - in_channels=1, - img_size=(128, 128, 128), - patch_size=(16, 16, 16), - hidden_size=128, - mlp_dim=3072, - num_layers=12, - num_heads=12, - pos_embed="conv", - dropout_rate=5.0, - ) - - with self.assertRaises(ValueError): - ViTAutoEnc( - in_channels=1, - img_size=(32, 32, 32), - patch_size=(64, 64, 64), - hidden_size=512, - mlp_dim=3072, - num_layers=12, - num_heads=8, - pos_embed="perceptron", - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViTAutoEnc( - in_channels=1, - img_size=(96, 96, 96), - patch_size=(8, 8, 8), - hidden_size=512, - mlp_dim=3072, - num_layers=12, - num_heads=14, - pos_embed="conv", - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViTAutoEnc( - in_channels=1, - img_size=(97, 97, 97), - patch_size=(4, 4, 4), - hidden_size=768, - mlp_dim=3072, - num_layers=12, - num_heads=8, - pos_embed="perceptron", - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViTAutoEnc( - in_channels=4, - img_size=(96, 96, 96), - patch_size=(16, 16, 16), - hidden_size=768, - mlp_dim=3072, - num_layers=12, - num_heads=12, - pos_embed="perc", - dropout_rate=0.3, - ) - - with self.assertRaises(ValueError): - ViTAutoEnc( - in_channels=4, - img_size=(96, 96, 96), - patch_size=(9, 9, 9), - hidden_size=768, - mlp_dim=3072, - num_layers=12, - num_heads=12, - pos_embed="perc", - dropout_rate=0.3, + in_channels=in_channels, + img_size=img_size, + patch_size=patch_size, + hidden_size=hidden_size, + mlp_dim=mlp_dim, + num_layers=num_layers, + num_heads=num_heads, + pos_embed=pos_embed, + dropout_rate=dropout_rate, ) From 00b1465e5dca2b8b98620f19d66decdb38f1c634 Mon Sep 17 00:00:00 2001 From: Han Wang Date: Thu, 18 Apr 2024 16:41:45 +0100 Subject: [PATCH 2/5] reformatted from black Signed-off-by: Han Wang --- tests/test_affine_transform.py | 26 +++++--- tests/test_global_mutual_information_loss.py | 30 +++++---- tests/test_hausdorff_loss.py | 24 +++++--- tests/test_multi_scale.py | 18 ++++-- tests/test_prepare_batch_default.py | 35 ++++++----- tests/test_tversky_loss.py | 12 ++-- ...est_ultrasound_confidence_map_transform.py | 61 ++++++++++--------- tests/test_vit.py | 31 +++++++--- tests/test_vitautoenc.py | 33 +++++++--- 9 files changed, 169 insertions(+), 101 deletions(-) diff --git a/tests/test_affine_transform.py b/tests/test_affine_transform.py index f8af583e87..30c11f90a9 100644 --- a/tests/test_affine_transform.py +++ b/tests/test_affine_transform.py @@ -133,13 +133,25 @@ def test_to_norm_affine_ill(self, affine, src_size, dst_size, align_corners): class TestAffineTransform(unittest.TestCase): - @parameterized.expand([ - ("shift", torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]), - ("shift_1", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]), - [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]]), - ("shift_2", torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), - [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]]), - ]) + @parameterized.expand( + [ + ( + "shift", + torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), + [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]], + ), + ( + "shift_1", + torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]), + [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]], + ), + ( + "shift_2", + torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), + [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]], + ), + ] + ) def test_affine_transforms(self, name, affine, expected): image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]]) out = AffineTransform(align_corners=False)(image, affine) diff --git a/tests/test_global_mutual_information_loss.py b/tests/test_global_mutual_information_loss.py index 26b218ca14..0cfbd727dd 100644 --- a/tests/test_global_mutual_information_loss.py +++ b/tests/test_global_mutual_information_loss.py @@ -117,22 +117,30 @@ def transformation(translate_params=(0.0, 0.0, 0.0), rotate_params=(0.0, 0.0, 0. class TestGlobalMutualInformationLossIll(unittest.TestCase): - @parameterized.expand([ - ("mismatched_simple_dims", torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), - ("mismatched_advanced_dims", torch.ones((1, 3, 3), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), - # You can add more test cases as needed - ]) + @parameterized.expand( + [ + ("mismatched_simple_dims", torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), + ( + "mismatched_advanced_dims", + torch.ones((1, 3, 3), dtype=torch.float), + torch.ones((1, 3), dtype=torch.float), + ), + # You can add more test cases as needed + ] + ) def test_ill_shape(self, name, input1, input2): loss = GlobalMutualInformationLoss() with self.assertRaises(ValueError): loss.forward(input1, input2) - @parameterized.expand([ - ("num_bins_zero", 0, "mean", ValueError, ""), - ("num_bins_negative", -1, "mean", ValueError, ""), - ("reduction_unknown", 64, "unknown", ValueError, ""), - ("reduction_none", 64, None, ValueError, ""), - ]) + @parameterized.expand( + [ + ("num_bins_zero", 0, "mean", ValueError, ""), + ("num_bins_negative", -1, "mean", ValueError, ""), + ("reduction_unknown", 64, "unknown", ValueError, ""), + ("reduction_none", 64, None, ValueError, ""), + ] + ) def test_ill_opts(self, name, num_bins, reduction, expected_exception, expected_message): pred = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) target = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) diff --git a/tests/test_hausdorff_loss.py b/tests/test_hausdorff_loss.py index 15f00a7440..00d1364183 100644 --- a/tests/test_hausdorff_loss.py +++ b/tests/test_hausdorff_loss.py @@ -219,11 +219,13 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): HausdorffDTLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand([ - (False, False, False), - (False, True, False), - (False, False, True), - ]) + @parameterized.expand( + [ + (False, False, False), + (False, True, False), + (False, False, True), + ] + ) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) @@ -255,11 +257,13 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): LogHausdorffDTLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand([ - (False, False, False), - (False, True, False), - (False, False, True), - ]) + @parameterized.expand( + [ + (False, False, False), + (False, True, False), + (False, False, True), + ] + ) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) diff --git a/tests/test_multi_scale.py b/tests/test_multi_scale.py index 930bf9d5e1..9ce04c9b47 100644 --- a/tests/test_multi_scale.py +++ b/tests/test_multi_scale.py @@ -58,12 +58,18 @@ def test_shape(self, input_param, input_data, expected_val): result = MultiScaleLoss(**input_param).forward(**input_data) np.testing.assert_allclose(result.detach().cpu().numpy(), expected_val, rtol=1e-5) - @parameterized.expand([ - ("kernel_none", {"loss": dice_loss, "kernel": "none"}, None, None), - ("scales_negative", {"loss": dice_loss, "scales": [-1]}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), - ("scales_negative_reduction_none", {"loss": dice_loss, "scales": [-1], "reduction": "none"}, - torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), - ]) + @parameterized.expand( + [ + ("kernel_none", {"loss": dice_loss, "kernel": "none"}, None, None), + ("scales_negative", {"loss": dice_loss, "scales": [-1]}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), + ( + "scales_negative_reduction_none", + {"loss": dice_loss, "scales": [-1], "reduction": "none"}, + torch.ones((1, 1, 3)), + torch.ones((1, 1, 3)), + ), + ] + ) def test_ill_opts(self, name, kwargs, input, target): if input is None and target is None: with self.assertRaisesRegex(ValueError, ""): diff --git a/tests/test_prepare_batch_default.py b/tests/test_prepare_batch_default.py index aa68960679..fae72ac742 100644 --- a/tests/test_prepare_batch_default.py +++ b/tests/test_prepare_batch_default.py @@ -28,20 +28,27 @@ def forward(self, x: torch.Tensor): class TestPrepareBatchDefault(unittest.TestCase): - @parameterized.expand([ - ("dict_content", [ - { - "image": torch.tensor([1, 2]), - "label": torch.tensor([3, 4]), - "extra1": torch.tensor([5, 6]), - "extra2": 16, - "extra3": "test", - } - ], TestNet(), True), - ("tensor_content", [torch.tensor([1, 2])], torch.nn.Identity(), True), - ("pair_content", [(torch.tensor([1, 2]), torch.tensor([3, 4]))], torch.nn.Identity(), True), - ("empty_data", [], TestNet(), False), - ]) + @parameterized.expand( + [ + ( + "dict_content", + [ + { + "image": torch.tensor([1, 2]), + "label": torch.tensor([3, 4]), + "extra1": torch.tensor([5, 6]), + "extra2": 16, + "extra3": "test", + } + ], + TestNet(), + True, + ), + ("tensor_content", [torch.tensor([1, 2])], torch.nn.Identity(), True), + ("pair_content", [(torch.tensor([1, 2]), torch.tensor([3, 4]))], torch.nn.Identity(), True), + ("empty_data", [], TestNet(), False), + ] + ) def test_prepare_batch(self, name, dataloader, network, should_run): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") evaluator = SupervisedEvaluator( diff --git a/tests/test_tversky_loss.py b/tests/test_tversky_loss.py index 1c1310c316..24518ebd00 100644 --- a/tests/test_tversky_loss.py +++ b/tests/test_tversky_loss.py @@ -165,11 +165,13 @@ def test_ill_shape(self): with self.assertRaisesRegex(ValueError, ""): TverskyLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand([ - (False, False, False), - (False, True, False), - (False, False, True), - ]) + @parameterized.expand( + [ + (False, False, False), + (False, True, False), + (False, False, True), + ] + ) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 3)) chn_target = torch.ones((1, 1, 3)) diff --git a/tests/test_ultrasound_confidence_map_transform.py b/tests/test_ultrasound_confidence_map_transform.py index 0528640e84..71abac74f9 100644 --- a/tests/test_ultrasound_confidence_map_transform.py +++ b/tests/test_ultrasound_confidence_map_transform.py @@ -536,12 +536,14 @@ def test_parameters(self): with self.assertRaises(ValueError): UltrasoundConfidenceMapTransform(sink_mode="unknown") - @parameterized.expand([ - ("all", SINK_ALL_OUTPUT), - ("mid", SINK_MID_OUTPUT), - ("min", SINK_MIN_OUTPUT), - ("mask", SINK_MASK_OUTPUT, True), - ]) + @parameterized.expand( + [ + ("all", SINK_ALL_OUTPUT), + ("mid", SINK_MID_OUTPUT), + ("min", SINK_MIN_OUTPUT), + ("mask", SINK_MASK_OUTPUT, True), + ] + ) def test_ultrasound_confidence_map_transform(self, sink_mode, expected_output, use_mask=False): # RGB image input_img_rgb = np.expand_dims(np.repeat(self.input_img_np, 3, axis=0), axis=0) @@ -561,12 +563,14 @@ def test_ultrasound_confidence_map_transform(self, sink_mode, expected_output, u self.assertIsInstance(result_np, np.ndarray) assert_allclose(result_np, expected_output, rtol=1e-4, atol=1e-4) - @parameterized.expand([ - ("all", SINK_ALL_OUTPUT), - ("mid", SINK_MID_OUTPUT), - ("min", SINK_MIN_OUTPUT), - ("mask", SINK_MASK_OUTPUT, True), # Adding a flag for mask cases - ]) + @parameterized.expand( + [ + ("all", SINK_ALL_OUTPUT), + ("mid", SINK_MID_OUTPUT), + ("min", SINK_MIN_OUTPUT), + ("mask", SINK_MASK_OUTPUT, True), # Adding a flag for mask cases + ] + ) def test_multi_channel_2d(self, sink_mode, expected_output, use_mask=False): input_img_rgb = np.expand_dims(np.repeat(self.input_img_np, 17, axis=0), axis=0) input_img_rgb_torch = torch.from_numpy(input_img_rgb) @@ -585,12 +589,14 @@ def test_multi_channel_2d(self, sink_mode, expected_output, use_mask=False): self.assertIsInstance(result_np, np.ndarray) assert_allclose(result_np, expected_output, rtol=1e-4, atol=1e-4) - @parameterized.expand([ - ("all",), - ("mid",), - ("min",), - ("mask",), - ]) + @parameterized.expand( + [ + ("all",), + ("mid",), + ("min",), + ("mask",), + ] + ) def test_non_one_first_dim(self, sink_mode): transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) input_img_rgb = np.repeat(self.input_img_np, 3, axis=0) @@ -607,12 +613,7 @@ def test_non_one_first_dim(self, sink_mode): with self.assertRaises(ValueError): transform(input_img_rgb) - @parameterized.expand([ - ("all",), - ("mid",), - ("min",), - ("mask",) - ]) + @parameterized.expand([("all",), ("mid",), ("min",), ("mask",)]) def test_no_first_dim(self, sink_mode): input_img_rgb = self.input_img_np[0] input_img_rgb_torch = torch.from_numpy(input_img_rgb) @@ -630,11 +631,13 @@ def test_no_first_dim(self, sink_mode): with self.assertRaises(ValueError): transform(input_img_rgb, self.input_mask_np) - @parameterized.expand([ - ("all",), - ("mid",), - ("min",), - ]) + @parameterized.expand( + [ + ("all",), + ("mid",), + ("min",), + ] + ) def test_sink_mode(self, mode): transform = UltrasoundConfidenceMapTransform(sink_mode=mode) diff --git a/tests/test_vit.py b/tests/test_vit.py index f30e04a2fc..d27c10f95e 100644 --- a/tests/test_vit.py +++ b/tests/test_vit.py @@ -69,15 +69,28 @@ def test_shape(self, input_param, input_shape, expected_shape): result, _ = net(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) - @parameterized.expand([ - (1, (128, 128, 128), (16, 16, 16), 128, 3072, 12, 12, "conv", False, 5.0), - (1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", False, 0.3), - (1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", False, 0.3), - (1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", True, 0.3), - (4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", False, 0.3), - ]) - def test_ill_arg(self, in_channels, img_size, patch_size, hidden_size, mlp_dim, num_layers, num_heads, pos_embed, - classification, dropout_rate): + @parameterized.expand( + [ + (1, (128, 128, 128), (16, 16, 16), 128, 3072, 12, 12, "conv", False, 5.0), + (1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", False, 0.3), + (1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", False, 0.3), + (1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", True, 0.3), + (4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", False, 0.3), + ] + ) + def test_ill_arg( + self, + in_channels, + img_size, + patch_size, + hidden_size, + mlp_dim, + num_layers, + num_heads, + pos_embed, + classification, + dropout_rate, + ): with self.assertRaises(ValueError): ViT( in_channels=in_channels, diff --git a/tests/test_vitautoenc.py b/tests/test_vitautoenc.py index a54cba524a..02a6787672 100644 --- a/tests/test_vitautoenc.py +++ b/tests/test_vitautoenc.py @@ -82,16 +82,29 @@ def test_shape(self, input_param, input_shape, expected_shape): result, _ = net(torch.randn(input_shape)) self.assertEqual(result.shape, expected_shape) - @parameterized.expand([ - ("img_size_too_large_for_patch_size", 1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", 0.3), - ("num_heads_out_of_bound", 1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", 0.3), - ("img_size_not_divisible_by_patch_size", 1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", 0.3), - ("invalid_pos_embed", 4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", 0.3), - ("patch_size_not_divisible", 4, (96, 96, 96), (9, 9, 9), 768, 3072, 12, 12, "perc", 0.3), - # Add more test cases as needed - ]) - def test_ill_arg(self, name, in_channels, img_size, patch_size, hidden_size, mlp_dim, num_layers, num_heads, - pos_embed, dropout_rate): + @parameterized.expand( + [ + ("img_size_too_large_for_patch_size", 1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", 0.3), + ("num_heads_out_of_bound", 1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", 0.3), + ("img_size_not_divisible_by_patch_size", 1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", 0.3), + ("invalid_pos_embed", 4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", 0.3), + ("patch_size_not_divisible", 4, (96, 96, 96), (9, 9, 9), 768, 3072, 12, 12, "perc", 0.3), + # Add more test cases as needed + ] + ) + def test_ill_arg( + self, + name, + in_channels, + img_size, + patch_size, + hidden_size, + mlp_dim, + num_layers, + num_heads, + pos_embed, + dropout_rate, + ): with self.assertRaises(ValueError): ViTAutoEnc( in_channels=in_channels, From d01b61e54c419f551731359d1085e8ec096672a0 Mon Sep 17 00:00:00 2001 From: Han Wang Date: Thu, 18 Apr 2024 16:51:20 +0100 Subject: [PATCH 3/5] fix formatting issues for three more files Signed-off-by: Han Wang --- tests/test_hausdorff_loss.py | 16 ++----------- tests/test_tversky_loss.py | 8 +------ ...est_ultrasound_confidence_map_transform.py | 24 +++---------------- 3 files changed, 6 insertions(+), 42 deletions(-) diff --git a/tests/test_hausdorff_loss.py b/tests/test_hausdorff_loss.py index 00d1364183..f2211008c2 100644 --- a/tests/test_hausdorff_loss.py +++ b/tests/test_hausdorff_loss.py @@ -219,13 +219,7 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): HausdorffDTLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand( - [ - (False, False, False), - (False, True, False), - (False, False, True), - ] - ) + @parameterized.expand([(False, False, False), (False, True, False), (False, False, True)]) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) @@ -257,13 +251,7 @@ def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): LogHausdorffDTLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand( - [ - (False, False, False), - (False, True, False), - (False, False, True), - ] - ) + @parameterized.expand([(False, False, False), (False, True, False), (False, False, True)]) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 1, 3)) chn_target = torch.ones((1, 1, 1, 3)) diff --git a/tests/test_tversky_loss.py b/tests/test_tversky_loss.py index 24518ebd00..0365503ea2 100644 --- a/tests/test_tversky_loss.py +++ b/tests/test_tversky_loss.py @@ -165,13 +165,7 @@ def test_ill_shape(self): with self.assertRaisesRegex(ValueError, ""): TverskyLoss(reduction=None)(chn_input, chn_target) - @parameterized.expand( - [ - (False, False, False), - (False, True, False), - (False, False, True), - ] - ) + @parameterized.expand([(False, False, False), (False, True, False), (False, False, True)]) def test_input_warnings(self, include_background, softmax, to_onehot_y): chn_input = torch.ones((1, 1, 3)) chn_target = torch.ones((1, 1, 3)) diff --git a/tests/test_ultrasound_confidence_map_transform.py b/tests/test_ultrasound_confidence_map_transform.py index 71abac74f9..63ce7d58e4 100644 --- a/tests/test_ultrasound_confidence_map_transform.py +++ b/tests/test_ultrasound_confidence_map_transform.py @@ -537,12 +537,7 @@ def test_parameters(self): UltrasoundConfidenceMapTransform(sink_mode="unknown") @parameterized.expand( - [ - ("all", SINK_ALL_OUTPUT), - ("mid", SINK_MID_OUTPUT), - ("min", SINK_MIN_OUTPUT), - ("mask", SINK_MASK_OUTPUT, True), - ] + [("all", SINK_ALL_OUTPUT), ("mid", SINK_MID_OUTPUT), ("min", SINK_MIN_OUTPUT), ("mask", SINK_MASK_OUTPUT, True)] ) def test_ultrasound_confidence_map_transform(self, sink_mode, expected_output, use_mask=False): # RGB image @@ -589,14 +584,7 @@ def test_multi_channel_2d(self, sink_mode, expected_output, use_mask=False): self.assertIsInstance(result_np, np.ndarray) assert_allclose(result_np, expected_output, rtol=1e-4, atol=1e-4) - @parameterized.expand( - [ - ("all",), - ("mid",), - ("min",), - ("mask",), - ] - ) + @parameterized.expand([("all",), ("mid",), ("min",), ("mask",)]) def test_non_one_first_dim(self, sink_mode): transform = UltrasoundConfidenceMapTransform(sink_mode=sink_mode) input_img_rgb = np.repeat(self.input_img_np, 3, axis=0) @@ -631,13 +619,7 @@ def test_no_first_dim(self, sink_mode): with self.assertRaises(ValueError): transform(input_img_rgb, self.input_mask_np) - @parameterized.expand( - [ - ("all",), - ("mid",), - ("min",), - ] - ) + @parameterized.expand([("all",), ("mid",), ("min",)]) def test_sink_mode(self, mode): transform = UltrasoundConfidenceMapTransform(sink_mode=mode) From 82c125e8e7b433025cebd7674c095d4ea8cb56e4 Mon Sep 17 00:00:00 2001 From: Han Wang Date: Fri, 19 Apr 2024 11:34:09 +0100 Subject: [PATCH 4/5] Reformat test cases and remove unused parameters. Signed-off-by: Han Wang --- tests/test_affine_transform.py | 20 ++++-------------- tests/test_compute_f_beta.py | 20 +++++------------- tests/test_global_mutual_information_loss.py | 18 +++++++--------- tests/test_median_filter.py | 11 +++------- tests/test_multi_scale.py | 9 ++++---- tests/test_prepare_batch_default.py | 9 ++++---- tests/test_vitautoenc.py | 22 ++++++-------------- 7 files changed, 34 insertions(+), 75 deletions(-) diff --git a/tests/test_affine_transform.py b/tests/test_affine_transform.py index 30c11f90a9..11464070e0 100644 --- a/tests/test_affine_transform.py +++ b/tests/test_affine_transform.py @@ -135,24 +135,12 @@ class TestAffineTransform(unittest.TestCase): @parameterized.expand( [ - ( - "shift", - torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), - [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]], - ), - ( - "shift_1", - torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]), - [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]], - ), - ( - "shift_2", - torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), - [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]], - ), + (torch.as_tensor([[1.0, 0.0, 0.0], [0.0, 1.0, -1.0]]), [[[[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]]]), + (torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0]]), [[[[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]]]), + (torch.as_tensor([[1.0, 0.0, -1.0], [0.0, 1.0, 0.0]]), [[[[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]]]), ] ) - def test_affine_transforms(self, name, affine, expected): + def test_affine_transforms(self, affine, expected): image = torch.as_tensor([[[[4.0, 1.0, 3.0, 2.0], [7.0, 6.0, 8.0, 5.0], [3.0, 5.0, 3.0, 6.0]]]]) out = AffineTransform(align_corners=False)(image, affine) out = out.detach().cpu().numpy() diff --git a/tests/test_compute_f_beta.py b/tests/test_compute_f_beta.py index 421a52823f..43ebb6a6d5 100644 --- a/tests/test_compute_f_beta.py +++ b/tests/test_compute_f_beta.py @@ -36,27 +36,17 @@ def test_expecting_success_and_device(self): @parameterized.expand( [ + (0.5, torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), torch.Tensor([0.609756])), # success_beta_0_5 + (2, torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), torch.Tensor([0.862069])), # success_beta_2 ( - "success_beta_0_5", - FBetaScore(beta=0.5), - torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), - torch.Tensor([0.609756]), - ), - ( - "success_beta_2", - FBetaScore(beta=2), - torch.Tensor([[1, 0, 1], [0, 1, 0], [1, 0, 1]]), - torch.Tensor([0.862069]), - ), - ( - "denominator_zero", - FBetaScore(beta=2), + 2, # success_beta_2, denominator_zero torch.Tensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]), torch.Tensor([0.0]), ), ] ) - def test_success_and_zero(self, name, metric, y, expected_score): + def test_success_and_zero(self, beta, y, expected_score): + metric = FBetaScore(beta=beta) metric(y_pred=torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]), y=y) assert_allclose(metric.aggregate()[0], expected_score, atol=1e-6, rtol=1e-6) diff --git a/tests/test_global_mutual_information_loss.py b/tests/test_global_mutual_information_loss.py index 0cfbd727dd..22f5e88431 100644 --- a/tests/test_global_mutual_information_loss.py +++ b/tests/test_global_mutual_information_loss.py @@ -119,29 +119,27 @@ class TestGlobalMutualInformationLossIll(unittest.TestCase): @parameterized.expand( [ - ("mismatched_simple_dims", torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), + (torch.ones((1, 2), dtype=torch.float), torch.ones((1, 3), dtype=torch.float)), # mismatched_simple_dims ( - "mismatched_advanced_dims", torch.ones((1, 3, 3), dtype=torch.float), torch.ones((1, 3), dtype=torch.float), - ), - # You can add more test cases as needed + ), # mismatched_advanced_dims ] ) - def test_ill_shape(self, name, input1, input2): + def test_ill_shape(self, input1, input2): loss = GlobalMutualInformationLoss() with self.assertRaises(ValueError): loss.forward(input1, input2) @parameterized.expand( [ - ("num_bins_zero", 0, "mean", ValueError, ""), - ("num_bins_negative", -1, "mean", ValueError, ""), - ("reduction_unknown", 64, "unknown", ValueError, ""), - ("reduction_none", 64, None, ValueError, ""), + (0, "mean", ValueError, ""), # num_bins_zero + (-1, "mean", ValueError, ""), # num_bins_negative + (64, "unknown", ValueError, ""), # reduction_unknown + (64, None, ValueError, ""), # reduction_none ] ) - def test_ill_opts(self, name, num_bins, reduction, expected_exception, expected_message): + def test_ill_opts(self, num_bins, reduction, expected_exception, expected_message): pred = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) target = torch.ones((1, 3, 3, 3, 3), dtype=torch.float, device=device) with self.assertRaisesRegex(expected_exception, expected_message): diff --git a/tests/test_median_filter.py b/tests/test_median_filter.py index 96ddb74056..516388afce 100644 --- a/tests/test_median_filter.py +++ b/tests/test_median_filter.py @@ -21,14 +21,9 @@ class MedianFilterTestCase(unittest.TestCase): - @parameterized.expand( - [ - ("3d_big", torch.ones(1, 1, 2, 3, 5), MedianFilter([1, 2, 4])), - ("3d", torch.ones(1, 1, 4, 3, 4), MedianFilter(1)), - ] - ) - def test_3d(self, name, input_tensor, filter): - filter = filter.to(torch.device("cpu:0")) + @parameterized.expand([(torch.ones(1, 1, 2, 3, 5), [1, 2, 4]), (torch.ones(1, 1, 4, 3, 4), 1)]) # 3d_big # 3d + def test_3d(self, input_tensor, radius): + filter = MedianFilter(radius).to(torch.device("cpu:0")) expected = input_tensor.numpy() output = filter(input_tensor).cpu().numpy() diff --git a/tests/test_multi_scale.py b/tests/test_multi_scale.py index 9ce04c9b47..0b49087216 100644 --- a/tests/test_multi_scale.py +++ b/tests/test_multi_scale.py @@ -60,17 +60,16 @@ def test_shape(self, input_param, input_data, expected_val): @parameterized.expand( [ - ("kernel_none", {"loss": dice_loss, "kernel": "none"}, None, None), - ("scales_negative", {"loss": dice_loss, "scales": [-1]}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), + ({"loss": dice_loss, "kernel": "none"}, None, None), # kernel_none + ({"loss": dice_loss, "scales": [-1]}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3))), # scales_negative ( - "scales_negative_reduction_none", {"loss": dice_loss, "scales": [-1], "reduction": "none"}, torch.ones((1, 1, 3)), torch.ones((1, 1, 3)), - ), + ), # scales_negative_reduction_none ] ) - def test_ill_opts(self, name, kwargs, input, target): + def test_ill_opts(self, kwargs, input, target): if input is None and target is None: with self.assertRaisesRegex(ValueError, ""): MultiScaleLoss(**kwargs) diff --git a/tests/test_prepare_batch_default.py b/tests/test_prepare_batch_default.py index fae72ac742..93a9be04bc 100644 --- a/tests/test_prepare_batch_default.py +++ b/tests/test_prepare_batch_default.py @@ -31,7 +31,6 @@ class TestPrepareBatchDefault(unittest.TestCase): @parameterized.expand( [ ( - "dict_content", [ { "image": torch.tensor([1, 2]), @@ -43,10 +42,10 @@ class TestPrepareBatchDefault(unittest.TestCase): ], TestNet(), True, - ), - ("tensor_content", [torch.tensor([1, 2])], torch.nn.Identity(), True), - ("pair_content", [(torch.tensor([1, 2]), torch.tensor([3, 4]))], torch.nn.Identity(), True), - ("empty_data", [], TestNet(), False), + ), # dict_content + ([torch.tensor([1, 2])], torch.nn.Identity(), True), # tensor_content + ([(torch.tensor([1, 2]), torch.tensor([3, 4]))], torch.nn.Identity(), True), # pair_content + ([], TestNet(), False), # empty_data ] ) def test_prepare_batch(self, name, dataloader, network, should_run): diff --git a/tests/test_vitautoenc.py b/tests/test_vitautoenc.py index 02a6787672..c68c583a0e 100644 --- a/tests/test_vitautoenc.py +++ b/tests/test_vitautoenc.py @@ -84,26 +84,16 @@ def test_shape(self, input_param, input_shape, expected_shape): @parameterized.expand( [ - ("img_size_too_large_for_patch_size", 1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", 0.3), - ("num_heads_out_of_bound", 1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", 0.3), - ("img_size_not_divisible_by_patch_size", 1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", 0.3), - ("invalid_pos_embed", 4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", 0.3), - ("patch_size_not_divisible", 4, (96, 96, 96), (9, 9, 9), 768, 3072, 12, 12, "perc", 0.3), + (1, (32, 32, 32), (64, 64, 64), 512, 3072, 12, 8, "perceptron", 0.3), # img_size_too_large_for_patch_size + (1, (96, 96, 96), (8, 8, 8), 512, 3072, 12, 14, "conv", 0.3), # num_heads_out_of_bound + (1, (97, 97, 97), (4, 4, 4), 768, 3072, 12, 8, "perceptron", 0.3), # img_size_not_divisible_by_patch_size + (4, (96, 96, 96), (16, 16, 16), 768, 3072, 12, 12, "perc", 0.3), # invalid_pos_embed + (4, (96, 96, 96), (9, 9, 9), 768, 3072, 12, 12, "perc", 0.3), # patch_size_not_divisible # Add more test cases as needed ] ) def test_ill_arg( - self, - name, - in_channels, - img_size, - patch_size, - hidden_size, - mlp_dim, - num_layers, - num_heads, - pos_embed, - dropout_rate, + self, in_channels, img_size, patch_size, hidden_size, mlp_dim, num_layers, num_heads, pos_embed, dropout_rate ): with self.assertRaises(ValueError): ViTAutoEnc( From cd49a0c3597f2fc0b5488ae9060537a14b6ec6c0 Mon Sep 17 00:00:00 2001 From: Han Wang Date: Fri, 19 Apr 2024 14:30:57 +0100 Subject: [PATCH 5/5] fix assert error Signed-off-by: Han Wang --- tests/test_prepare_batch_default.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_prepare_batch_default.py b/tests/test_prepare_batch_default.py index 93a9be04bc..9aa498866f 100644 --- a/tests/test_prepare_batch_default.py +++ b/tests/test_prepare_batch_default.py @@ -48,7 +48,7 @@ class TestPrepareBatchDefault(unittest.TestCase): ([], TestNet(), False), # empty_data ] ) - def test_prepare_batch(self, name, dataloader, network, should_run): + def test_prepare_batch(self, dataloader, network, should_run): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") evaluator = SupervisedEvaluator( device=device, @@ -64,10 +64,10 @@ def test_prepare_batch(self, name, dataloader, network, should_run): if should_run: output = evaluator.state.output - if name == "dict_content" or name == "pair_content": + if isinstance(dataloader[0], dict) or isinstance(dataloader[0], tuple): assert_allclose(output["image"], torch.tensor([1, 2], device=device)) assert_allclose(output["label"], torch.tensor([3, 4], device=device)) - elif name == "tensor_content": + else: assert_allclose(output["image"], torch.tensor([1, 2], device=device)) self.assertTrue(output["label"] is None)