pyhealth.processors.NestedMultiHotProcessor#

Processor for nested categorical sequences, emitted as per-visit multi-hot vectors.

Takes the same input as NestedSequenceProcessor – a list of visits, each a list of codes – but emits one row per visit with one column per vocabulary entry, set to 1 where the code is present. Repeats within a visit collapse, so this records presence rather than order or count.

Prefer it over NestedSequenceProcessor for set-membership models such as generative EHR models: the index form pads every visit to the longest visit seen during fit, so a single outlier visit sets the width for the whole dataset. Sizing by the vocabulary instead is both smaller and cheaper to consume.

class pyhealth.processors.NestedMultiHotProcessor(padding=0)[source]#

Bases: FeatureProcessor, TokenProcessorInterface

Nested categorical sequences as per-visit multi-hot vectors.

Same input as NestedSequenceProcessor – a list of visits, each a list of codes – but it emits what set-membership models actually consume: one row per visit, one column per vocabulary entry, 1 where the code is present.

NestedSequenceProcessor pads every visit to the longest visit seen during fit. That width is set by a single outlier: on eICU one visit holds 3,951 code entries (the same diagnosis re-charted through a stay) while a typical visit holds about five. Every downstream consumer then pays for it twice – once in memory, once again if it loops over the padding to find the handful of real codes.

For a 921-code vocabulary on eICU the multi-hot form is 8.6x smaller than the padded index form (4.5 KB vs 38.7 KB per patient), because it is sized by the vocabulary rather than by the worst-case visit.

A code charted five times in one visit sets the same column to 1 once. That matches what set-membership models already do with the index form, so swapping this in changes nothing about what a model sees. If you need counts, this is the wrong processor.

<pad> (0) and <unk> (1) keep their indices, so the vocabulary is interchangeable with NestedSequenceProcessor – a cached vocabulary from one restores into the other. Column 0 is therefore always zero: <pad> means “nothing here”, and marking it would make padding indistinguishable from a real code.

Examples

>>> processor = NestedMultiHotProcessor()
>>> samples = [{"codes": [["A", "B"], ["C"]]}]
>>> processor.fit(samples, "codes")
>>> out = processor.process([["A", "B"], ["A"]])
>>> out.shape           # (2 visits, vocab_size)
torch.Size([2, 5])
>>> out[0].nonzero().flatten().tolist()   # A and B present in visit 0
[2, 3]
stores_tensor: bool = True#
fit(samples, field)[source]#

Build the vocabulary. Inner length is irrelevant here, so unlike NestedSequenceProcessor nothing is measured about visit width.

Parameters:
  • samples (Iterable[dict[str, Any]]) – Sample dictionaries.

  • field (str) – Field holding the nested sequence.

Return type:

None

remove(tokens)[source]#

Remove specified vocabularies from the processor.

retain(tokens)[source]#

Retain only the specified vocabularies in the processor.

add(tokens)[source]#

Add specified vocabularies to the processor.

tokens()[source]#

Return the set of tokens in the processor’s vocabulary.

Return type:

set[str]

process(value)[source]#

Nested sequence -> (num_visits, vocab_size) float multi-hot.

Built with one scatter_ per visit rather than per-code assignment, so cost tracks the number of real codes, never the vocabulary size or a padded width.

An empty or None sample yields a single all-zero visit, mirroring NestedSequenceProcessor returning one all-<pad> row: both say “one visit, nothing in it”.

Parameters:

value (list[list[Any]]) – Nested list of codes [[code1, code2], [code3], ...].

Return type:

Tensor

Returns:

2D float tensor (num_visits, vocab_size), 1.0 where present.

size()[source]#

Feature width: the vocabulary, since that is the row length.

Return type:

int

vocab_size()[source]#

Return vocabulary size.

Return type:

int

is_token()[source]#

Output is a dense indicator vector, not token indices.

Return type:

bool

schema()[source]#

Returns the schema of the processed feature. For a processor that emits a single tensor, this should just return [“value”]. For a processor that emits a tuple of tensors, this should return a tuple of the same length as the tuple, with the semantic name of each tensor, such as [“time”, “value”], [“value”, “mask”], etc.

Typical semantic names include:
  • “value”: the main processed tensor output of the processor

  • “time”: the time tensor output of the processor (mostly for StageNet)

  • “mask”: the mask tensor output of the processor (if applicable)

Return type:

tuple[str, ...]

Returns:

Tuple of semantic names corresponding to the output of the processor.

dim()[source]#

Output is a 2D tensor (visits, vocab).

Return type:

tuple[int, ...]

spatial()[source]#

Whether each dimension (axis) of the value tensor is spatial (i.e. corresponds to a spatial axis like time, height, width, etc.) or not. This is used to determine how to apply augmentations and other transformations that should only be applied to spatial dimensions.

E.g. for CNN or RNN features, this would help determine which dimensions to apply spatial augmentations to, and which dimensions to treat as channels or features.

Return type:

tuple[bool, ...]

Returns:

Tuple of booleans corresponding to whether each axis of the value tensor is spatial or not.

PAD = 0#
UNK = 1#
learns_statistics: bool = False#
load(path)#

Optional: Load processor state from disk.

Parameters:

path (str) – File path to load processor state from.

Return type:

None

save(path)#

Optional: Save processor state to disk.

Parameters:

path (str) – File path to save processor state.

Return type:

None