|
| 1 | +import unittest |
| 2 | +import torch |
| 3 | +import os |
| 4 | +from chebai.callbacks.epoch_metrics import MacroF1 |
| 5 | +from torchmetrics.classification import MultilabelF1Score |
| 6 | +import random |
| 7 | + |
| 8 | + |
| 9 | +class TestCustomMacroF1Metric(unittest.TestCase): |
| 10 | + |
| 11 | + @classmethod |
| 12 | + def setUpClass(cls) -> None: |
| 13 | + cls.device = "cuda" if torch.cuda.is_available() else "cpu" |
| 14 | + |
| 15 | + @unittest.expectedFailure |
| 16 | + def test_all_predictions_are_1_half_labels_are_1(self): |
| 17 | + """Test custom metric against standard metric for the scenario where all prediction are 1 but only half of |
| 18 | + the labels are 1""" |
| 19 | + preds = torch.ones((1, 900), dtype=torch.int) |
| 20 | + label = torch.ones((1, 900), dtype=torch.int) |
| 21 | + |
| 22 | + mask = [ |
| 23 | + [True] * (label.size(1) // 2) |
| 24 | + + [False] * (label.size(1) - (label.size(1) // 2)) |
| 25 | + ] |
| 26 | + random.shuffle(mask[0]) |
| 27 | + label[torch.tensor(mask)] = 0 |
| 28 | + |
| 29 | + macro_f1_custom_score, macro_f1_standard_score = ( |
| 30 | + self.__get_custom_and_standard_metric_scores(label.shape[1], preds, label) |
| 31 | + ) |
| 32 | + |
| 33 | + # preds = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) |
| 34 | + # label = torch.tensor([[1, 1, 0, 0, 1, 1, 0, 0, 1, 0]]) |
| 35 | + # tps = [1, 1, 0, 0, 1, 1, 0, 0, 1, 0] |
| 36 | + # positive_predictions = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] |
| 37 | + # positive_labels = [1, 1, 0, 0, 1, 1, 0, 0, 1, 0] |
| 38 | + |
| 39 | + # ---------------------- For Standard F1 Macro Metric --------------------- |
| 40 | + # The metric is only proper defined when TP + FP ≠ 0 ∧ TP + FN ≠ 0 |
| 41 | + # If this case is encountered for any class/label, the metric for that class/label |
| 42 | + # will be set to 0 and the overall metric may therefore be affected in turn. |
| 43 | + |
| 44 | + # precision = [1, 1, 0, 0, 1, 1, 0, 0, 1, 0] |
| 45 | + # recall = [1, 1, 0, 0, 1, 1, 0, 0, 1, 0] |
| 46 | + # classwise_f1 = [2, 2, 0, 0, 2, 2, 0, 0, 2, 0] / [2, 2, 0, 0, 2, 2, 0, 0, 2, 0] |
| 47 | + # = [1, 1, 0, 0, 1, 1, 0, 0, 1, 0] |
| 48 | + # mean = 5/10 = 0.5 |
| 49 | + |
| 50 | + # ----------------------- For Custom F1 Metric ---------------------------- |
| 51 | + # Perform masking as first step to take only class with positive labels |
| 52 | + # mask = [True, True, False, False, True, True, False, False, True, False] |
| 53 | + # precision = [1, 1, 1, 1, 1] / [1, 1, 1, 1, 1] = [1, 1, 1, 1, 1] |
| 54 | + # recall = [1, 1, 1, 1, 1] / [1, 1, 1, 1, 1] = [1, 1, 1, 1, 1] |
| 55 | + # classwise_f1 = [2, 2, 2, 2, 2] / [2, 2, 2, 2, 2] = [1, 1, 1, 1, 1] |
| 56 | + # mean = 5/5 = 1 (because of masking we averaging with across positive labels only) |
| 57 | + |
| 58 | + self.assertAlmostEqual(macro_f1_custom_score, macro_f1_standard_score, places=4) |
| 59 | + |
| 60 | + def test_all_labels_are_1_half_predictions_are_1(self): |
| 61 | + """Test custom metric against standard metric for the scenario where all labels are 1 but only half of |
| 62 | + the predictions are 1""" |
| 63 | + preds = torch.ones((1, 900), dtype=torch.int) |
| 64 | + label = torch.ones((1, 900), dtype=torch.int) |
| 65 | + |
| 66 | + mask = [ |
| 67 | + [True] * (label.size(1) // 2) |
| 68 | + + [False] * (label.size(1) - (label.size(1) // 2)) |
| 69 | + ] |
| 70 | + random.shuffle(mask[0]) |
| 71 | + preds[torch.tensor(mask)] = 0 |
| 72 | + |
| 73 | + macro_f1_custom_score, macro_f1_standard_score = ( |
| 74 | + self.__get_custom_and_standard_metric_scores(label.shape[1], preds, label) |
| 75 | + ) |
| 76 | + |
| 77 | + # As we are only taking positive labels for custom metric calculation via masking, |
| 78 | + # and since all labels are positive in this scenario, custom and std metric are same |
| 79 | + self.assertAlmostEqual(macro_f1_custom_score, macro_f1_standard_score, places=4) |
| 80 | + |
| 81 | + def test_iterative_vs_single_call_approach(self): |
| 82 | + """Test the custom metric implementation in update fashion approach against |
| 83 | + the single call approach""" |
| 84 | + preds = torch.tensor([[1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1]]) |
| 85 | + label = torch.tensor([[0, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1]]) |
| 86 | + |
| 87 | + num_labels = label.shape[1] |
| 88 | + iterative_custom_metric = MacroF1(num_labels=num_labels) |
| 89 | + for i in range(label.shape[0]): |
| 90 | + iterative_custom_metric.update(preds[i].unsqueeze(0), label[i].unsqueeze(0)) |
| 91 | + iterative_custom_metric_score = iterative_custom_metric.compute().item() |
| 92 | + |
| 93 | + single_call_custom_metric = MacroF1(num_labels=num_labels) |
| 94 | + single_call_custom_metric_score = single_call_custom_metric(preds, label).item() |
| 95 | + |
| 96 | + self.assertEqual(iterative_custom_metric_score, single_call_custom_metric_score) |
| 97 | + |
| 98 | + @unittest.expectedFailure |
| 99 | + def test_metric_against_realistic_data(self): |
| 100 | + """Test the custom metric against the standard on realistic data""" |
| 101 | + directory_path = "CheBIOver100_test" |
| 102 | + abs_path = os.path.join(os.getcwd(), directory_path) |
| 103 | + print(f"Checking data from - {abs_path}") |
| 104 | + num_of_files = len(os.listdir(abs_path)) // 2 |
| 105 | + |
| 106 | + # load single file to get the num of labels for metric class instantiation |
| 107 | + labels = torch.load( |
| 108 | + f"{directory_path}/labels{0:03d}.pt", map_location=torch.device(self.device) |
| 109 | + ) |
| 110 | + num_labels = labels.shape[1] |
| 111 | + macro_f1_custom = MacroF1(num_labels=num_labels) |
| 112 | + macro_f1_standard = MultilabelF1Score(num_labels=num_labels, average="macro") |
| 113 | + |
| 114 | + # load each file in the directory and update the stats |
| 115 | + for i in range(num_of_files): |
| 116 | + labels = torch.load( |
| 117 | + f"{directory_path}/labels{i:03d}.pt", |
| 118 | + map_location=torch.device(self.device), |
| 119 | + ) |
| 120 | + preds = torch.load( |
| 121 | + f"{directory_path}/preds{i:03d}.pt", |
| 122 | + map_location=torch.device(self.device), |
| 123 | + ) |
| 124 | + macro_f1_standard.update(preds, labels) |
| 125 | + macro_f1_custom.update(preds, labels) |
| 126 | + |
| 127 | + macro_f1_custom_score = macro_f1_custom.compute().item() |
| 128 | + macro_f1_standard_score = macro_f1_standard.compute().item() |
| 129 | + print( |
| 130 | + f"Realistic Data - Custom F1 score: {macro_f1_custom_score}, Std. F1 score: {macro_f1_standard_score}" |
| 131 | + ) |
| 132 | + |
| 133 | + self.assertAlmostEqual(macro_f1_custom_score, macro_f1_standard_score, places=4) |
| 134 | + |
| 135 | + @unittest.expectedFailure |
| 136 | + def test_case_when_few_class_has_no_labels(self): |
| 137 | + """Test custom metric against standard metric for the scenario where some class has no labels""" |
| 138 | + preds = torch.tensor([[1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1]]) |
| 139 | + label = torch.tensor([[0, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1]]) |
| 140 | + macro_f1_custom_score, macro_f1_standard_score = ( |
| 141 | + self.__get_custom_and_standard_metric_scores(label.shape[1], preds, label) |
| 142 | + ) |
| 143 | + |
| 144 | + self.assertAlmostEqual(macro_f1_custom_score, macro_f1_standard_score, places=4) |
| 145 | + |
| 146 | + @staticmethod |
| 147 | + def __get_custom_and_standard_metric_scores(num_labels, preds, labels): |
| 148 | + # Custom metric score |
| 149 | + macro_f1_custom = MacroF1(num_labels=num_labels) |
| 150 | + macro_f1_custom_score = macro_f1_custom(preds, labels).item() |
| 151 | + |
| 152 | + # Standard metric score |
| 153 | + macro_f1_standard = MultilabelF1Score(num_labels=num_labels, average="macro") |
| 154 | + macro_f1_standard_score = macro_f1_standard(preds, labels).item() |
| 155 | + |
| 156 | + return macro_f1_custom_score, macro_f1_standard_score |
| 157 | + |
| 158 | + |
| 159 | +if __name__ == "__main__": |
| 160 | + unittest.main() |
0 commit comments