Skip to content
Merged
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
5 changes: 3 additions & 2 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,9 @@ in the loss with the label processor's ``pos_weight``:
.. code-block:: python

output_schema = {"mortality": ("binary", {"pos_weight": "balanced"})}
# or a fixed weight: ("binary", {"pos_weight": 9.0}); per label for
# ("multilabel", {"pos_weight": [...]})
# or a fixed weight: ("binary", {"pos_weight": 9.0}); per label, in the
# order of the given labels:
# ("multilabel", {"labels": [...], "pos_weight": [...]})

``"balanced"`` is negatives / positives over the samples the processor is
fitted on, so fit the processors on the training split
Expand Down
16 changes: 15 additions & 1 deletion pyhealth/datasets/sample_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from ..processors import get_processor, IgnoreProcessor
from ..processors.base_processor import FeatureProcessor
from ..processors.label_processor import LabelProcessor

if TYPE_CHECKING: # splitter imports this module
from .splitter import Split
Expand Down Expand Up @@ -241,7 +242,11 @@ def fit(
:class:`~pyhealth.datasets.PatientSplit`. When given,
processors are fitted on the first (training) part only, and
the sample indices of every part are kept in
``split_indices``.
``split_indices``. Label processors with a learned
vocabulary then add the labels of every part
(:meth:`~pyhealth.processors.LabelProcessor.fit_test`), so
a class seen only in validation or test still gets a model
output.

Behavior:
- Validates the samples contain all keys specified by the input
Expand Down Expand Up @@ -299,6 +304,15 @@ def fit(
if key not in processors:
processor = self._get_processor_instance(spec)
processor.fit(fit_samples, key)
if (
split is not None
and isinstance(processor, LabelProcessor)
and processor.need_fit_test
):
# The label vocabulary covers every split, test
# included; fit_test learns nothing else from them.
# Without a split, fit already saw every label.
processor.fit_test(samples, key)
processors[key] = processor
if split is None and getattr(processor, "learns_statistics", False):
learned_on_all.append(key)
Expand Down
135 changes: 133 additions & 2 deletions pyhealth/processors/label_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import math
from numbers import Real
from abc import abstractmethod
from collections.abc import Hashable, Iterable, Sequence
from typing import Any, ClassVar
Expand Down Expand Up @@ -57,6 +58,50 @@ class LabelProcessor(FeatureProcessor):

mode: ClassVar[str]
stores_tensor = True
need_fit_test: bool = False
"""Whether :meth:`fit_test` has anything to learn: True for a label
vocabulary learned from the data (``labels`` not given)."""

def fit_test(self, samples: Iterable[dict[str, Any]], field: str) -> None:
"""Adds the labels that only occur outside the training samples.

This is the only fitting step that sees validation and test samples.
It exists because a label vocabulary (the classes, and so
:meth:`size` and the model's output layer) has to cover the test
labels too: a class seen only in validation or test, common for rare
drugs in drug recommendation, would otherwise have no output and fail
in :meth:`process`.

Call it after :meth:`fit`: :meth:`fit` learns from the training
samples, then this adds the labels of all samples to the vocabulary.
:class:`~pyhealth.datasets.sample_dataset.SampleBuilder` does this for
every processor with :attr:`need_fit_test` when it is given a split;
without one, ``fit`` already saw every label. Calling it again, or on
the samples ``fit`` saw, changes nothing.

.. warning::

**Learn only which label values exist here, nothing else.**
Anything computed from the label values (label frequencies, class
weights such as ``pos_weight="balanced"``, means, scales, ...)
must be learned in :meth:`fit`, from the training samples only.
Learning it here leaks test labels into training.

The default learns nothing: labels without a vocabulary to learn
(binary, regression, given ``labels``) need none.

Args:
samples: Samples of every split, test included.
field: The label field.

Examples:
>>> from pyhealth.processors import MultiClassLabelProcessor
>>> p = MultiClassLabelProcessor()
>>> p.fit([{"y": "a"}, {"y": "b"}], "y") # training split
>>> p.fit_test([{"y": "a"}, {"y": "b"}, {"y": "c"}], "y") # all splits
>>> p.label_vocab
{'a': 0, 'b': 1, 'c': 2}
"""

@abstractmethod
def size(self) -> int:
Expand Down Expand Up @@ -141,6 +186,24 @@ def _learned_vocab(seen: set) -> dict[Any, int]:
return {label: i for i, label in enumerate(sorted(seen))}


def _add_labels(processor: Any, seen: set, field: str) -> dict[Any, int] | None:
"""Rebuilds ``label_vocab`` over its labels and ``seen``, in the order of
:func:`_learned_vocab`, so the indices do not depend on the split.

Returns the old vocabulary when labels were added, else None.
"""
old = processor.label_vocab
new = seen - old.keys()
if not new:
return None
processor.label_vocab = _learned_vocab(set(old) | seen)
logger.info(
f"Label {field}: added {len(new)} labels that occur only outside the "
f"fitted samples; vocab: {processor.label_vocab}"
)
return old


def _index(vocab: dict[Any, int], label: Any) -> int:
try:
return vocab[label]
Expand Down Expand Up @@ -189,6 +252,25 @@ def _fit_pos_weight(self, targets: list[torch.Tensor]) -> None:
positives > 0, (len(stacked) - positives) / positives.clamp(min=1), 1.0
)

def _remap_pos_weight(self, old_vocab: dict[Any, int]) -> None:
"""Moves a ``"balanced"`` weight to the indices of a grown vocabulary.

Labels new to the vocabulary had no positives in the fitted samples,
so their weight is 1, as for any label without positives.
"""
if self.pos_weight != "balanced" or self._weight is None:
return
vocab = self.label_vocab # type: ignore[attr-defined]
weight = torch.ones(len(vocab))
for label, i in old_vocab.items():
weight[vocab[label]] = self._weight[i]
self._weight = weight
logger.warning(
"pos_weight='balanced': %d labels occur only outside the fitted "
"(training) samples; their weight is set to 1.",
len(vocab) - len(old_vocab),
)

@property
def weight(self) -> torch.Tensor | None:
"""The positive-class weight the loss uses, or None."""
Expand Down Expand Up @@ -312,6 +394,12 @@ def __init__(self, labels: int | Sequence[Hashable] | None = None):
super().__init__()
self.labels = labels
self.label_vocab: dict[Any, int] = {} if labels is None else _fixed_vocab(labels)
self.need_fit_test = labels is None

def fit_test(self, samples: Iterable[dict[str, Any]], field: str) -> None:
"""Adds the classes of all samples, see :meth:`LabelProcessor.fit_test`."""
if self.need_fit_test:
_add_labels(self, {sample[field] for sample in samples}, field)

def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None:
seen = {sample[field] for sample in samples}
Expand Down Expand Up @@ -366,8 +454,9 @@ class MultiLabelProcessor(_WeightedBCE, LabelProcessor):
When omitted, they are learned in ``fit``: ``0..K-1`` as is, any
other set in sorted order.
pos_weight: Weight of positive examples in the loss: a number for all
labels, one number per label, ``"balanced"`` (negatives /
positives of each label in the fitted samples) or None.
labels, one number per label (in the order of ``labels``, which
must then be given), ``"balanced"`` (negatives / positives of
each label in the fitted samples) or None.

Examples:
>>> from pyhealth.processors import MultiLabelProcessor
Expand All @@ -388,7 +477,49 @@ def __init__(
super().__init__()
self.labels = labels
self.label_vocab: dict[Any, int] = {} if labels is None else _fixed_vocab(labels)
self.need_fit_test = labels is None
self._init_pos_weight(pos_weight)
self._check_per_label_weight()

def _check_per_label_weight(self) -> None:
"""A per-label ``pos_weight`` needs given ``labels``, one weight each.

Weights are matched to labels by position, and a learned vocabulary's
order is only known after fitting, so without ``labels`` a user
cannot know which weight goes to which label.
"""
pos_weight = self.pos_weight
if pos_weight is None or isinstance(pos_weight, str):
return
if isinstance(pos_weight, Real) or (
isinstance(pos_weight, torch.Tensor) and pos_weight.dim() == 0
):
return # one number for every label
if self.labels is None:
raise ValueError(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[high] Per-label pos_weight without labels= now raises (undisclosed breaking change)

Before this PR, MultiLabelProcessor(pos_weight=[2.0, 0.5]) without labels= was accepted: the weights were matched to the learned vocabulary in sorted label order. _check_per_label_weight now raises ValueError for every list, tuple or 1-D tensor weight when labels is None, including a one-element list that previously broadcast to all labels. The PR description does not mention this break. The existing test test_per_label_pos_weight was changed to pass labels=, and test_protoecgnet was edited the same way, which hides the change. Fix: either keep accepting the list (matching in sorted order, with a warning that the order depends on the data), or, if the break is intended, say so in the description and deprecate first. Add a test that documents the new error for user code that relied on the old behaviour.

"A per-label pos_weight needs labels=[...], which fixes the "
"label order the weights are matched to; without labels, the "
"order is learned from the data. Pass labels, or use one "
"number or 'balanced' for every label."
)
weight = self._weight
if weight is not None and len(weight) != len(self.label_vocab):
raise ValueError(
f"pos_weight has {len(weight)} weights for "
f"{len(self.label_vocab)} labels; give one weight per label."
)

def fit_test(self, samples: Iterable[dict[str, Any]], field: str) -> None:
"""Adds the labels of all samples, see :meth:`LabelProcessor.fit_test`.

A ``"balanced"`` weight keeps its training values; added labels get 1.
"""
if not self.need_fit_test:
return
seen = {label for sample in samples for label in sample[field]}
old_vocab = _add_labels(self, seen, field)
if old_vocab is not None:
self._remap_pos_weight(old_vocab)

def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None:
values = [sample[field] for sample in samples]
Expand Down
14 changes: 12 additions & 2 deletions pyhealth/processors/timeseries_label_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,28 @@ def __init__(self, base: B) -> None:
self.base: B = base
"""The static label processor of each record, fitted on all records."""
self.learns_statistics = base.learns_statistics
self.need_fit_test = base.need_fit_test

# ------------------------------------------------------------------
# FeatureProcessor
# ------------------------------------------------------------------
def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None:
"""Fits :attr:`base` on the values of every label record."""
records = [
self.base.fit(self._records(samples, field), field)

def fit_test(self, samples: Iterable[dict[str, Any]], field: str) -> None:
"""Adds the labels of every label record to :attr:`base`, see
:meth:`LabelProcessor.fit_test`."""
if self.need_fit_test:
self.base.fit_test(self._records(samples, field), field)

def _records(self, samples: Iterable[dict[str, Any]], field: str) -> list[dict]:
"""One sample per label record, holding its value under ``field``."""
return [
{field: self._value(value)}
for sample in samples
for value in sample[field]["values"]
]
self.base.fit(records, field)

def process(self, value: dict[str, Any]) -> tuple[torch.Tensor, torch.Tensor]:
if not isinstance(value, dict) or "time" not in value or "values" not in value:
Expand Down
110 changes: 109 additions & 1 deletion tests/core/test_label_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def test_against_the_torch_functions(self):

def test_per_label_pos_weight(self):
logits, y = torch.randn(3, 2), torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
processor = MultiLabelProcessor(pos_weight=[2.0, 0.5])
processor = MultiLabelProcessor(labels=["a", "b"], pos_weight=[2.0, 0.5])
expected = F.binary_cross_entropy_with_logits(
logits, y, pos_weight=torch.tensor([2.0, 0.5])
)
Expand Down Expand Up @@ -190,6 +190,114 @@ def test_pickles_from_before_the_options_load(self):
self.assertEqual(restored.process(["b"]).tolist(), [0.0, 1.0])


class TestFitTest(unittest.TestCase):
"""fit on the training labels, then fit_test adds the labels of every split."""

ALL = [{"y": "c"}, {"y": "b"}, {"y": "a"}]
TRAIN = [{"y": "a"}, {"y": "c"}]

def test_multiclass_adds_the_labels_of_every_split(self):
processor = MultiClassLabelProcessor()
processor.fit(self.TRAIN, "y")
self.assertEqual(processor.label_vocab, {"a": 0, "c": 1})
processor.fit_test(self.ALL, "y")
# The order is that of all labels, whatever the split.
self.assertEqual(processor.label_vocab, {"a": 0, "b": 1, "c": 2})
self.assertEqual(processor.process("c").item(), 2)

def test_order_does_not_depend_on_the_split(self):
labels = ["d", "b", "a", "c"]
for cls, value in ((MultiClassLabelProcessor, str), (MultiLabelProcessor, list)):
everything = [{"y": value(label)} for label in labels]
expected = cls()
expected.fit(everything, "y")
# Every non-empty training subset, in every position.
for mask in range(1, 2 ** len(labels)):
train = [s for i, s in enumerate(everything) if mask >> i & 1]
with self.subTest(cls=cls.__name__, train=train):
processor = cls()
processor.fit(train, "y")
processor.fit_test(everything, "y")
self.assertEqual(processor.label_vocab, expected.label_vocab)

def test_range_labels_keep_their_values(self):
processor = MultiClassLabelProcessor()
processor.fit([{"y": 0}, {"y": 2}], "y")
processor.fit_test([{"y": 1}], "y")
self.assertEqual(processor.label_vocab, {0: 0, 1: 1, 2: 2})

def test_running_it_again_changes_nothing(self):
processor = MultiClassLabelProcessor()
processor.fit(self.ALL, "y")
for _ in range(2):
processor.fit_test(self.ALL, "y")
self.assertEqual(processor.label_vocab, {"a": 0, "b": 1, "c": 2})

def test_need_fit_test_only_for_learned_vocabularies(self):
self.assertTrue(MultiClassLabelProcessor().need_fit_test)
self.assertTrue(MultiLabelProcessor().need_fit_test)
self.assertTrue(TimeseriesMultiClassLabelProcessor().need_fit_test)
for processor in (
MultiClassLabelProcessor(labels=["c", "b", "a"]),
MultiLabelProcessor(labels=2),
BinaryLabelProcessor(),
RegressionLabelProcessor(),
TimeseriesBinaryLabelProcessor(),
TimeseriesMultiClassLabelProcessor(labels=2),
TimeseriesRegressionLabelProcessor(),
):
with self.subTest(processor=processor):
self.assertFalse(processor.need_fit_test)
processor.fit_test(None, "y") # never reads the samples

def test_given_labels_are_kept(self):
processor = MultiClassLabelProcessor(labels=["c", "b", "a"])
processor.fit_test([{"y": "d"}], "y")
self.assertEqual(processor.label_vocab, {"c": 0, "b": 1, "a": 2})

def test_balanced_weight_keeps_its_training_values(self):
processor = MultiLabelProcessor(pos_weight="balanced")
processor.fit([{"y": ["a"]}, {"y": ["c"]}, {"y": ["c"]}], "y")
self.assertEqual(processor.weight.tolist(), [2.0, 0.5])
with self.assertLogs("pyhealth.processors.label_processor", "WARNING"):
processor.fit_test([{"y": ["a", "b"]}, {"y": ["c", "d"]}], "y")
self.assertEqual(processor.label_vocab, {"a": 0, "b": 1, "c": 2, "d": 3})
self.assertEqual(processor.weight.tolist(), [2.0, 1.0, 0.5, 1.0])

def test_given_and_unweighted_multilabel_weights_are_kept(self):
processor = MultiLabelProcessor(pos_weight=2.0)
processor.fit([{"y": ["a"]}], "y")
processor.fit_test([{"y": ["b"]}], "y")
self.assertEqual(processor.size(), 2)
self.assertEqual(processor.weight.tolist(), [2.0])
self.assertIsNone(MultiLabelProcessor().weight)

def test_per_label_weight_needs_given_labels(self):
# Without labels, the order the weights are matched to is unknown.
for cls in (MultiLabelProcessor, TimeseriesMultiLabelProcessor):
for weight in ([2.0, 0.5], (2.0,), torch.tensor([2.0, 0.5])):
with self.subTest(cls=cls.__name__, weight=weight):
with self.assertRaisesRegex(ValueError, "needs labels"):
cls(pos_weight=weight)
with self.assertRaisesRegex(ValueError, "2 weights for 3 labels"):
MultiLabelProcessor(labels=["a", "b", "c"], pos_weight=[2.0, 0.5])
# One number, or a weight per given label, is fine.
for weight in (2.0, 3, torch.tensor(2.0)):
MultiLabelProcessor(pos_weight=weight)
processor = TimeseriesMultiLabelProcessor(labels=["a", "b"], pos_weight=[2.0, 0.5])
self.assertEqual(processor.base.weight.tolist(), [2.0, 0.5])

def test_timeseries_labels(self):
multilabel = TimeseriesMultiLabelProcessor(pos_weight="balanced")
multilabel.fit([{"y": {"time": [0.0, 1.0], "values": [["a"], []]}}], "y")
with self.assertLogs("pyhealth.processors.label_processor", "WARNING"):
multilabel.fit_test(
[{"y": {"time": [0.0, 1.0], "values": [["a"], ["b"]]}}], "y"
)
self.assertEqual(multilabel.size(), 2)
self.assertEqual(multilabel.base.weight.tolist(), [1.0, 1.0])


class TestTimeseriesLabels(unittest.TestCase):
def test_multiclass_and_multilabel_values(self):
multiclass = TimeseriesMultiClassLabelProcessor()
Expand Down
Loading
Loading