diff --git a/docs/api/models.rst b/docs/api/models.rst index 20968daa07..36f78db48a 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -358,6 +358,7 @@ API Reference models/pyhealth.models.califorest models/pyhealth.models.XGBoostModel models/pyhealth.models.survival_mdn + models/pyhealth.models.survival_dcm models/pyhealth.models.personalized_survival_moe models/pyhealth.models.cet models/pyhealth.models.TrajSurv diff --git a/docs/api/models/pyhealth.models.survival_dcm.rst b/docs/api/models/pyhealth.models.survival_dcm.rst new file mode 100644 index 0000000000..c7eabc6bf4 --- /dev/null +++ b/docs/api/models/pyhealth.models.survival_dcm.rst @@ -0,0 +1,76 @@ +pyhealth.models.survival_dcm +============================ + +Overview +-------- + +Deep Cox Mixtures models right-censored survival with a mixture of Cox models. +A shared multilayer perceptron encodes each patient. A gate gives the +probability of belonging to each latent subgroup, and an expert gives one log +hazard ratio per subgroup. Each subgroup has its own non-parametric baseline +survival curve, so proportional hazards only has to hold within a subgroup and +the predicted survival curves of two patients can cross. The model follows +Nagpal, Yadlowsky, Rostamzadeh and Heller, `Deep Cox Mixtures for Survival +Regression `_ (MLHC 2021). +With ``num_components=1`` it is a single deep Cox model. + +Inputs and outputs +------------------ + +Create a PyHealth sample dataset with ``features: tensor`` as input schema and +``duration: tensor, event: tensor`` as output schema, for example with +:class:`~pyhealth.tasks.SurvivalDCMSupport2`. Each sample has a dense feature +vector, one positive duration and one event indicator (1 for an observed event, +0 for censoring). The features must be finite, so standardize them and impute +missing values first. + +``forward`` returns ``log_gate`` and ``log_hazard_ratio``, each of shape +``[batch, num_components]``, and the training ``loss`` when the labels are +given. In evaluation mode it also returns ``y_true``, with columns duration and +event, and ``y_prob``, the survival curve at every time in ``baseline_grid``. +Use ``predict_survival(features, times)`` for survival probabilities at chosen +times. + +Training +-------- + +Training is the approximate EM procedure of the paper. Call ``fit_baselines`` +once before training and again after every epoch, from your own training loop:: + + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + + model.fit_baselines(train_loader) + for epoch in range(num_epochs): + model.train() + for batch in train_loader: + optimizer.zero_grad() + loss = model(**batch)["loss"] + loss.backward() + optimizer.step() + model.fit_baselines(train_loader) + +PyHealth's ``Trainer.train`` does not refit the baseline curves between epochs, +so do not use it on its own to train this model. ``Trainer.inference`` and +``Trainer.evaluate`` work on a fitted model. + +Differences from the authors' implementation +-------------------------------------------- + +The baseline curves are refitted once per epoch, not every few batches. They +are smoothed with a cubic spline, as the paper describes, where the authors' +released PyTorch code uses a linear one. The optional variational auto-encoder +term is not included. The log hazard ratio is bounded with a scaled tanh, and +the default bound of 1 matches the authors' default. + +API +--- + +.. autoclass:: pyhealth.models.SurvivalDCM + :members: + :show-inheritance: + +.. autofunction:: pyhealth.models.survival_dcm.cox_partial_log_likelihood + +.. autofunction:: pyhealth.models.survival_dcm.breslow_baseline_survival + +.. autofunction:: pyhealth.models.survival_dcm.smooth_baseline_survival diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 7182e02a44..3041ca0f6c 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -318,3 +318,4 @@ Available Tasks Value Set Pair Classification (VSAC) Time-to-event survival (GBSG and SUPPORT) TCGA RNA-seq Survival Prediction + Deep Cox Mixtures Survival (SUPPORT2) diff --git a/docs/api/tasks/pyhealth.tasks.survival_dcm_support2.rst b/docs/api/tasks/pyhealth.tasks.survival_dcm_support2.rst new file mode 100644 index 0000000000..f7ae0d0ce8 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.survival_dcm_support2.rst @@ -0,0 +1,25 @@ +pyhealth.tasks.survival_dcm_support2 +==================================== + +Time-to-event survival prediction on :class:`~pyhealth.datasets.Support2Dataset` +in the representation used by Deep Cox Mixtures (Nagpal et al., MLHC 2021): one +sample per patient with a 44-value ``features`` vector and ``duration: [days]`` +and ``event: [indicator]`` labels. Event 1 is death; event 0 is censored. + +All 9,105 patients are kept. The features are 18 numeric covariates followed by +6 categorical covariates one-hot coded with every level kept, in the order of +``DCM_SUPPORT2_FEATURES``. A missing categorical value sets that covariate's +columns to 0. A missing numeric value is NaN in raw output and 0 after +standardization, which is mean imputation. + +This differs from :class:`~pyhealth.tasks.SurvivalTimeToEventSupport2`, which +uses the DeepSurv benchmark representation (8,873 complete cases, 27 features). + +Fit ``feature_mean`` and ``feature_scale`` on training patients and reuse them +for validation and test patients. Raw output is only for fitting those +statistics. + +.. autoclass:: pyhealth.tasks.SurvivalDCMSupport2 + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/support2_survival_survival_dcm.py b/examples/support2_survival_survival_dcm.py new file mode 100644 index 0000000000..a1bbd662a2 --- /dev/null +++ b/examples/support2_survival_survival_dcm.py @@ -0,0 +1,518 @@ +"""Authors: Murphy Crosby + +Deep Cox Mixtures on SUPPORT2: reproduction and an ablation of the mixture. + +Paper: Deep Cox Mixtures for Survival Regression, Nagpal et al., MLHC 2021. +https://proceedings.mlr.press/v149/nagpal21a.html + +This script runs the whole pipeline: load SUPPORT2 with ``Support2Dataset``, +build samples with the ``SurvivalDCMSupport2`` task, train ``SurvivalDCM`` +with cross-validation, and evaluate discrimination and calibration. + +How to run +---------- +With no arguments it generates a small synthetic SUPPORT2-like file, so it +runs anywhere in a few minutes. That run only shows that the pipeline works: +its numbers come from made-up data and say nothing about the models:: + + python examples/support2_survival_survival_dcm.py + +To use the real data, download ``support2.csv`` from the UCI Machine Learning +Repository (https://archive.ics.uci.edu/dataset/880/support2) and pass it:: + + python examples/support2_survival_survival_dcm.py --data /path/support2.csv + +The UCI file names its patient column ``id``; ``Support2Dataset`` expects +``sno``. The script writes a working copy with the column renamed. + +What is compared +---------------- +Every model is the same ``SurvivalDCM`` class with different settings: + +* ``CPH``: one subgroup and no hidden layer, a linear Cox model. +* ``Deep Cox (K=1)``: one subgroup with a hidden-layer encoder. This is a + single deep Cox model in the style of DeepSurv. +* ``DCM (K=3)``, ``DCM (K=4)``, ``DCM (K=6)``: the mixture, at the three + numbers of subgroups the paper tuned over. + +Ablation: the paper reports only its best ``K``. Comparing ``K=1`` with +``K=3, 4, 6`` on the same folds shows how much of the result comes from the +mixture itself rather than from the neural encoder. + +Evaluation follows the paper: 5-fold cross-validation, with predictions from +all folds pooled, at the 25th, 50th and 75th percentiles of the event times, +for all patients and for non-White patients (a missing race counts as +non-White, which reproduces the paper's 21.02%). The metrics are the +time-dependent concordance index (higher is better), the Brier score and the +expected calibration error (lower is better). Standard errors come from +bootstrapping the pooled predictions. + +Differences from the paper +-------------------------- +* Imputation and scaling statistics are fitted on each training fold only. + The authors fit them on all patients, which leaks test-fold information. +* Hyperparameters are fixed instead of tuned. As in the authors' code, + training stops early: about one training patient in seven is held out, and + training stops when the loss on them has not improved for 3 epochs. +* The concordance index is truncated at each horizon but not weighted for + censoring. The Brier score is censoring-weighted. The calibration error + uses a Kaplan-Meier estimate within each bin of predicted survival. + +Results +------- +Full run on the real SUPPORT2 file (9,105 patients, 31.89% censored, 21.02% +non-White; horizons 14, 58 and 252 days), with default settings. Each cell is +the 25th / 50th / 75th percentile horizon. + +All patients +model C_td Brier ECE +CPH 0.689 / 0.673 / 0.670 0.134 / 0.200 / 0.213 0.020 / 0.024 / 0.020 +Deep Cox (K=1) 0.696 / 0.680 / 0.676 0.133 / 0.197 / 0.211 0.022 / 0.023 / 0.016 +DCM (K=3) 0.753 / 0.713 / 0.679 0.124 / 0.189 / 0.211 0.018 / 0.022 / 0.029 +DCM (K=4) 0.725 / 0.695 / 0.668 0.128 / 0.194 / 0.214 0.017 / 0.017 / 0.021 +DCM (K=6) 0.742 / 0.702 / 0.673 0.125 / 0.192 / 0.213 0.015 / 0.021 / 0.027 + +Non-White patients +model C_td Brier ECE +CPH 0.716 / 0.700 / 0.692 0.133 / 0.193 / 0.205 0.031 / 0.038 / 0.038 +Deep Cox (K=1) 0.719 / 0.704 / 0.697 0.132 / 0.192 / 0.203 0.021 / 0.028 / 0.028 +DCM (K=3) 0.763 / 0.729 / 0.700 0.124 / 0.187 / 0.205 0.033 / 0.049 / 0.056 +DCM (K=4) 0.740 / 0.714 / 0.687 0.129 / 0.190 / 0.206 0.029 / 0.040 / 0.034 +DCM (K=6) 0.755 / 0.718 / 0.691 0.126 / 0.190 / 0.206 0.020 / 0.038 / 0.043 + +Bootstrap standard errors are about 0.004 to 0.007 for C_td, 0.002 for the +Brier score and 0.003 to 0.005 for ECE over all patients, and roughly twice +that for non-White patients. They reflect which patients are in the test +data, not the variation from retraining a model. + +Findings. On C_td and the Brier score the baselines reproduce the paper's +Table 8 to within about 0.003. DCM discriminates better than both baselines +at the 25th and 50th percentile horizons (paper, K tuned: 0.743 / 0.706 / +0.675), and the three are close at the 75th. DCM is at least as well +calibrated as the baselines at the first two horizons but not at the 75th, +and for non-White patients it does not have the lowest calibration error, so +that claim of the paper is not reproduced. + +Ablation. Every mixture (K=3, 4, 6) beats the single deep Cox model (K=1) on +C_td at the first two horizons: by 0.03 to 0.06 at the 25th percentile and by +0.015 to 0.033 at the 50th. So the gain comes from the mixture and not from +the encoder. The order among K=3, 4 and 6 changed between two training runs, +so there is no evidence that more than three subgroups helps. +""" + +import argparse +import copy +import csv +import tempfile +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +import yaml + +import pyhealth.datasets +from pyhealth.datasets import Support2Dataset, get_dataloader +from pyhealth.metrics import concordance_index, ipcw_brier_score +from pyhealth.models import SurvivalDCM +from pyhealth.tasks import SurvivalDCMSupport2 +from pyhealth.tasks.survival_dcm_support2 import ( + DCM_SUPPORT2_CATEGORIES, + DCM_SUPPORT2_FEATURES, + DCM_SUPPORT2_NUMERIC, +) + +# The models to compare. Each entry is the settings passed to SurvivalDCM. +MODELS = { + "CPH": {"num_components": 1, "num_hidden_layers": 0}, + "Deep Cox (K=1)": {"num_components": 1}, + "DCM (K=3)": {"num_components": 3}, + "DCM (K=4)": {"num_components": 4}, + "DCM (K=6)": {"num_components": 6}, +} +QUANTILES = (0.25, 0.50, 0.75) + + +def write_synthetic_support2(path: Path, num_patients: int, seed: int) -> None: + """Write a made-up file with SUPPORT2's columns, for running without data. + + Survival depends on age, on mean blood pressure and on the disease class, + so the models have something to learn. Some values are left missing. + + Args: + path: Where to write the CSV. + num_patients: Number of rows. + seed: Random seed. + """ + rng = np.random.default_rng(seed) + config = Path(pyhealth.datasets.__file__).parent / "configs" / "support2.yaml" + columns = ["sno"] + yaml.safe_load(config.read_text())["tables"]["support2"][ + "attributes" + ] + categories = dict(DCM_SUPPORT2_CATEGORIES) + + rows = [] + for i in range(num_patients): + row = {"sno": str(i + 1)} + for name in DCM_SUPPORT2_NUMERIC: + # About one value in ten is missing, written as in the UCI file. + row[name] = "NaN" if rng.random() < 0.1 else f"{rng.normal(50, 10):.2f}" + for name, levels in categories.items(): + row[name] = str(rng.choice(levels)) + # Most patients are White, as in the real data. + if rng.random() < 0.79: + row["race"] = "white" + age = rng.normal(63, 15) + blood_pressure = rng.normal(85, 25) + row["age"] = f"{age:.2f}" + row["meanbp"] = f"{blood_pressure:.2f}" + + # Cancer patients die on a different time pattern, so the hazards of + # the two groups are not proportional. + risk = np.exp(0.03 * (age - 63) - 0.02 * (blood_pressure - 85)) + shape = 0.7 if row["dzclass"] == "Cancer" else 1.8 + death_time = 200 * rng.weibull(shape) / risk ** (1 / shape) + censor_time = rng.exponential(600) + row["d.time"] = str(int(max(1, np.ceil(min(death_time, censor_time))))) + row["death"] = "1" if death_time <= censor_time else "0" + rows.append(row) + + with path.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=columns, restval="") + writer.writeheader() + writer.writerows(rows) + + +def prepare_data(data: Path | None, root: Path, seed: int) -> None: + """Put a ``support2.csv`` that ``Support2Dataset`` can read into ``root``. + + Args: + data: The real SUPPORT2 file, or None to generate synthetic data. + root: Working directory to write into. + seed: Random seed for the synthetic data. + """ + target = root / "support2.csv" + if data is None: + print("No --data given: using synthetic SUPPORT2-like data.") + write_synthetic_support2(target, num_patients=600, seed=seed) + return + # Read everything as text so the values are written back unchanged. + frame = pd.read_csv(data, dtype=str, keep_default_na=False) + if "sno" not in frame.columns: + frame = frame.rename(columns={"id": "sno"}) + frame.to_csv(target, index=False) + + +def load_all(samples) -> dict: + """Read a whole sample dataset into memory as one batch. + + Args: + samples: A PyHealth sample dataset. + + Returns: + ``patient_id`` (list), and ``features``, ``duration`` and ``event`` + as tensors with one row per patient. + """ + loader = get_dataloader(samples, batch_size=len(samples), shuffle=False) + batch = next(iter(loader)) + return { + "patient_id": list(batch["patient_id"]), + "features": batch["features"].float(), + "duration": batch["duration"].float().reshape(-1), + "event": batch["event"].float().reshape(-1), + } + + +def fit_standardizer(features: torch.Tensor) -> tuple[list[float], list[float]]: + """Fit the paper's imputation and scaling on raw training features. + + The mean of each column is taken over its observed values. The standard + deviation is taken after the missing values are replaced by that mean, + which is what imputing first and scaling second does. + + Args: + features: Raw features of the training patients, NaN where missing. + + Returns: + The mean and the scale of each column. + """ + mean = torch.nanmean(features, dim=0) + filled = torch.where(torch.isnan(features), mean, features) + scale = filled.std(dim=0, correction=0) + scale[scale == 0] = 1.0 # a constant column is left unscaled + return mean.tolist(), scale.tolist() + + +def validation_loss(model: SurvivalDCM, loader) -> float: + """Average loss of a model on held-out patients, without training on them.""" + model.eval() + with torch.no_grad(): + losses = [model(**batch)["loss"].item() for batch in loader] + return sum(losses) / len(losses) + + +def train_model( + train_samples, settings: dict, max_epochs: int, patience: int, seed: int +) -> tuple[SurvivalDCM, int]: + """Train one model with the EM loop, stopping early on a validation split. + + Some training patients are held out. After every epoch the loss on them + is measured, and training stops once it has not improved for ``patience`` + epochs in a row. The model is then put back to its best epoch. This keeps + the model from overfitting without ever looking at the test fold. + + Args: + train_samples: Standardized training samples. + settings: Keyword arguments for ``SurvivalDCM``. + max_epochs: Most passes over the training data. + patience: Epochs to wait for the validation loss to improve. + seed: Random seed. + + Returns: + The trained model, in evaluation mode, and the epoch it was taken from. + """ + torch.manual_seed(seed) + + # Hold out about one training patient in seven for validation. + rng = np.random.default_rng(seed) + shuffled = rng.permutation(len(train_samples)) + num_validation = len(train_samples) // 7 + validation_samples = train_samples.subset(shuffled[:num_validation].tolist()) + fit_samples = train_samples.subset(shuffled[num_validation:].tolist()) + + loader = get_dataloader(fit_samples, batch_size=128, shuffle=True, seed=seed) + validation_loader = get_dataloader( + validation_samples, batch_size=len(validation_samples), shuffle=False + ) + model = SurvivalDCM(fit_samples, **settings) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + + best_loss = float("inf") + best_state = copy.deepcopy(model.state_dict()) + best_epoch = 0 + epochs_without_improvement = 0 + + model.fit_baselines(loader) # once, before training + for epoch in range(1, max_epochs + 1): + model.train() + for batch in loader: + optimizer.zero_grad() + loss = model(**batch)["loss"] + loss.backward() + optimizer.step() + model.fit_baselines(loader) # again after every epoch + + current_loss = validation_loss(model, validation_loader) + if current_loss < best_loss: + best_loss = current_loss + best_state = copy.deepcopy(model.state_dict()) + best_epoch = epoch + epochs_without_improvement = 0 + else: + epochs_without_improvement = epochs_without_improvement + 1 + if epochs_without_improvement >= patience: + break + + model.load_state_dict(best_state) + model.eval() + return model, best_epoch + + +def concordance_at( + duration: np.ndarray, event: np.ndarray, survival: np.ndarray, time: float +) -> float: + """Time-dependent concordance index at one horizon. + + Among pairs where one patient died by ``time`` and the other outlived + them, this is the share where the model gave the patient who died the + lower survival probability at ``time``. + """ + # Only deaths up to the horizon start a comparison. + counted = event * (duration <= time) + return concordance_index(duration, counted, 1.0 - survival) + + +def kaplan_meier_at(duration: np.ndarray, event: np.ndarray, time: float) -> float: + """Kaplan-Meier estimate of the share of a group surviving past ``time``.""" + survival = 1.0 + for death_time in np.unique(duration[(event == 1) & (duration <= time)]): + at_risk = (duration >= death_time).sum() + deaths = ((duration == death_time) & (event == 1)).sum() + survival = survival * (1 - deaths / at_risk) + return survival + + +def calibration_error( + duration: np.ndarray, + event: np.ndarray, + survival: np.ndarray, + time: float, + num_bins: int = 10, +) -> float: + """Expected calibration error of survival probabilities at one horizon. + + Patients are sorted by predicted survival and cut into equal-sized bins. + In each bin the average prediction is compared with the share that + actually survived, estimated with Kaplan-Meier to allow for censoring. + The result is the average gap over the bins. + """ + order = np.argsort(survival) + total_gap = 0.0 + for members in np.array_split(order, num_bins): + predicted = survival[members].mean() + observed = kaplan_meier_at(duration[members], event[members], time) + total_gap = total_gap + len(members) * abs(observed - predicted) + return total_gap / len(survival) + + +METRICS = { + "C_td": concordance_at, + "Brier": ipcw_brier_score, + "ECE": calibration_error, +} + + +def score( + duration: np.ndarray, + event: np.ndarray, + survival: np.ndarray, + times: np.ndarray, + num_bootstrap: int, + seed: int, +) -> dict: + """Compute every metric at every horizon, with bootstrap standard errors. + + Args: + duration: Follow-up times of the scored patients. + event: Their event indicators. + survival: Predicted survival, one column per horizon. + times: The horizons. + num_bootstrap: Number of bootstrap resamples; 0 skips them. + seed: Random seed for the resampling. + + Returns: + ``{metric: [(value, standard_error), ...]}`` with one pair per + horizon. + """ + rng = np.random.default_rng(seed) + resamples = [ + rng.integers(0, len(duration), len(duration)) for _ in range(num_bootstrap) + ] + results = {} + for name, metric in METRICS.items(): + results[name] = [] + for column, time in enumerate(times): + value = metric(duration, event, survival[:, column], float(time)) + repeats = [ + metric(duration[rows], event[rows], survival[rows, column], float(time)) + for rows in resamples + ] + error = float(np.std(repeats)) if repeats else float("nan") + results[name].append((float(value), error)) + return results + + +def print_table(title: str, scores: dict, quantiles: tuple) -> None: + """Print one table: a row per model, a column per metric and horizon.""" + print(f"\n{title}") + header = f"{'model':<16}" + for name in METRICS: + for quantile in quantiles: + header += f"{name + '@' + str(int(quantile * 100)):>16}" + print(header) + for model_name, results in scores.items(): + line = f"{model_name:<16}" + for name in METRICS: + for value, error in results[name]: + if np.isnan(error): # no bootstrap was run + line += f"{value:>16.4f}" + else: + line += f"{value:>9.4f}±{error:<6.4f}" + print(line) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[1]) + parser.add_argument("--data", type=Path, help="path to the real support2.csv") + parser.add_argument("--folds", type=int, default=5) + parser.add_argument("--epochs", type=int, default=50, help="most epochs") + parser.add_argument("--patience", type=int, default=3) + parser.add_argument("--bootstrap", type=int, default=100) + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args() + + with tempfile.TemporaryDirectory() as workdir: + root = Path(workdir) + prepare_data(args.data, root, args.seed) + dataset = Support2Dataset( + root=str(root), tables=["support2"], cache_dir=root / "cache", num_workers=1 + ) + + # Raw pass: unstandardized features, NaN where a value is missing. + # These are used to fit the statistics and to find non-White patients. + raw = load_all(dataset.set_task(SurvivalDCMSupport2(), num_workers=1)) + patient_ids = raw["patient_id"] + duration = raw["duration"].numpy() + event = raw["event"].numpy() + white_column = DCM_SUPPORT2_FEATURES.index("race=white") + non_white = raw["features"][:, white_column].numpy() == 0 + times = np.quantile(duration[event == 1], QUANTILES) + print( + f"{len(patient_ids)} patients, {100 * (1 - event.mean()):.2f}% censored, " + f"{100 * non_white.mean():.2f}% non-White, horizons {times.tolist()}" + ) + + # Assign every patient to one of the folds at random. + rng = np.random.default_rng(args.seed) + fold_of = rng.permutation(len(patient_ids)) % args.folds + row_of = {pid: row for row, pid in enumerate(patient_ids)} + predictions = { + name: np.zeros((len(patient_ids), len(times))) for name in MODELS + } + + for fold in range(args.folds): + is_test = fold_of == fold + mean, scale = fit_standardizer(raw["features"][~is_test]) + + # Standardized pass, with this fold's training statistics. + task = SurvivalDCMSupport2(feature_mean=mean, feature_scale=scale) + samples = dataset.set_task(task, num_workers=1) + # The samples can come back in a different order, so match them + # to the raw pass by patient ID. + position = {pid: i for i, pid in enumerate(load_all(samples)["patient_id"])} + order = np.array([position[pid] for pid in patient_ids]) + train_samples = samples.subset(order[~is_test].tolist()) + test = load_all(samples.subset(order[is_test].tolist())) + test_rows = np.array([row_of[pid] for pid in test["patient_id"]]) + + for name, settings in MODELS.items(): + model, best_epoch = train_model( + train_samples, settings, args.epochs, args.patience, args.seed + ) + survival = model.predict_survival( + test["features"], torch.as_tensor(times, dtype=torch.float32) + ) + predictions[name][test_rows] = survival.numpy() + print( + f"fold {fold + 1}/{args.folds}: trained {name}, " + f"best epoch {best_epoch}" + ) + + # Pool the test predictions of all folds, then score them. + for title, rows in (("All patients", slice(None)), ("Non-White", non_white)): + scores = { + name: score( + duration[rows], + event[rows], + predictions[name][rows], + times, + args.bootstrap, + args.seed, + ) + for name in MODELS + } + print_table(title, scores, QUANTILES) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 6ffde7e4e5..faba36e240 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -122,6 +122,7 @@ from .generators.corgan import CorGAN as CorGAN from .generators.tardiff import TarDiff as TarDiff from .survival_mdn import SurvivalMDN as SurvivalMDN +from .survival_dcm import SurvivalDCM as SurvivalDCM from .personalized_survival_moe import PersonalizedSurvivalMoE as PersonalizedSurvivalMoE from .cet import CET as CET from .trajsurv import TrajSurv as TrajSurv diff --git a/pyhealth/models/survival_dcm.py b/pyhealth/models/survival_dcm.py new file mode 100644 index 0000000000..a5748c3bf1 --- /dev/null +++ b/pyhealth/models/survival_dcm.py @@ -0,0 +1,623 @@ +"""Authors: Murphy Crosby + +Deep Cox Mixtures survival model. +Paper: Deep Cox Mixtures for Survival Regression, Nagpal et al., MLHC 2021. +https://proceedings.mlr.press/v149/nagpal21a.html +""" + +import numpy as np +import torch +from scipy.interpolate import UnivariateSpline +from torch import Tensor, nn +from torch.utils.data import DataLoader + +from pyhealth.datasets import SampleDataset +from pyhealth.processors import LabelProcessor + +from .base_model import BaseModel + + +def cox_partial_log_likelihood( + log_hazard_ratio: Tensor, duration: Tensor, event: Tensor +) -> Tensor: + """Cox partial log-likelihood of one group of patients. + + For each patient with an observed event, this compares that patient's + hazard with the total hazard of everyone who was still at risk at that + time. Censored patients add no term of their own, but they do count as + at risk until their follow-up ends. + + Args: + log_hazard_ratio: Log hazard ratios, shape ``[n]``. + duration: Follow-up times, shape ``[n]``. + event: 1 for an observed event and 0 for censoring, shape ``[n]``. + + Returns: + The partial log-likelihood summed over observed events, a scalar. It + is 0 when the group has no observed events. + + Examples: + >>> import torch + >>> log_hazard_ratio = torch.log(torch.tensor([1.0, 2.0, 3.0])) + >>> duration = torch.tensor([3.0, 2.0, 1.0]) + >>> event = torch.ones(3) + >>> value = cox_partial_log_likelihood(log_hazard_ratio, duration, event) + >>> round(value.item(), 4) + -1.0986 + """ + total = log_hazard_ratio.new_zeros(()) + for i in range(len(duration)): + if event[i] == 0: + continue + + # A patient is still at risk at time duration[i] if their own + # follow-up lasted at least that long. Patients tied at the same + # time are all included. + still_at_risk = duration >= duration[i] + + # log of the summed hazard ratios of the at-risk patients. logsumexp + # does this without leaving log space, which avoids overflow. + log_total_risk = torch.logsumexp(log_hazard_ratio[still_at_risk], dim=0) + + total = total + log_hazard_ratio[i] - log_total_risk + return total + + +@torch.no_grad() +def breslow_baseline_survival( + log_hazard_ratio: Tensor, duration: Tensor, event: Tensor +) -> tuple[Tensor, Tensor]: + """Breslow estimate of the baseline survival curve of one group. + + The baseline curve is the survival of a patient whose hazard ratio is 1. + It is a step function that drops at each time an event was observed. The + size of each drop is the number of events at that time divided by the + total hazard of the patients still at risk. + + Args: + log_hazard_ratio: Log hazard ratios, shape ``[n]``. + duration: Follow-up times, shape ``[n]``. + event: 1 for an observed event and 0 for censoring, shape ``[n]``. + + Returns: + The distinct event times in increasing order, and the baseline + survival probability just after each of them. Both have shape + ``[m]``, where ``m`` is the number of distinct event times. Both are + empty if the group has no observed events. + + Examples: + >>> import torch + >>> times, survival = breslow_baseline_survival( + ... torch.zeros(4), + ... torch.tensor([1.0, 2.0, 3.0, 4.0]), + ... torch.tensor([1.0, 1.0, 0.0, 1.0]), + ... ) + >>> times.tolist() + [1.0, 2.0, 4.0] + >>> [round(value, 3) for value in survival.tolist()] + [0.779, 0.558, 0.205] + """ + hazard_ratio = torch.exp(log_hazard_ratio) + event_times = torch.unique(duration[event == 1]) # sorted, no repeats + + cumulative_hazard = 0.0 + survival = [] + for time in event_times: + deaths_now = ((duration == time) & (event == 1)).sum() + + # Everyone whose follow-up lasted at least this long is at risk. + total_risk = hazard_ratio[duration >= time].sum() + + cumulative_hazard = cumulative_hazard + deaths_now / total_risk + survival.append(torch.exp(-cumulative_hazard)) + + if not survival: + return event_times, hazard_ratio.new_zeros(0) + return event_times, torch.stack(survival) + + +def smooth_baseline_survival( + event_times: Tensor, survival: Tensor, grid: Tensor, smoothing: float = 1e-4 +) -> tuple[Tensor, Tensor]: + """Smooth a Breslow step curve and tabulate it on a time grid. + + The Breslow estimate is a staircase, so it has no usable slope. A cubic + smoothing spline through its points gives a curve whose slope tells how + fast survival is falling at any time, which the E-step needs. + + Args: + event_times: Distinct event times in increasing order, shape ``[m]``. + survival: Baseline survival after each event time, shape ``[m]``. + grid: Increasing times at which to tabulate the curve, shape ``[g]``. + smoothing: Smoothing factor of the spline. 0 passes through every + point; larger values give a smoother curve. + + Returns: + The smoothed survival and its slope (change in survival per unit + time, never positive) at each grid time. Both have shape ``[g]``. A + group with no events gets a flat curve at 1 with slope 0. + + Examples: + >>> import torch + >>> event_times = torch.tensor([10.0, 20.0, 30.0, 40.0]) + >>> survival = torch.tensor([0.9, 0.7, 0.5, 0.4]) + >>> grid = torch.linspace(0.0, 40.0, 5) + >>> smooth, slope = smooth_baseline_survival(event_times, survival, grid) + >>> smooth.shape, slope.shape + (torch.Size([5]), torch.Size([5])) + >>> bool((slope <= 0).all()) + True + """ + if len(event_times) == 0: + return torch.ones_like(grid), torch.zeros_like(grid) + + times = event_times.cpu().numpy().astype(float) + values = survival.cpu().numpy().astype(float) + grid_times = grid.cpu().numpy().astype(float) + + # Everyone is alive at time 0, so the curve starts at 1. + if times[0] > 0: + times = np.concatenate([[0.0], times]) + values = np.concatenate([[1.0], values]) + + # A cubic spline needs at least four points; use a lower degree if not. + degree = min(3, len(times) - 1) + if degree == 0: + smooth = np.full_like(grid_times, values[0]) + else: + spline = UnivariateSpline(times, values, k=degree, s=smoothing) + # Past the last event the data says nothing more, so hold the curve + # at its last value instead of letting the spline extrapolate. + smooth = spline(np.minimum(grid_times, times[-1])) + + # Keep it a valid survival curve: between 0 and 1, and never rising. + smooth = np.clip(smooth, 1e-6, 1.0) + smooth = np.minimum.accumulate(smooth) + + slope = np.gradient(smooth, grid_times) + return ( + torch.as_tensor(smooth, dtype=grid.dtype, device=grid.device), + torch.as_tensor(slope, dtype=grid.dtype, device=grid.device), + ) + + +class SurvivalDCM(BaseModel): + """Deep Cox Mixtures for right-censored survival data. + + A shared multilayer perceptron maps each patient's features to a latent + representation. Two linear heads read that representation: a gate that + gives the log-probability of belonging to each of ``num_components`` + latent subgroups, and an expert that gives one log hazard ratio per + subgroup. Each subgroup is a Cox model with its own baseline survival + function, so proportional hazards only has to hold within a subgroup. + + Training follows the approximate EM procedure of the paper. Call + :meth:`fit_baselines` once before training and again after every epoch, + from your own training loop. PyHealth's ``Trainer.train`` does not refit + the baseline curves between epochs, so on its own it would train against + curves that never change. ``Trainer.inference`` and ``Trainer.evaluate`` + work on a fitted model. + + Note: + This implementation differs from the authors' in a few ways. The + baseline curves are refitted once per epoch, not every few batches. + They are smoothed with a cubic spline, as the paper describes, where + the authors' released PyTorch code uses a linear one. The optional + variational auto-encoder term of the paper is not included. The log + hazard ratio is bounded with a scaled tanh, and the default bound of + 1 matches the authors' default. + + Args: + dataset: Fitted PyHealth ``SampleDataset`` with one dense feature + vector and two tensor outputs, duration and event. + feature_key: Input field holding the feature vector. + duration_key: Output field holding positive follow-up times. + event_key: Output field holding 1 for an observed event and 0 for + right censoring. + hidden_dim: Width of each hidden layer of the encoder. + num_hidden_layers: Number of hidden layers in the encoder. With 0 + the hazard ratios are a linear function of the features. + num_components: Number of latent subgroups, K. With 1, the model is + a single deep Cox model. + num_grid_points: Number of evenly spaced times at which each + subgroup's baseline survival curve is stored. + max_log_hazard_ratio: Largest absolute log hazard ratio the expert + can output. A patient's hazard within a subgroup is then between + ``exp(-max)`` and ``exp(max)`` times the baseline. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset + >>> samples = [ + ... { + ... "patient_id": "p0", + ... "features": [0.0, 1.0, -0.5], + ... "duration": [12.0], + ... "event": [1.0], + ... }, + ... { + ... "patient_id": "p1", + ... "features": [1.0, 0.2, 0.4], + ... "duration": [30.0], + ... "event": [0.0], + ... }, + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"features": "tensor"}, + ... output_schema={"duration": "tensor", "event": "tensor"}, + ... ) + >>> model = SurvivalDCM(dataset, hidden_dim=8, num_components=3) + >>> model.input_dim, model.num_components + (3, 3) + """ + + def __init__( + self, + dataset: SampleDataset, + feature_key: str = "features", + duration_key: str = "duration", + event_key: str = "event", + hidden_dim: int = 100, + num_hidden_layers: int = 2, + num_components: int = 3, + num_grid_points: int = 2049, + max_log_hazard_ratio: float = 1.0, + ) -> None: + super().__init__(dataset) + if feature_key not in dataset.input_schema: + raise ValueError(f"feature_key {feature_key!r} is not an input field") + for key in (duration_key, event_key): + if key not in dataset.output_schema: + raise ValueError(f"{key!r} is not an output field") + if max_log_hazard_ratio <= 0: + raise ValueError("max_log_hazard_ratio must be positive") + if num_grid_points < 2: + raise ValueError("num_grid_points must be at least 2") + if hidden_dim < 1 or num_hidden_layers < 0 or num_components < 1: + raise ValueError( + "hidden_dim and num_components must be positive, and " + "num_hidden_layers must not be negative" + ) + self.feature_key = feature_key + self.duration_key = duration_key + self.event_key = event_key + self.num_components = num_components + self.max_log_hazard_ratio = max_log_hazard_ratio + self.input_dim = dataset.input_processors[feature_key].size() + + layers: list[nn.Module] = [] + width = self.input_dim + for _ in range(num_hidden_layers): + layers += [nn.Linear(width, hidden_dim), nn.ReLU()] + width = hidden_dim + self.encoder = nn.Sequential(*layers) + # With no hidden layers the heads read the features directly. + self.gate = nn.Linear(width, num_components) + self.expert = nn.Linear(width, num_components, bias=False) + self.tanh = nn.Tanh() + self.log_softmax = nn.LogSoftmax(dim=1) + + # Each subgroup's baseline survival curve is stored as a table: its + # value and slope at evenly spaced times. Buffers are saved with the + # model but are not trained by the optimizer. Until the curves are + # fitted, the grid runs from 0 to 1 and every curve is flat at 1. + self.register_buffer("baseline_grid", torch.linspace(0.0, 1.0, num_grid_points)) + self.register_buffer( + "baseline_survival", torch.ones(num_components, num_grid_points) + ) + self.register_buffer( + "baseline_slope", torch.zeros(num_components, num_grid_points) + ) + # Turns True the first time fit_baselines() runs. + self.register_buffer("baselines_fitted", torch.tensor(False)) + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """Empty: duration and event are scored by the model's own loss.""" + return {} + + def baseline_at(self, time: Tensor) -> tuple[Tensor, Tensor]: + """Look up every subgroup's baseline curve at the given times. + + The curves are stored on a grid, so a time between two grid points is + read off by linear interpolation. Times beyond the grid use its last + point. + + Args: + time: Times, shape ``[n]``. + + Returns: + The baseline survival and its slope for each time and subgroup. + Both have shape ``[n, num_components]``. + """ + last = len(self.baseline_grid) - 1 + step = self.baseline_grid[1] - self.baseline_grid[0] + + # Where each time falls on the grid, as a number of steps from 0. + position = (time / step).clamp(min=0, max=last) + left = position.floor().long().clamp(max=last - 1) + fraction = position - left # 0 at the left grid point, 1 at the right + + survival = self.baseline_survival[:, left] + fraction * ( + self.baseline_survival[:, left + 1] - self.baseline_survival[:, left] + ) + slope = self.baseline_slope[:, left] + fraction * ( + self.baseline_slope[:, left + 1] - self.baseline_slope[:, left] + ) + # Stored as [num_components, n]; return as [n, num_components]. + return survival.T, slope.T + + @torch.no_grad() + def subgroup_posterior( + self, + log_gate: Tensor, + log_hazard_ratio: Tensor, + duration: Tensor, + event: Tensor, + ) -> Tensor: + """E-step: how likely each subgroup is, given what happened to a patient. + + For every subgroup this asks how well it explains the patient's + outcome: dying at the observed time if the event was seen, or + surviving past it if the patient was censored. That is combined with + the gate's belief from the features alone and normalized so the + probabilities of the subgroups sum to 1. + + Args: + log_gate: Log-probability of each subgroup from the gate, shape + ``[n, num_components]``. + log_hazard_ratio: Log hazard ratio under each subgroup, same shape. + duration: Follow-up times, shape ``[n]``. + event: 1 for an observed event and 0 for censoring, shape ``[n]``. + + Returns: + Posterior probability of each subgroup, shape + ``[n, num_components]``. Each row sums to 1. + """ + baseline_survival, baseline_slope = self.baseline_at(duration) + + # Surviving past the observed time in a subgroup: the baseline + # survival raised to the power of the patient's hazard ratio. + log_survival = torch.exp(log_hazard_ratio) * torch.log(baseline_survival) + + # Hazard at the observed time: how fast the baseline curve is falling + # relative to its height, scaled by the patient's hazard ratio. The + # small floor keeps the log finite where a curve is flat. + baseline_hazard = (-baseline_slope / baseline_survival).clamp(min=1e-8) + log_hazard = torch.log(baseline_hazard) + log_hazard_ratio + + # A censored patient only tells us they survived this long. A patient + # with an event also tells us the event happened right then. + log_likelihood = log_survival + event.unsqueeze(1) * log_hazard + + return torch.softmax(log_gate + log_likelihood, dim=1) + + @torch.no_grad() + def sample_subgroup(self, posterior: Tensor) -> Tensor: + """Draw one subgroup per patient at random from the posterior. + + Args: + posterior: Posterior probabilities, shape ``[n, num_components]``. + + Returns: + The index of the sampled subgroup for each patient, shape ``[n]``. + """ + return torch.multinomial(posterior, num_samples=1).squeeze(1) + + @torch.no_grad() + def fit_baselines(self, dataloader: DataLoader, smoothing: float = 1e-4) -> None: + """Refit every subgroup's baseline survival curve from training data. + + Call this once before training and again after every epoch. Each + patient is assigned to a subgroup, then each subgroup's curve is + estimated from its own patients with the Breslow estimator and + smoothed with a cubic spline. No gradients are involved. + + The first call has no curves to compute posteriors with, so it + assigns patients to subgroups uniformly at random. Later calls sample + each patient's subgroup from the posterior of the E-step. + + Args: + dataloader: Training data. Shuffling does not matter. + smoothing: Smoothing factor of the splines. + """ + was_training = self.training + self.eval() + + # Run the whole training set through the network. + log_gates, log_hazard_ratios, durations, events = [], [], [], [] + for batch in dataloader: + output = self(**{self.feature_key: batch[self.feature_key]}) + log_gates.append(output["log_gate"]) + log_hazard_ratios.append(output["log_hazard_ratio"]) + duration = batch[self.duration_key].to(self.device).float() + event = batch[self.event_key].to(self.device).float() + durations.append(duration.reshape(-1)) + events.append(event.reshape(-1)) + log_gate = torch.cat(log_gates) + log_hazard_ratio = torch.cat(log_hazard_ratios) + duration = torch.cat(durations) + event = torch.cat(events) + + # Assign every patient to one subgroup. + if self.baselines_fitted: + posterior = self.subgroup_posterior( + log_gate, log_hazard_ratio, duration, event + ) + assigned = self.sample_subgroup(posterior) + else: + assigned = torch.randint( + self.num_components, duration.shape, device=self.device + ) + + # The curves are stored from time 0 to the longest follow-up seen. + grid = torch.linspace( + 0.0, float(duration.max()), len(self.baseline_grid), device=self.device + ) + + for k in range(self.num_components): + members = assigned == k + event_times, survival = breslow_baseline_survival( + log_hazard_ratio[members, k], duration[members], event[members] + ) + smooth, slope = smooth_baseline_survival( + event_times, survival, grid, smoothing + ) + self.baseline_survival[k] = smooth + self.baseline_slope[k] = slope + + self.baseline_grid.copy_(grid) + self.baselines_fitted.fill_(True) + self.train(was_training) + + @torch.no_grad() + def _mixture_survival( + self, log_gate: Tensor, log_hazard_ratio: Tensor, times: Tensor + ) -> Tensor: + """Survival probability of each patient at each time. + + Within a subgroup, a patient's survival is the baseline survival + raised to the power of their hazard ratio. The subgroup is unknown at + prediction time, so the subgroups are averaged with the gate's + probabilities as weights. + + Args: + log_gate: Log-probability of each subgroup, shape + ``[n, num_components]``. + log_hazard_ratio: Log hazard ratio under each subgroup, same shape. + times: Times at which to predict, shape ``[num_times]``. + + Returns: + Survival probabilities, shape ``[n, num_times]``. + """ + baseline, _ = self.baseline_at(times) # [num_times, num_components] + hazard_ratio = torch.exp(log_hazard_ratio) # [n, num_components] + + # Survival within each subgroup: [n, num_times, num_components]. + within_subgroup = baseline.unsqueeze(0) ** hazard_ratio.unsqueeze(1) + + # Weighted average over the subgroups: [n, num_times]. + gate = torch.exp(log_gate).unsqueeze(1) + return (gate * within_subgroup).sum(dim=2) + + def predict_survival(self, features: Tensor, times: Tensor) -> Tensor: + """Predict each patient's survival probability at the given times. + + Args: + features: Feature vectors, shape ``[n, input_dim]``. + times: Times at which to predict, shape ``[num_times]``. + + Returns: + Survival probabilities, shape ``[n, num_times]``. Entry ``[i, j]`` + is the probability that patient ``i`` survives past ``times[j]``. + + Raises: + RuntimeError: If the baseline curves have not been fitted. + """ + if not self.baselines_fitted: + raise RuntimeError("Call fit_baselines() before predicting survival") + output = self(**{self.feature_key: features}) + times = times.to(device=self.device, dtype=torch.float32) + return self._mixture_survival( + output["log_gate"], output["log_hazard_ratio"], times + ) + + def forward(self, **kwargs: Tensor | tuple[Tensor, ...]) -> dict[str, Tensor]: + """Score a batch under every subgroup and compute the training loss. + + The loss is one step of the approximate EM procedure of the paper. + The E-step gives each patient a posterior over subgroups, and one + subgroup is drawn from it. The loss then has two parts: the gate is + trained to predict the posterior from the features alone, and each + subgroup's hazard ratios are trained with the Cox partial likelihood + of the patients assigned to it. + + Args: + **kwargs: Batch fields from the PyHealth dataloader. Must include + ``feature_key``. The loss is computed when ``duration_key`` + and ``event_key`` are also present. + + Returns: + ``log_gate``: log-probability of each subgroup, shape + ``[batch, num_components]``. ``log_hazard_ratio``: log hazard + ratio under each subgroup, same shape. ``loss``: the training + loss averaged over the batch, when the labels are present. + + In evaluation mode with labels, also ``y_true``: duration and + event side by side, shape ``[batch, 2]``, and ``y_prob``: the + predicted survival curve at every time in ``baseline_grid``, + shape ``[batch, num_grid_points]``. Column ``j`` of ``y_prob`` + is the survival at ``baseline_grid[j]``. ``fit_baselines`` resets + that grid, so read it from the same fitted model that produced + ``y_prob``. To predict at chosen times, use + :meth:`predict_survival`. + + Raises: + ValueError: If the features have the wrong shape or are not finite. + RuntimeError: If called in training mode before the baseline + curves have been fitted. + """ + features = kwargs[self.feature_key] + if isinstance(features, tuple): + features = features[0] + features = features.to(device=self.device, dtype=torch.float32) + if features.ndim != 2 or features.shape[1] != self.input_dim: + raise ValueError( + f"features must have shape [batch, {self.input_dim}]; " + f"got {tuple(features.shape)}" + ) + if not torch.isfinite(features).all(): + raise ValueError( + "features must be finite; standardize them so that missing " + "values are imputed before training" + ) + if self.training and not self.baselines_fitted: + raise RuntimeError("Call fit_baselines() before training") + hidden = self.encoder(features) + log_gate = self.log_softmax(self.gate(hidden)) + # Keep every log hazard ratio between -max and +max. Tanh squashes + # any number into (-1, 1), and the multiplier sets the range. + log_hazard_ratio = self.max_log_hazard_ratio * self.tanh(self.expert(hidden)) + output = {"log_gate": log_gate, "log_hazard_ratio": log_hazard_ratio} + + if self.duration_key not in kwargs or self.event_key not in kwargs: + return output + + # The dataloader gives the labels as [batch, 1]; flatten to [batch]. + duration = kwargs[self.duration_key].to(self.device).float().reshape(-1) + event = kwargs[self.event_key].to(self.device).float().reshape(-1) + + # E-step: posterior over subgroups, then one subgroup per patient. + # While training the subgroup is sampled, as in the paper. When + # evaluating, the most likely subgroup is used so the loss is not + # random. + posterior = self.subgroup_posterior(log_gate, log_hazard_ratio, duration, event) + if self.training: + assigned = self.sample_subgroup(posterior) + else: + assigned = posterior.argmax(dim=1) + + # First part: the gate should predict the posterior. + gate_term = (posterior * log_gate).sum() + + # Second part: one Cox partial likelihood per subgroup, each over the + # patients assigned to that subgroup. + cox_term = log_gate.new_zeros(()) + for k in range(self.num_components): + members = assigned == k + cox_term = cox_term + cox_partial_log_likelihood( + log_hazard_ratio[members, k], duration[members], event[members] + ) + + # Both parts are log-likelihoods to maximize, so the loss is their + # negative, averaged over the batch. + output["loss"] = -(gate_term + cox_term) / len(duration) + + # When evaluating, also return what PyHealth's Trainer collects: the + # labels, and each patient's survival curve at the stored grid times. + if not self.training: + output["y_true"] = torch.stack([duration, event], dim=1) + output["y_prob"] = self._mixture_survival( + log_gate, log_hazard_ratio, self.baseline_grid + ) + return output diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 1e8fbc5a34..9121f7c503 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -165,6 +165,7 @@ from .survival_time_to_event import ( SurvivalTimeToEventSupport2 as SurvivalTimeToEventSupport2, ) +from .survival_dcm_support2 import SurvivalDCMSupport2 as SurvivalDCMSupport2 from .mortality_prediction_stagenet_mimic4 import ( MortalityPredictionStageNetMIMIC4, ) diff --git a/pyhealth/tasks/survival_dcm_support2.py b/pyhealth/tasks/survival_dcm_support2.py new file mode 100644 index 0000000000..68b7ef504c --- /dev/null +++ b/pyhealth/tasks/survival_dcm_support2.py @@ -0,0 +1,243 @@ +"""Authors: Murphy Crosby + +Time-to-event task for SUPPORT2 in the representation used by Deep Cox Mixtures. +Paper: Deep Cox Mixtures for Survival Regression, Nagpal et al., MLHC 2021. +https://proceedings.mlr.press/v149/nagpal21a.html +""" + +import math +from collections.abc import Mapping, Sequence +from typing import ClassVar + +import numpy as np + +from pyhealth.data import Patient + +from .base_task import BaseTask + +# SUPPORT2 in the representation used by Deep Cox Mixtures (Nagpal et al., 2021): +# all 9,105 patients, 18 numeric covariates and 6 one-hot coded categorical. +DCM_SUPPORT2_NUMERIC = ( + "age", + "num.co", + "meanbp", + "wblc", + "hrt", + "resp", + "temp", + "pafi", + "alb", + "bili", + "crea", + "sod", + "ph", + "glucose", + "bun", + "urine", + "adlp", + "adls", +) + +# Every level gets its own column (no reference level is dropped). A missing +# value sets all of that covariate's columns to 0. +DCM_SUPPORT2_CATEGORIES = ( + ("sex", ("female", "male")), + ( + "dzgroup", + ( + "ARF/MOSF w/Sepsis", + "CHF", + "COPD", + "Cirrhosis", + "Colon Cancer", + "Coma", + "Lung Cancer", + "MOSF w/Malig", + ), + ), + ("dzclass", ("ARF/MOSF", "COPD/CHF/Cirrhosis", "Cancer", "Coma")), + ("income", ("$11-$25k", "$25-$50k", ">$50k", "under $11k")), + ("race", ("asian", "black", "hispanic", "other", "white")), + ("ca", ("metastatic", "no", "yes")), +) + +# Feature names in output order: 18 numeric, then 26 one-hot columns. +DCM_SUPPORT2_FEATURES = DCM_SUPPORT2_NUMERIC + tuple( + f"{name}={level}" for name, levels in DCM_SUPPORT2_CATEGORIES for level in levels +) + +_MISSING_TOKENS = frozenset({"", "nan", "na"}) + + +def _is_missing(value: object) -> bool: + """Whether a raw SUPPORT2 field holds no value.""" + if value is None: + return True + if isinstance(value, float): + return math.isnan(value) + return str(value).strip().lower() in _MISSING_TOKENS + + +def _dcm_support2_values( + record: Mapping[str, object], source_id: str +) -> tuple[list[float], float, float]: + """Encode one SUPPORT2 record as 44 raw features and its labels. + + Args: + record: Column name to raw value for one patient. + source_id: Patient identifier, used in error messages. + + Returns: + The 44 features in the order of ``DCM_SUPPORT2_FEATURES`` (NaN for a + missing numeric, all zeros for a missing categorical), the follow-up + time in days, and the event indicator (1 death, 0 censored). + + Raises: + ValueError: If a value is malformed or a label is missing. + """ + features: list[float] = [] + for name in DCM_SUPPORT2_NUMERIC: + raw = record.get(name) + if _is_missing(raw): + features.append(math.nan) + continue + try: + value = float(raw) + except (TypeError, ValueError) as exc: + raise ValueError( + f"SUPPORT2 record {source_id}: non-numeric {name} {raw!r}" + ) from exc + if not math.isfinite(value): + raise ValueError(f"SUPPORT2 record {source_id}: {name} must be finite") + features.append(value) + + for name, levels in DCM_SUPPORT2_CATEGORIES: + raw = record.get(name) + level = None if _is_missing(raw) else str(raw).strip() + if level is not None and level not in levels: + raise ValueError(f"SUPPORT2 record {source_id}: unknown {name} {raw!r}") + features.extend(1.0 if level == candidate else 0.0 for candidate in levels) + + labels = [] + for name in ("d.time", "death"): + raw = record.get(name) + try: + labels.append(float(raw)) + except (TypeError, ValueError) as exc: + raise ValueError( + f"SUPPORT2 record {source_id}: missing or non-numeric {name}" + ) from exc + time, event = labels + if not math.isfinite(time) or time <= 0: + raise ValueError(f"SUPPORT2 record {source_id}: d.time must be positive") + if event not in (0.0, 1.0): + raise ValueError(f"SUPPORT2 record {source_id}: death must be 0 or 1") + return features, time, event + + +class SurvivalDCMSupport2(BaseTask): + """Time to death for SUPPORT2, in the Deep Cox Mixtures representation. + + Use with :class:`~pyhealth.datasets.Support2Dataset`. Following Nagpal et + al. (2021), this keeps all 9,105 patients and encodes 18 numeric covariates + and 6 one-hot coded categoricals as ``features: [44]``, in the order of + ``DCM_SUPPORT2_FEATURES``. Labels are ``duration: [days]`` and + ``event: [indicator]``, with event 1 for death and 0 for censoring. + + This differs from :class:`~pyhealth.tasks.SurvivalTimeToEventSupport2`, + which uses the DeepSurv benchmark representation (8,873 complete cases, + 27 features). + + Without ``feature_mean`` and ``feature_scale`` the features are raw, and a + missing numeric is NaN. Raw output is only for fitting the statistics; do + not train on it. With both supplied, every feature is standardized and a + missing numeric becomes 0, which is mean imputation. + + To match the paper's preprocessing, fit the statistics on raw features: + ``feature_mean`` is each column's mean over observed values, and + ``feature_scale`` is each column's standard deviation (population + standard deviation, ``ddof=0``, as in sklearn's ``StandardScaler``) after + its missing values are replaced by that mean. This is smaller than the + standard deviation of the observed values alone for columns with many + missing values. + + Note: + The original authors fit the imputer and scaler on all patients before + cross-validation. Fit the statistics on training patients only to keep + test-fold information out of training. This is a deliberate departure + from the released code. + + Args: + feature_mean: Optional 44 means fitted on training patients only. + feature_scale: Matching 44 positive standard deviations. Supply both + arguments or neither. Use a scale of 1 for a constant feature. + + Examples: + >>> from pyhealth.tasks import SurvivalDCMSupport2 + >>> task = SurvivalDCMSupport2() + >>> task.output_schema + {'duration': 'tensor', 'event': 'tensor'} + >>> from pyhealth.tasks.survival_dcm_support2 import DCM_SUPPORT2_FEATURES + >>> len(DCM_SUPPORT2_FEATURES), DCM_SUPPORT2_FEATURES[18] + (44, 'sex=female') + """ + + task_name = "SurvivalDCMSupport2" + input_schema: ClassVar[dict[str, str]] = {"features": "tensor"} + output_schema: ClassVar[dict[str, str]] = {"duration": "tensor", "event": "tensor"} + + def __init__( + self, + feature_mean: Sequence[float] | None = None, + feature_scale: Sequence[float] | None = None, + ) -> None: + super().__init__() + if (feature_mean is None) != (feature_scale is None): + raise ValueError("Supply both feature_mean and feature_scale, or neither") + self.feature_mean: list[float] | None = None + self.feature_scale: list[float] | None = None + if feature_mean is not None: + mean = np.asarray(feature_mean, dtype=float) + scale = np.asarray(feature_scale, dtype=float) + n = len(DCM_SUPPORT2_FEATURES) + if mean.shape != (n,) or scale.shape != (n,): + raise ValueError(f"Expected {n} means and {n} scales") + if not np.isfinite(mean).all() or not np.isfinite(scale).all(): + raise ValueError("feature_mean and feature_scale must be finite") + if (scale <= 0).any(): + raise ValueError("feature_scale must be positive") + self.feature_mean, self.feature_scale = mean.tolist(), scale.tolist() + + def __call__(self, patient: Patient) -> list[dict]: + """Return one sample for the patient. + + Args: + patient: Patient with exactly one ``support2`` event. + + Returns: + One sample with ``patient_id``, ``features``, ``duration`` and + ``event``. + + Raises: + ValueError: For invalid values or not exactly one record. + """ + events = patient.get_events("support2") + if len(events) != 1: + raise ValueError( + f"SUPPORT2 record {patient.patient_id}: expected exactly one " + f"support2 event, got {len(events)}" + ) + features, time, event = _dcm_support2_values( + events[0].attr_dict, patient.patient_id + ) + if self.feature_mean is not None: + values = (np.asarray(features) - self.feature_mean) / self.feature_scale + features = np.where(np.isnan(values), 0.0, values).tolist() + return [ + { + "patient_id": patient.patient_id, + "features": features, + "duration": [time], + "event": [event], + } + ] diff --git a/tests/core/test_survival_dcm.py b/tests/core/test_survival_dcm.py new file mode 100644 index 0000000000..a817f79bda --- /dev/null +++ b/tests/core/test_survival_dcm.py @@ -0,0 +1,438 @@ +# Authors: Murphy Crosby +# Deep Cox Mixtures for Survival Regression, Nagpal et al., MLHC 2021. +# https://proceedings.mlr.press/v149/nagpal21a.html +"""Deep Cox Mixtures survival model and its building blocks.""" + +import io +import math +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import SurvivalDCM +from pyhealth.models.survival_dcm import ( + breslow_baseline_survival, + cox_partial_log_likelihood, + smooth_baseline_survival, +) + +NUM_PATIENTS = 24 +NUM_FEATURES = 4 + + +def make_dataset(): + """A small made-up survival dataset with tied times and censoring.""" + samples = [] + for i in range(NUM_PATIENTS): + samples.append( + { + "patient_id": f"p{i}", + "features": [math.sin(i), math.cos(2 * i), (i % 5) / 5, (-1.0) ** i], + "duration": [5.0 + (i * 7) % 23], + "event": [0.0 if i % 3 == 0 else 1.0], + } + ) + return create_sample_dataset( + samples=samples, + input_schema={"features": "tensor"}, + output_schema={"duration": "tensor", "event": "tensor"}, + dataset_name="test", + ) + + +class TestCoxPartialLogLikelihood(unittest.TestCase): + def setUp(self): + # Hazard ratios 1, 2 and 3; the highest-risk patient dies first. + self.log_hazard_ratio = torch.log(torch.tensor([1.0, 2.0, 3.0])) + self.duration = torch.tensor([3.0, 2.0, 1.0]) + + def test_hand_computed_value(self): + # (3/6) * (2/3) * (1/1) = 1/3 + value = cox_partial_log_likelihood( + self.log_hazard_ratio, self.duration, torch.ones(3) + ) + self.assertAlmostEqual(value.item(), -math.log(3), places=5) + + def test_censored_patient_adds_no_term(self): + # Without the first death's term: (2/3) * (1/1) + event = torch.tensor([1.0, 1.0, 0.0]) + value = cox_partial_log_likelihood(self.log_hazard_ratio, self.duration, event) + self.assertAlmostEqual(value.item(), math.log(2) - math.log(3), places=5) + + def test_no_events_gives_zero(self): + value = cox_partial_log_likelihood( + self.log_hazard_ratio, self.duration, torch.zeros(3) + ) + self.assertEqual(value.item(), 0.0) + + def test_tied_times_share_a_risk_set(self): + # Two deaths at the same time, hazard ratios 1 and 1, among three + # patients with total hazard 3: each contributes log(1/3). + value = cox_partial_log_likelihood( + torch.zeros(3), torch.tensor([2.0, 2.0, 5.0]), torch.tensor([1.0, 1.0, 0.0]) + ) + self.assertAlmostEqual(value.item(), 2 * math.log(1 / 3), places=5) + + def test_unchanged_by_a_constant_shift(self): + event = torch.ones(3) + original = cox_partial_log_likelihood( + self.log_hazard_ratio, self.duration, event + ) + shifted = cox_partial_log_likelihood( + self.log_hazard_ratio + 5.0, self.duration, event + ) + self.assertAlmostEqual(original.item(), shifted.item(), places=5) + + def test_gradient_is_finite(self): + log_hazard_ratio = self.log_hazard_ratio.clone().requires_grad_(True) + cox_partial_log_likelihood( + log_hazard_ratio, self.duration, torch.ones(3) + ).backward() + self.assertTrue(torch.isfinite(log_hazard_ratio.grad).all()) + + +class TestBreslowBaselineSurvival(unittest.TestCase): + def test_hand_computed_curve(self): + # Cumulative hazard grows by 1/6, then 1/3, then 1/1. + times, survival = breslow_baseline_survival( + torch.log(torch.tensor([1.0, 2.0, 3.0])), + torch.tensor([3.0, 2.0, 1.0]), + torch.ones(3), + ) + self.assertEqual(times.tolist(), [1.0, 2.0, 3.0]) + expected = torch.exp(-torch.tensor([1 / 6, 1 / 2, 3 / 2])) + self.assertTrue(torch.allclose(survival, expected)) + + def test_equal_hazards_with_censoring_and_ties(self): + # With every hazard ratio 1 this is the Nelson-Aalen estimator. + times, survival = breslow_baseline_survival( + torch.zeros(5), + torch.tensor([1.0, 2.0, 2.0, 3.0, 4.0]), + torch.tensor([1.0, 0.0, 1.0, 1.0, 0.0]), + ) + self.assertEqual(times.tolist(), [1.0, 2.0, 3.0]) + cumulative_hazard = -torch.log(survival) + self.assertTrue( + torch.allclose(cumulative_hazard, torch.tensor([0.2, 0.45, 0.95])) + ) + + def test_no_events_gives_empty_curve(self): + times, survival = breslow_baseline_survival( + torch.zeros(3), torch.tensor([1.0, 2.0, 3.0]), torch.zeros(3) + ) + self.assertEqual(len(times), 0) + self.assertEqual(len(survival), 0) + + def test_no_gradient_flows_through(self): + log_hazard_ratio = torch.zeros(3, requires_grad=True) + _, survival = breslow_baseline_survival( + log_hazard_ratio, torch.tensor([1.0, 2.0, 3.0]), torch.ones(3) + ) + self.assertFalse(survival.requires_grad) + + +class TestSmoothBaselineSurvival(unittest.TestCase): + def setUp(self): + self.grid = torch.linspace(0.0, 100.0, 201) + + def test_recovers_a_known_curve(self): + times = torch.arange(1.0, 81.0) + smooth, slope = smooth_baseline_survival( + times, torch.exp(-0.02 * times), self.grid + ) + inside = (self.grid >= 2) & (self.grid <= 78) + truth = torch.exp(-0.02 * self.grid) + self.assertLess((smooth - truth)[inside].abs().max().item(), 0.02) + self.assertLess((slope + 0.02 * truth)[inside].abs().max().item(), 0.005) + + def test_result_is_a_valid_survival_curve(self): + times = torch.tensor([3.0, 10.0, 11.0, 40.0, 41.0, 42.0, 90.0]) + survival = torch.tensor([0.9, 0.85, 0.6, 0.55, 0.5, 0.3, 0.1]) + smooth, slope = smooth_baseline_survival(times, survival, self.grid) + self.assertEqual(smooth.shape, self.grid.shape) + self.assertTrue(((smooth > 0) & (smooth <= 1)).all()) + self.assertTrue((smooth[1:] <= smooth[:-1]).all()) + self.assertTrue((slope <= 0).all()) + + def test_no_events_gives_a_flat_curve(self): + empty = torch.zeros(0) + smooth, slope = smooth_baseline_survival(empty, empty, self.grid) + self.assertTrue((smooth == 1).all()) + self.assertTrue((slope == 0).all()) + + def test_few_event_times(self): + for count in (1, 2, 3): + with self.subTest(count=count): + times = torch.arange(1.0, count + 1.0) + survival = torch.linspace(0.9, 0.7, count) + smooth, slope = smooth_baseline_survival(times, survival, self.grid) + self.assertTrue(torch.isfinite(smooth).all()) + self.assertTrue(torch.isfinite(slope).all()) + + +class TestSurvivalDCM(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = make_dataset() + loader = get_dataloader(cls.dataset, batch_size=NUM_PATIENTS, shuffle=False) + cls.batch = next(iter(loader)) + + def setUp(self): + torch.manual_seed(0) + self.loader = get_dataloader(self.dataset, batch_size=8, shuffle=False) + self.model = SurvivalDCM( + self.dataset, hidden_dim=8, num_components=3, num_grid_points=65 + ) + + def fitted_model(self, **kwargs): + """A model whose baseline curves have been fitted once.""" + settings = {"hidden_dim": 8, "num_components": 3, "num_grid_points": 65} + settings.update(kwargs) + model = SurvivalDCM(self.dataset, **settings) + model.fit_baselines(self.loader) + return model + + def test_initialization(self): + self.assertEqual(self.model.input_dim, NUM_FEATURES) + self.assertEqual(self.model.num_components, 3) + self.assertEqual(self.model.label_processors, {}) + self.assertIsNone(self.model.mode) + self.assertIsNone(self.model.expert.bias) + self.assertEqual(self.model.baseline_grid.shape, (65,)) + self.assertEqual(self.model.baseline_survival.shape, (3, 65)) + self.assertEqual(self.model.baseline_slope.shape, (3, 65)) + self.assertFalse(self.model.baselines_fitted) + + def test_invalid_arguments_raise(self): + bad_arguments = { + "unknown feature key": {"feature_key": "missing"}, + "unknown duration key": {"duration_key": "missing"}, + "unknown event key": {"event_key": "missing"}, + "no hidden units": {"hidden_dim": 0}, + "negative hidden layers": {"num_hidden_layers": -1}, + "no components": {"num_components": 0}, + "one grid point": {"num_grid_points": 1}, + "zero hazard bound": {"max_log_hazard_ratio": 0.0}, + } + for label, kwargs in bad_arguments.items(): + with self.subTest(label), self.assertRaises(ValueError): + SurvivalDCM(self.dataset, **kwargs) + + def test_no_hidden_layers_gives_a_linear_model(self): + model = SurvivalDCM(self.dataset, num_components=1, num_hidden_layers=0) + self.assertEqual(len(model.encoder), 0) + self.assertEqual(model.expert.in_features, NUM_FEATURES) + self.assertEqual(model.gate.in_features, NUM_FEATURES) + model.eval() + output = model(**self.batch) + self.assertEqual(output["log_hazard_ratio"].shape, (NUM_PATIENTS, 1)) + + def test_forward_output_shapes(self): + self.model.eval() + output = self.model(**self.batch) + self.assertEqual(output["log_gate"].shape, (NUM_PATIENTS, 3)) + self.assertEqual(output["log_hazard_ratio"].shape, (NUM_PATIENTS, 3)) + self.assertEqual(output["loss"].ndim, 0) + self.assertEqual(output["y_true"].shape, (NUM_PATIENTS, 2)) + self.assertEqual(output["y_prob"].shape, (NUM_PATIENTS, 65)) + + def test_gate_rows_are_probabilities(self): + self.model.eval() + gate = self.model(**self.batch)["log_gate"].exp() + self.assertTrue(torch.allclose(gate.sum(dim=1), torch.ones(NUM_PATIENTS))) + + def test_log_hazard_ratio_stays_within_bound(self): + model = SurvivalDCM(self.dataset, hidden_dim=8, max_log_hazard_ratio=0.5) + model.eval() + extreme = {"features": self.batch["features"] * 1000} + log_hazard_ratio = model(**extreme)["log_hazard_ratio"] + self.assertLessEqual(log_hazard_ratio.abs().max().item(), 0.5) + + def test_features_only_returns_no_loss(self): + self.model.eval() + output = self.model(features=self.batch["features"]) + self.assertEqual(sorted(output), ["log_gate", "log_hazard_ratio"]) + + def test_invalid_features_raise(self): + self.model.eval() + features = self.batch["features"] + not_finite = features.clone() + not_finite[0, 0] = float("nan") + bad_features = { + "nan value": not_finite, + "wrong width": features[:, :2], + "one dimension": features[0], + } + for label, bad in bad_features.items(): + with self.subTest(label), self.assertRaises(ValueError): + self.model(features=bad) + + def test_training_before_fitting_raises(self): + self.model.train() + with self.assertRaises(RuntimeError): + self.model(**self.batch) + + def test_fit_baselines(self): + self.model.train() + self.model.fit_baselines(self.loader) + self.assertTrue(self.model.baselines_fitted) + self.assertTrue(self.model.training) # the mode is put back + longest = self.batch["duration"].max().item() + self.assertAlmostEqual(self.model.baseline_grid[-1].item(), longest, places=4) + survival = self.model.baseline_survival + self.assertTrue(((survival > 0) & (survival <= 1)).all()) + self.assertTrue((survival[:, 1:] <= survival[:, :-1]).all()) + self.assertTrue((self.model.baseline_slope <= 0).all()) + + def test_loss_and_gradients(self): + model = self.fitted_model() + model.train() + output = model(**self.batch) + self.assertEqual(sorted(output), ["log_gate", "log_hazard_ratio", "loss"]) + self.assertTrue(torch.isfinite(output["loss"])) + output["loss"].backward() + for name, parameter in model.named_parameters(): + if name == "_dummy_param": + continue + with self.subTest(name): + self.assertIsNotNone(parameter.grad) + self.assertTrue(torch.isfinite(parameter.grad).all()) + self.assertGreater(parameter.grad.abs().sum().item(), 0.0) + + def test_one_component_loss_is_the_partial_likelihood(self): + model = self.fitted_model(num_components=1) + model.train() + output = model(**self.batch) + duration = self.batch["duration"].reshape(-1) + event = self.batch["event"].reshape(-1) + expected = -cox_partial_log_likelihood( + output["log_hazard_ratio"][:, 0], duration, event + ) / len(duration) + self.assertTrue(torch.allclose(output["loss"], expected)) + + def test_evaluation_loss_is_repeatable(self): + model = self.fitted_model() + model.eval() + first = model(**self.batch)["loss"].item() + second = model(**self.batch)["loss"].item() + self.assertEqual(first, second) + + def test_y_true_holds_duration_and_event(self): + model = self.fitted_model() + model.eval() + y_true = model(**self.batch)["y_true"] + self.assertTrue(torch.equal(y_true[:, 0], self.batch["duration"].reshape(-1))) + self.assertTrue(torch.equal(y_true[:, 1], self.batch["event"].reshape(-1))) + + def test_baseline_lookup_interpolates(self): + # Give every subgroup the straight line 1 - t / 200 on a 0..64 grid. + self.model.baseline_grid.copy_(torch.linspace(0.0, 64.0, 65)) + self.model.baseline_survival.copy_( + (1 - self.model.baseline_grid / 200).repeat(3, 1) + ) + self.model.baseline_slope.fill_(-1 / 200) + survival, slope = self.model.baseline_at(torch.tensor([0.0, 10.5, 64.0, 500.0])) + self.assertEqual(survival.shape, (4, 3)) + expected = torch.tensor([1.0, 1 - 10.5 / 200, 1 - 64 / 200, 1 - 64 / 200]) + self.assertTrue(torch.allclose(survival[:, 0], expected)) + self.assertTrue(torch.allclose(slope, torch.full((4, 3), -1 / 200))) + + def test_posterior_matches_hand_computation(self): + # Two subgroups with constant hazards 0.001 (slow) and 0.05 (fast). + model = SurvivalDCM( + self.dataset, hidden_dim=8, num_components=2, num_grid_points=4001 + ) + rate = torch.tensor([[0.001], [0.05]]) + model.baseline_grid.copy_(torch.linspace(0.0, 400.0, 4001)) + model.baseline_survival.copy_(torch.exp(-rate * model.baseline_grid)) + model.baseline_slope.copy_(-rate * torch.exp(-rate * model.baseline_grid)) + + even_gate = torch.full((2, 2), math.log(0.5)) + posterior = model.subgroup_posterior( + even_gate, + torch.zeros(2, 2), + torch.tensor([5.0, 300.0]), # one early, one late + torch.tensor([1.0, 0.0]), # the early one died; the late one did not + ) + self.assertTrue(torch.allclose(posterior.sum(dim=1), torch.ones(2))) + + # Early death: compare the two densities, rate * exp(-rate * 5). + slow = 0.001 * math.exp(-0.005) + fast = 0.05 * math.exp(-0.25) + self.assertAlmostEqual(posterior[0, 1].item(), fast / (slow + fast), places=3) + # Late censoring: surviving 300 is far likelier in the slow subgroup. + self.assertGreater(posterior[1, 0].item(), 0.999) + + def test_sample_subgroup(self): + certain = torch.tensor([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) + assigned = self.model.sample_subgroup(certain) + self.assertEqual(assigned.tolist(), [1, 0, 2]) + self.assertEqual(assigned.dtype, torch.int64) + + def test_predicting_before_fitting_raises(self): + with self.assertRaises(RuntimeError): + self.model.predict_survival(self.batch["features"], torch.tensor([10.0])) + + def test_predict_survival(self): + model = self.fitted_model() + model.eval() + times = torch.tensor([0.0, 8.0, 15.0, 27.0]) + survival = model.predict_survival(self.batch["features"], times) + self.assertEqual(survival.shape, (NUM_PATIENTS, 4)) + self.assertTrue(((survival >= 0) & (survival <= 1)).all()) + self.assertTrue((survival[:, 1:] <= survival[:, :-1] + 1e-6).all()) + # At time 0 nobody has died yet. The smoothed curves start very close + # to 1 but not exactly at it, so allow a small tolerance. + self.assertGreater(survival[:, 0].min().item(), 0.99) + + def test_one_component_prediction_is_baseline_to_the_hazard_ratio(self): + model = self.fitted_model(num_components=1) + model.eval() + times = torch.tensor([8.0, 15.0]) + features = self.batch["features"] + hazard_ratio = model(features=features)["log_hazard_ratio"].exp() + baseline, _ = model.baseline_at(times) + expected = baseline[:, 0].unsqueeze(0) ** hazard_ratio + self.assertTrue( + torch.allclose(model.predict_survival(features, times), expected) + ) + + def test_save_and_load(self): + model = self.fitted_model() + model.eval() + buffer = io.BytesIO() + torch.save(model.state_dict(), buffer) + buffer.seek(0) + + restored = SurvivalDCM( + self.dataset, hidden_dim=8, num_components=3, num_grid_points=65 + ) + restored.load_state_dict(torch.load(buffer)) + restored.eval() + self.assertTrue(restored.baselines_fitted) + times = torch.tensor([8.0, 15.0]) + features = self.batch["features"] + self.assertTrue( + torch.allclose( + restored.predict_survival(features, times), + model.predict_survival(features, times), + ) + ) + + def test_training_lowers_the_loss(self): + model = self.fitted_model(num_components=1) + optimizer = torch.optim.Adam(model.parameters(), lr=0.05) + model.train() + losses = [] + for _ in range(30): + optimizer.zero_grad() + loss = model(**self.batch)["loss"] + loss.backward() + optimizer.step() + losses.append(loss.item()) + self.assertLess(losses[-1], losses[0]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_survival_dcm_support2.py b/tests/core/test_survival_dcm_support2.py new file mode 100644 index 0000000000..6fe5c54774 --- /dev/null +++ b/tests/core/test_survival_dcm_support2.py @@ -0,0 +1,260 @@ +# Authors: Murphy Crosby +# Deep Cox Mixtures for Survival Regression, Nagpal et al., MLHC 2021. +# https://proceedings.mlr.press/v149/nagpal21a.html +"""SUPPORT2 time-to-event task in the Deep Cox Mixtures representation.""" + +import csv +import math +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import numpy as np +import polars as pl +import torch +import yaml +from distributed import LocalCluster + +import pyhealth.datasets +from pyhealth.data import Patient +from pyhealth.datasets import Support2Dataset +from pyhealth.tasks import SurvivalDCMSupport2 +from pyhealth.tasks.survival_dcm_support2 import ( + DCM_SUPPORT2_CATEGORIES, + DCM_SUPPORT2_FEATURES, + DCM_SUPPORT2_NUMERIC, +) + +N_NUMERIC = len(DCM_SUPPORT2_NUMERIC) +N_FEATURES = len(DCM_SUPPORT2_FEATURES) + + +def record(**overrides): + """One synthetic SUPPORT2 record, as the strings the dataset provides.""" + values = {name: str(10.0 + i) for i, name in enumerate(DCM_SUPPORT2_NUMERIC)} + values.update( + { + "sex": "female", + "dzgroup": "CHF", + "dzclass": "COPD/CHF/Cirrhosis", + "income": "under $11k", + "race": "white", + "ca": "no", + "d.time": "120", + "death": "1", + } + ) + values.update(overrides) + return values + + +def patient(*records, patient_id="1"): + """A Patient holding one ``support2`` event per record.""" + events = [ + { + "patient_id": patient_id, + "event_type": "support2", + "timestamp": None, + **{f"support2/{name}": value for name, value in r.items()}, + } + for r in records + ] + + schema = { + "patient_id": pl.String, + "event_type": pl.String, + "timestamp": pl.Datetime, + } + frame = pl.DataFrame(events) if events else pl.DataFrame(schema=schema) + return Patient(patient_id, frame) + + +def one_hot(sample, name): + """The one-hot columns of one categorical covariate.""" + levels = dict(DCM_SUPPORT2_CATEGORIES)[name] + start = DCM_SUPPORT2_FEATURES.index(f"{name}={levels[0]}") + return sample["features"][start : start + len(levels)] + + +class TestSurvivalDCMSupport2(unittest.TestCase): + def test_feature_names(self): + self.assertEqual(N_NUMERIC, 18) + self.assertEqual(N_FEATURES, 44) + self.assertEqual(DCM_SUPPORT2_FEATURES[:N_NUMERIC], DCM_SUPPORT2_NUMERIC) + self.assertEqual(DCM_SUPPORT2_FEATURES[N_NUMERIC], "sex=female") + self.assertEqual(len(set(DCM_SUPPORT2_FEATURES)), N_FEATURES) + + def test_schema(self): + task = SurvivalDCMSupport2() + self.assertEqual(task.task_name, "SurvivalDCMSupport2") + self.assertEqual(task.input_schema, {"features": "tensor"}) + self.assertEqual(task.output_schema, {"duration": "tensor", "event": "tensor"}) + + def test_raw_sample(self): + samples = SurvivalDCMSupport2()(patient(record(), patient_id="7")) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["patient_id"], "7") + self.assertEqual(len(sample["features"]), N_FEATURES) + self.assertEqual( + sample["features"][:N_NUMERIC], [10.0 + i for i in range(N_NUMERIC)] + ) + self.assertEqual(sample["duration"], [120.0]) + self.assertEqual(sample["event"], [1.0]) + + def test_one_hot_encoding(self): + sample = SurvivalDCMSupport2()(patient(record()))[0] + self.assertEqual(one_hot(sample, "sex"), [1.0, 0.0]) + self.assertEqual(one_hot(sample, "race"), [0.0, 0.0, 0.0, 0.0, 1.0]) + self.assertEqual(one_hot(sample, "ca"), [0.0, 1.0, 0.0]) + for name, levels in DCM_SUPPORT2_CATEGORIES: + self.assertEqual(sum(one_hot(sample, name)), 1.0, name) + self.assertEqual(len(one_hot(sample, name)), len(levels), name) + + def test_missing_numeric_is_nan_in_raw_mode(self): + for missing in ("NaN", "", None): + sample = SurvivalDCMSupport2()(patient(record(alb=missing)))[0] + index = DCM_SUPPORT2_FEATURES.index("alb") + self.assertTrue(math.isnan(sample["features"][index]), repr(missing)) + others = [v for i, v in enumerate(sample["features"]) if i != index] + self.assertFalse(any(math.isnan(v) for v in others)) + + def test_missing_categorical_is_all_zeros(self): + for missing in ("NaN", "", None): + sample = SurvivalDCMSupport2()( + patient(record(race=missing, income=missing)) + )[0] + self.assertEqual(one_hot(sample, "race"), [0.0] * 5, repr(missing)) + self.assertEqual(one_hot(sample, "income"), [0.0] * 4, repr(missing)) + self.assertEqual(one_hot(sample, "sex"), [1.0, 0.0]) + + def test_standardized_sample(self): + raw = SurvivalDCMSupport2()(patient(record()))[0]["features"] + mean = [float(i) for i in range(N_FEATURES)] + scale = [1.0 + 0.5 * i for i in range(N_FEATURES)] + task = SurvivalDCMSupport2(feature_mean=mean, feature_scale=scale) + sample = task(patient(record()))[0] + expected = (np.asarray(raw) - np.asarray(mean)) / np.asarray(scale) + np.testing.assert_allclose(sample["features"], expected) + self.assertEqual(sample["duration"], [120.0]) + + def test_missing_numeric_is_zero_when_standardized(self): + task = SurvivalDCMSupport2( + feature_mean=[5.0] * N_FEATURES, feature_scale=[2.0] * N_FEATURES + ) + sample = task(patient(record(alb="NaN", glucose=None)))[0] + self.assertEqual(sample["features"][DCM_SUPPORT2_FEATURES.index("alb")], 0.0) + self.assertEqual( + sample["features"][DCM_SUPPORT2_FEATURES.index("glucose")], 0.0 + ) + self.assertFalse(any(math.isnan(v) for v in sample["features"])) + + def test_censored_patient(self): + sample = SurvivalDCMSupport2()(patient(record(death="0")))[0] + self.assertEqual(sample["event"], [0.0]) + + def test_invalid_records_raise(self): + bad_records = { + "unknown category": record(race="martian"), + "non-numeric value": record(age="old"), + "infinite value": record(age="inf"), + "zero time": record(**{"d.time": "0"}), + "missing time": record(**{"d.time": "NaN"}), + "invalid event": record(death="2"), + "missing event": record(death=None), + } + for label, bad in bad_records.items(): + with self.subTest(label), self.assertRaises(ValueError): + SurvivalDCMSupport2()(patient(bad)) + + def test_requires_exactly_one_record(self): + for label, records in {"none": (), "two": (record(), record())}.items(): + with self.subTest(label), self.assertRaises(ValueError): + SurvivalDCMSupport2()(patient(*records)) + + def test_invalid_statistics_raise(self): + ok = [1.0] * N_FEATURES + bad_arguments = { + "mean only": {"feature_mean": ok}, + "scale only": {"feature_scale": ok}, + "wrong length": {"feature_mean": ok[:-1], "feature_scale": ok}, + "zero scale": {"feature_mean": ok, "feature_scale": [0.0] * N_FEATURES}, + "nan mean": {"feature_mean": [math.nan] * N_FEATURES, "feature_scale": ok}, + "negative scale": { + "feature_mean": ok, + "feature_scale": [-1.0] * N_FEATURES, + }, + "infinite scale": { + "feature_mean": ok, + "feature_scale": [math.inf] * N_FEATURES, + }, + } + for label, kwargs in bad_arguments.items(): + with self.subTest(label), self.assertRaises(ValueError): + SurvivalDCMSupport2(**kwargs) + + +class TestSurvivalDCMSupport2WithDataset(unittest.TestCase): + """One end-to-end check through ``Support2Dataset`` and ``set_task``. + + This loads a CSV, so it takes about half a second rather than milliseconds. + It guards the layer the in-memory tests cannot see: how the dataset names, + types and represents missing values before they reach the task. + """ + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + config = Path(pyhealth.datasets.__file__).parent / "configs" / "support2.yaml" + columns = ["sno"] + yaml.safe_load(config.read_text())["tables"]["support2"][ + "attributes" + ] + rows = [ + {"sno": "1", **record()}, + {"sno": "2", **record(alb="NaN", race="NaN", death="0")}, + {"sno": "3", **record(glucose="", income="", **{"d.time": "30"})}, + ] + with (self.root / "support2.csv").open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=columns, restval="") + writer.writeheader() + writer.writerows(rows) + + # Run the dataset's Dask workers as threads, so loading the CSV starts + # no child processes. Everything else in the loader runs unchanged. + def threaded_cluster(**kwargs): + kwargs["processes"] = False + return LocalCluster(**kwargs) + + patcher = patch("pyhealth.datasets.base_dataset.DaskCluster", threaded_cluster) + patcher.start() + self.addCleanup(patcher.stop) + + def test_dataset_to_samples(self): + dataset = Support2Dataset( + root=str(self.root), + tables=["support2"], + cache_dir=self.root / "cache", + num_workers=1, + ) + samples = dataset.set_task(SurvivalDCMSupport2(), num_workers=1) + self.assertEqual(len(samples), 3) + by_id = {sample["patient_id"]: sample for sample in samples} + self.assertEqual(set(by_id), {"1", "2", "3"}) + for sample in by_id.values(): + self.assertEqual(tuple(sample["features"].shape), (N_FEATURES,)) + alb = DCM_SUPPORT2_FEATURES.index("alb") + glucose = DCM_SUPPORT2_FEATURES.index("glucose") + self.assertFalse(torch.isnan(by_id["1"]["features"]).any()) + self.assertTrue(torch.isnan(by_id["2"]["features"][alb])) + self.assertTrue(torch.isnan(by_id["3"]["features"][glucose])) + self.assertEqual(one_hot(by_id["1"], "race").tolist(), [0.0] * 4 + [1.0]) + self.assertEqual(one_hot(by_id["2"], "race").tolist(), [0.0] * 5) + self.assertEqual(one_hot(by_id["3"], "income").tolist(), [0.0] * 4) + self.assertEqual(by_id["2"]["event"].item(), 0.0) + self.assertEqual(by_id["3"]["duration"].item(), 30.0) + + +if __name__ == "__main__": + unittest.main()