From 270bf010038f1d5b321d9c8ad197175d51b138fa Mon Sep 17 00:00:00 2001 From: AnvitDevadiga Date: Sun, 6 Dec 2026 17:35:56 +0530 Subject: [PATCH 1/3] fix(processors): keep balanced weight for labels without negatives pos_weight='balanced' set the weight of a label with no negative examples to 0, so every positive of that label dropped out of the loss and its gradient. Like labels without positives, such labels now get weight 1 and a warning. Fixes #1814 --- pyhealth/processors/label_processor.py | 9 ++++++++- tests/core/test_label_processor.py | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pyhealth/processors/label_processor.py b/pyhealth/processors/label_processor.py index 70bdf80d99..9165d91118 100644 --- a/pyhealth/processors/label_processor.py +++ b/pyhealth/processors/label_processor.py @@ -240,13 +240,20 @@ def _fit_pos_weight(self, targets: list[torch.Tensor]) -> None: raise ValueError("pos_weight='balanced' got no samples to fit on.") stacked = torch.stack([t.reshape(-1) for t in targets]) positives = stacked.sum(0) + negatives = len(stacked) - positives if bool((positives == 0).any()): logger.warning( "pos_weight='balanced': some labels have no positive examples; " "their weight is set to 1." ) + # a weight of 0 would drop every positive of a label from the loss + if bool((negatives == 0).any()): + logger.warning( + "pos_weight='balanced': some labels have no negative examples; " + "their weight is set to 1." + ) self._weight = torch.where( - positives > 0, (len(stacked) - positives) / positives.clamp(min=1), 1.0 + (positives > 0) & (negatives > 0), negatives / positives.clamp(min=1), 1.0 ) def _remap_pos_weight(self, old_vocab: dict[Any, int]) -> None: diff --git a/tests/core/test_label_processor.py b/tests/core/test_label_processor.py index 92eb815b58..fc2b97080b 100644 --- a/tests/core/test_label_processor.py +++ b/tests/core/test_label_processor.py @@ -154,6 +154,12 @@ def test_balanced_warns_on_a_label_without_positives(self): processor.fit([{"y": ["a"]}, {"y": []}], "y") self.assertEqual(processor.weight.tolist(), [1.0, 1.0]) + def test_balanced_warns_on_a_label_without_negatives(self): + processor = MultiLabelProcessor(labels=["a", "b"], pos_weight="balanced") + with self.assertLogs("pyhealth.processors.label_processor", "WARNING"): + processor.fit([{"y": ["a"]}, {"y": ["a", "b"]}, {"y": ["a"]}], "y") + self.assertEqual(processor.weight.tolist(), [1.0, 2.0]) + def test_fixed_multilabel_labels_are_checked_in_fit(self): with self.assertRaisesRegex(ValueError, "Unknown label 'c'"): MultiLabelProcessor(labels=["a", "b"]).fit([{"y": ["a", "c"]}], "y") From a3d8d1419fcd4e2e50925b83bd51582ae211e73a Mon Sep 17 00:00:00 2001 From: AnvitDevadiga Date: Sun, 6 Dec 2026 18:07:34 +0530 Subject: [PATCH 2/3] test(apricotm): expect weight 1 for a label positive in every sample test_balanced_pos_weight pinned the weight of 0 that #1814 reports; the label without negatives now falls back to 1 like a label without positives. --- tests/core/test_apricotm.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/core/test_apricotm.py b/tests/core/test_apricotm.py index a0153d3538..8f6a31bd75 100644 --- a/tests/core/test_apricotm.py +++ b/tests/core/test_apricotm.py @@ -329,11 +329,11 @@ def test_balanced_pos_weight(self): weighted = APRICOTM(self.dataset, static_key="static", embedding_dim=16, hidden_dim=8, state_size=4, top_k=3, pos_weight="balanced") - # "balanced" gives negatives / positives over the dataset, so the last - # label, positive in every sample, gets weight 0 (only labels with no - # positive at all fall back to 1). + # "balanced" gives negatives / positives over the dataset; labels with + # no positive or no negative (the last one is positive in every + # sample) fall back to 1. torch.testing.assert_close(weighted.label_processor.weight, - torch.tensor([1.0, 2.0, 1.0, 0.0])) + torch.tensor([1.0, 2.0, 1.0, 1.0])) self.assertIsNone(self.model.label_processor.weight) self.assertFalse(torch.allclose(plain, weighted(**batch)["loss"])) From f81f74ca265248c7691904b2543e895885c1fb32 Mon Sep 17 00:00:00 2001 From: AnvitDevadiga Date: Sun, 6 Dec 2026 19:21:25 +0530 Subject: [PATCH 3/3] test(split): expect weight 1 for a label in every training sample test_label_vocabulary_covers_every_split_part pinned weight 0 for drug "a", which occurs in every training sample; it now falls back to 1 (#1814). --- tests/core/test_split_set_task.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/core/test_split_set_task.py b/tests/core/test_split_set_task.py index 549af569aa..e5792a3bc8 100644 --- a/tests/core/test_split_set_task.py +++ b/tests/core/test_split_set_task.py @@ -338,10 +338,11 @@ def test_label_vocabulary_covers_every_split_part(self): self.assertEqual(out["cls"].label_vocab, {"a": 0, "b": 1, "c": 2}) self.assertEqual(out["drugs"].label_vocab, {"a": 0, "b": 1, "c": 2}) self.assertEqual(out["label"].label_vocab, {0: 0, 1: 1}) - # Statistics still come from the training part (p0-p3) only: "c" - # never occurs there, so its weight is 1, and the binary weight is - # 3 negatives / 1 positive (all samples would give 3 / 3). - self.assertEqual(out["drugs"].weight.tolist(), [0.0, 1.0, 1.0]) + # Statistics still come from the training part (p0-p3) only: "a" + # occurs in every sample there and "c" in none, so both weights are 1, + # and the binary weight is 3 negatives / 1 positive (all samples + # would give 3 / 3). + self.assertEqual(out["drugs"].weight.tolist(), [1.0, 1.0, 1.0]) self.assertEqual(out["label"].weight.tolist(), [3.0]) def test_label_vocabulary_does_not_depend_on_the_split(self):