|
| 1 | +import unittest |
| 2 | +import torch |
| 3 | +import os |
| 4 | +from chebai.callbacks.epoch_metrics import BalancedAccuracy |
| 5 | +import random |
| 6 | + |
| 7 | + |
| 8 | +class TestCustomBalancedAccuracyMetric(unittest.TestCase): |
| 9 | + |
| 10 | + @classmethod |
| 11 | + def setUpClass(cls) -> None: |
| 12 | + cls.device = "cuda" if torch.cuda.is_available() else "cpu" |
| 13 | + |
| 14 | + def test_iterative_vs_single_call_approach(self): |
| 15 | + """Test the custom metric implementation in update fashion approach against |
| 16 | + the single call approach""" |
| 17 | + |
| 18 | + preds = torch.tensor([[1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1]]) |
| 19 | + label = torch.tensor([[0, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1]]) |
| 20 | + |
| 21 | + num_labels = label.shape[1] |
| 22 | + iterative_custom_metric = BalancedAccuracy(num_labels=num_labels) |
| 23 | + for i in range(label.shape[0]): |
| 24 | + iterative_custom_metric.update(preds[i].unsqueeze(0), label[i].unsqueeze(0)) |
| 25 | + iterative_custom_metric_score = iterative_custom_metric.compute().item() |
| 26 | + |
| 27 | + single_call_custom_metric = BalancedAccuracy(num_labels=num_labels) |
| 28 | + single_call_custom_metric_score = single_call_custom_metric(preds, label).item() |
| 29 | + |
| 30 | + self.assertEqual(iterative_custom_metric_score, single_call_custom_metric_score) |
| 31 | + |
| 32 | + def test_metric_against_realistic_data(self): |
| 33 | + """Test the custom metric against the standard on realistic data""" |
| 34 | + directory_path = os.path.join("tests", "test_data", "CheBIOver100_test") |
| 35 | + abs_path = os.path.join(os.getcwd(), directory_path) |
| 36 | + print(f"Checking data from - {abs_path}") |
| 37 | + num_of_files = len(os.listdir(abs_path)) // 2 |
| 38 | + |
| 39 | + # load single file to get the num of labels for metric class instantiation |
| 40 | + labels = torch.load( |
| 41 | + f"{directory_path}/labels{0:03d}.pt", map_location=torch.device(self.device) |
| 42 | + ) |
| 43 | + num_labels = labels.shape[1] |
| 44 | + balanced_acc_custom = BalancedAccuracy(num_labels=num_labels) |
| 45 | + |
| 46 | + for i in range(num_of_files): |
| 47 | + labels = torch.load( |
| 48 | + f"{directory_path}/labels{i:03d}.pt", |
| 49 | + map_location=torch.device(self.device), |
| 50 | + ) |
| 51 | + preds = torch.load( |
| 52 | + f"{directory_path}/preds{i:03d}.pt", |
| 53 | + map_location=torch.device(self.device), |
| 54 | + ) |
| 55 | + balanced_acc_custom.update(preds, labels) |
| 56 | + |
| 57 | + balanced_acc_custom_score = balanced_acc_custom.compute().item() |
| 58 | + print(f"Balanced Accuracy for realistic data: {balanced_acc_custom_score}") |
| 59 | + |
| 60 | + def test_case_when_few_class_has_no_labels(self): |
| 61 | + """Test custom metric against standard metric for the scenario where some class has no labels""" |
| 62 | + preds = torch.tensor([[1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1]]) |
| 63 | + label = torch.tensor([[0, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1]]) # no labels |
| 64 | + |
| 65 | + # tp = [0, 1, 1, 2], fp = [2, 1, 0, 1], tn = [1, 1, 2, 0], fn = [0, 0, 0, 0] |
| 66 | + # tpr = [0, 1, 1, 2] / ([0, 1, 1, 2] + [0, 0, 0, 0]) = [0, 1, 1, 1] |
| 67 | + # tnr = [1, 1, 2, 0] / ([1, 1, 2, 0] + [2, 1, 0, 1]) = [0.33333, 0.5, 1, 0] |
| 68 | + # balanced_accuracy = ([0, 1, 1, 1] + [0.33333, 0.5, 1, 0]) / 2 = ([0.16666667, 0.75, 1, 0.5] |
| 69 | + # mean bal accuracy = 0.6041666666666666 |
| 70 | + |
| 71 | + balanced_acc_score = self.__get_custom_metric_score( |
| 72 | + preds, label, label.shape[1] |
| 73 | + ) |
| 74 | + |
| 75 | + self.assertAlmostEqual(balanced_acc_score, 0.6041666666, places=4) |
| 76 | + |
| 77 | + def test_all_predictions_are_1_half_labels_are_1(self): |
| 78 | + """Test custom metric against standard metric for the scenario where all prediction are 1 but only half of |
| 79 | + the labels are 1""" |
| 80 | + preds = torch.ones((1, 900), dtype=torch.int) |
| 81 | + label = torch.ones((1, 900), dtype=torch.int) |
| 82 | + |
| 83 | + mask = [ |
| 84 | + [True] * (label.size(1) // 2) |
| 85 | + + [False] * (label.size(1) - (label.size(1) // 2)) |
| 86 | + ] |
| 87 | + random.shuffle(mask[0]) |
| 88 | + label[torch.tensor(mask)] = 0 |
| 89 | + |
| 90 | + # preds = [1, 1, 1, 1], label = [0, 1, 0, 1] |
| 91 | + # tp = [0, 1, 0, 1], fp = [1, 0, 1, 0], tn = [0, 0, 0, 0], fn = [0, 0, 0, 0] |
| 92 | + # tpr = tp / (tp + fn) = [0, 1, 0, 1] / [0, 1, 0, 1] = [0, 1, 0, 1] |
| 93 | + # tnr = tn / (tn + fp) = [0, 0, 0, 0] |
| 94 | + # balanced accuracy = 1 / 4 = 0.25 |
| 95 | + |
| 96 | + balanced_acc_custom_score = self.__get_custom_metric_score( |
| 97 | + preds, label, label.shape[1] |
| 98 | + ) |
| 99 | + self.assertAlmostEqual(balanced_acc_custom_score, 0.25, places=4) |
| 100 | + |
| 101 | + def test_all_labels_are_1_half_predictions_are_1(self): |
| 102 | + """Test custom metric against standard metric for the scenario where all labels are 1 but only half of |
| 103 | + the predictions are 1""" |
| 104 | + preds = torch.ones((1, 900), dtype=torch.int) |
| 105 | + label = torch.ones((1, 900), dtype=torch.int) |
| 106 | + |
| 107 | + mask = [ |
| 108 | + [True] * (label.size(1) // 2) |
| 109 | + + [False] * (label.size(1) - (label.size(1) // 2)) |
| 110 | + ] |
| 111 | + random.shuffle(mask[0]) |
| 112 | + preds[torch.tensor(mask)] = 0 |
| 113 | + |
| 114 | + # label = [1, 1, 1, 1], pred = [0, 1, 0, 1] |
| 115 | + # tp = [0, 1, 0, 1], fp = [0, 1, 0, 1], tn = [0, 0, 0, 0], fn = [0, 0, 0, 0] |
| 116 | + # tpr = tp / (tp + fn) = [0, 1, 0, 1] / [0, 1, 0, 1] = [0, 1, 0, 1] |
| 117 | + # tnr = tn / (tn + fp) = [0, 0, 0, 0] |
| 118 | + # balanced accuracy = 1 / 4 = 0.25 |
| 119 | + |
| 120 | + balanced_acc_custom_score = self.__get_custom_metric_score( |
| 121 | + preds, label, label.shape[1] |
| 122 | + ) |
| 123 | + self.assertAlmostEqual(balanced_acc_custom_score, 0.25, places=4) |
| 124 | + |
| 125 | + @staticmethod |
| 126 | + def __get_custom_metric_score(preds, labels, num_labels): |
| 127 | + balanced_acc_custom = BalancedAccuracy(num_labels=num_labels) |
| 128 | + return balanced_acc_custom(preds, labels).item() |
| 129 | + |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + unittest.main() |
0 commit comments