Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion pyhealth/processors/label_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions tests/core/test_apricotm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]))

Expand Down
6 changes: 6 additions & 0 deletions tests/core/test_label_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
9 changes: 5 additions & 4 deletions tests/core/test_split_set_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading