custom_text_tokenization
Functions for tokenizing MEDS datasets.
Here, tokenization refers specifically to the process of converting a longitudinal, irregularly sampled, continuous time sequence into a temporal sequence at the level that will be consumed by deep-learning models.
All these functions take in normalized data – meaning data where there are no longer any code modifiers,
as those have been normalized alongside codes into integer indices (in the output code column). The only
columns of concern here thus are subject_id, time, code, numeric_value.
extract_seq_of_subject_events(df)
This function extracts sequences of subject events, which are sequences of measurements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
LazyFrame
|
The input data. |
required |
Returns:
| Type | Description |
|---|---|
LazyFrame
|
A tuple containing: |
dict[str, dict]
|
|
tuple[LazyFrame, dict[str, dict]]
|
|
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame({
... "subject_id": [1, 1, 1, 2, 2],
... "time": [None, datetime(2021, 1, 1), datetime(2021, 1, 13),
... None, datetime(2021, 1, 2)],
... "code": [100, 101, 102, 200, 201],
... "numeric_value": [1.0, 2.0, 3.0, 4.0, 5.0],
... "text_value": [None, "fever", None, None, "pain"]
... }).lazy()
>>> result_df, text_mapping = extract_seq_of_subject_events(df)
>>> result_df.collect()
shape: (2, 5)
┌────────────┬─────────────────┬─────────────────┬─────────────────┬─────────────────┐
│ subject_id ┆ time_delta_days ┆ code ┆ numeric_value ┆ modality_idx │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ list[f32] ┆ list[list[i64]] ┆ list[list[f64]] ┆ list[list[f32]] │
╞════════════╪═════════════════╪═════════════════╪═════════════════╪═════════════════╡
│ 1 ┆ [NaN, 12.0] ┆ [[101], [102]] ┆ [[2.0], [3.0]] ┆ [[0.0], [NaN]] │
│ 2 ┆ [NaN] ┆ [[201]] ┆ [[5.0]] ┆ [[1.0]] │
└────────────┴─────────────────┴─────────────────┴─────────────────┴─────────────────┘
>>> sorted(text_mapping.keys()) # Check text mapping was created
['0', '1']
Source code in meds_torch/utils/custom_text_tokenization.py
extract_statics_and_schema(df)
This function extracts static data and schema information (sequence of subject unique times).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
LazyFrame
|
The input data. |
required |
Returns:
| Type | Description |
|---|---|
LazyFrame
|
A tuple containing: |
dict[str, dict]
|
|
tuple[LazyFrame, dict[str, dict]]
|
|
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame({
... "subject_id": [1, 1, 1, 2, 2],
... "time": [None, datetime(2021, 1, 1), datetime(2021, 1, 13),
... None, datetime(2021, 1, 2)],
... "code": [100, 101, 102, 200, 201],
... "numeric_value": [1.0, 2.0, 3.0, 4.0, 5.0],
... "text_value": [None, "fever", "cough", None, "pain"]
... }).lazy()
>>> result_df = extract_statics_and_schema(df)
>>> result_df.collect()
shape: (2, 5)
┌────────────┬───────────┬───────────────┬─────────────────────┬─────────────────────────────────┐
│ subject_id ┆ code ┆ numeric_value ┆ start_time ┆ time │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ list[i64] ┆ list[f64] ┆ datetime[μs] ┆ list[datetime[μs]] │
╞════════════╪═══════════╪═══════════════╪═════════════════════╪═════════════════════════════════╡
│ 1 ┆ [100] ┆ [1.0] ┆ 2021-01-01 00:00:00 ┆ [2021-01-01 00:00:00, 2021-01-… │
│ 2 ┆ [200] ┆ [4.0] ┆ 2021-01-02 00:00:00 ┆ [2021-01-02 00:00:00] │
└────────────┴───────────┴───────────────┴─────────────────────┴─────────────────────────────────┘
Source code in meds_torch/utils/custom_text_tokenization.py
fill_to_nans(col)
This function fills infinite and null values with NaN.
This enables the downstream functions to naturally tensorize data into numpy or Torch tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col |
str | Expr
|
The input column. |
required |
Returns:
| Type | Description |
|---|---|
Expr
|
A |
Examples:
>>> print(fill_to_nans("value"))
.when([(col("value").is_infinite()) |
(col("value").is_null())]).then(dyn float: NaN).otherwise(col("value"))
>>> print(fill_to_nans(pl.col("time_delta")))
.when([(col("time_delta").is_infinite()) |
(col("time_delta").is_null())]).then(dyn float: NaN).otherwise(col("time_delta"))
>>> df = pl.DataFrame({"value": [1.0, float("inf"), None, -float("inf"), 2.0]})
>>> df.select(fill_to_nans("value").alias("value"))["value"].to_list()
[1.0, nan, nan, nan, 2.0]
Source code in meds_torch/utils/custom_text_tokenization.py
split_static_and_dynamic(df)
This function splits the input data into static and dynamic data.
Static data is data that has a null time, and dynamic data is everything else. For dynamic data, a modality index is added for non-null text values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
LazyFrame
|
The input data. |
required |
Returns:
| Type | Description |
|---|---|
LazyFrame
|
A tuple of two |
LazyFrame
|
dynamic data. |
Examples:
>>> from datetime import datetime
>>> df = pl.DataFrame({
... "subject_id": [1, 1, 2, 2],
... "time": [None, datetime(2021, 1, 1), None, datetime(2021, 1, 2)],
... "code": [100, 101, 200, 201],
... "numeric_value": [1.0, 2.0, 3.0, 4.0],
... "text_value": [None, "fever", None, "cough"]
... }).lazy()
>>> static, dynamic = split_static_and_dynamic(df)
>>> static.collect()
shape: (2, 4)
┌────────────┬──────┬───────────────┬────────────┐
│ subject_id ┆ code ┆ numeric_value ┆ text_value │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ f64 ┆ str │
╞════════════╪══════╪═══════════════╪════════════╡
│ 1 ┆ 100 ┆ 1.0 ┆ null │
│ 2 ┆ 200 ┆ 3.0 ┆ null │
└────────────┴──────┴───────────────┴────────────┘
>>> dynamic.collect()
shape: (2, 6)
┌────────────┬─────────────────────┬──────┬───────────────┬────────────┬──────────────┐
│ subject_id ┆ time ┆ code ┆ numeric_value ┆ text_value ┆ modality_idx │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ datetime[μs] ┆ i64 ┆ f64 ┆ str ┆ f32 │
╞════════════╪═════════════════════╪══════╪═══════════════╪════════════╪══════════════╡
│ 1 ┆ 2021-01-01 00:00:00 ┆ 101 ┆ 2.0 ┆ fever ┆ 1.0 │
│ 2 ┆ 2021-01-02 00:00:00 ┆ 201 ┆ 4.0 ┆ cough ┆ 0.0 │
└────────────┴─────────────────────┴──────┴───────────────┴────────────┴──────────────┘
Source code in meds_torch/utils/custom_text_tokenization.py
tokenize(cfg)
Main function for tokenizing MEDS datasets.
Examples:
>>> import tempfile
>>> import polars as pl
>>> from datetime import datetime
>>> from omegaconf import OmegaConf
>>> from safetensors import safe_open
>>>
>>> # Create temporary directory for test data
>>> with tempfile.TemporaryDirectory() as tmpdir:
... # Create test input data
... test_df = pl.DataFrame({
... "subject_id": [1, 1, 1, 2, 2],
... "time": [None, datetime(2021,1,1), datetime(2021,1,2), None, datetime(2021,1,3)],
... "code": [100, 101, 102, 200, 201],
... "numeric_value": [1.0, 2.0, 3.0, 4.0, 5.0],
... "text_value": [None, "normal", None, None, "abnormal"]
... })
...
... # Save test data
... in_fp = Path(tmpdir) / "shard_0.parquet"
... test_df.write_parquet(in_fp)
...
... # Create config
... cfg = OmegaConf.create({
... "stage": "tokenize",
... "stage_cfg": {
... "input_dir": str(tmpdir),
... "data_input_dir": str(tmpdir),
... "output_dir": str(tmpdir),
... "file_pattern": "shard_*.parquet",
... "do_sequential": True
... },
... "do_overwrite": True
... })
...
... # Run tokenize
... tokenize(cfg)
...
... # Verify outputs
... assert (Path(tmpdir) / "schemas" / "shard_0.parquet").exists()
... assert (Path(tmpdir) / "event_seqs" / "shard_0.parquet").exists()
... assert (Path(tmpdir) / "modalities" / "shard_0.safetensors").exists()
...
... # Check schema output
... schema_df = pl.read_parquet(Path(tmpdir) / "schemas" / "shard_0.parquet")
... assert len(schema_df) == 2 # Two subjects
... assert all(col in schema_df.columns for col in [
... "subject_id", "code", "numeric_value", "start_time"])
...
... # Check event sequences output
... events_df = pl.read_parquet(Path(tmpdir) / "event_seqs" / "shard_0.parquet")
... assert len(events_df) == 2 # Two subjects
... assert all(col in events_df.columns for col in [
... "subject_id", "time_delta_days", "code", "numeric_value", "modality_idx"])
...
... # Check event sequences output
... with safe_open(
... Path(tmpdir) / "modalities" / "shard_0.safetensors",
... framework="pt", device="cpu") as f:
... assert set(f.keys()) == {'1', '0'}
... print(f.get_tensor('1'))
... print(f.get_tensor('0'))
tensor([ 101, 2999, 102])
tensor([ 101, 22832, 102])
Source code in meds_torch/utils/custom_text_tokenization.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
tokenize_text_values(df)
Tokenize text values and create a mapping of code_modality to tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df |
DataFrame
|
DataFrame containing text values and their corresponding codes and modality indices. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, dict]
|
Dictionary mapping f”{code}_{modality_idx}” to tokenized text. |
Examples:
>>> df = pl.DataFrame({
... "code": [101, 201],
... "text_value": ["fever", "cough"],
... "modality_idx": [0, 1]
... })
>>> result = tokenize_text_values(df)
>>> sorted(result.keys()) # Check keys are formatted correctly
['0', '1']
>>> result['0']
tensor([ 101, 10880, 102])
>>> result['1']
tensor([ 101, 21810, 102])
>>> # Check empty case
>>> df_empty = pl.DataFrame({
... "code": [101],
... "text_value": [None],
... "modality_idx": [None]
... })
>>> tokenize_text_values(df_empty)
{}