ehrapy.ml.fit

Contents

ehrapy.ml.fit#

ehrapy.ml.fit(edata, task, *, model=None, trainer=None, var_names=None, obs_keys=(), layer=None, statistics=('min', 'max', 'mean'), split_key='split', time_key='interval_start_offset', max_train_obs=10000, random_state=0)[source]#

Fit a model that predicts the targets of a task from variables and obs columns.

Most models read the longitudinal variables summarized over the observation window of the task with summarize_measurements(). For them, missing values are imputed with the median and features are standardized, with both steps fit on the training set only, like the model. Models of time series read the variables at every timepoint of the observation window, whether they were observed and the time since their last observation, standardized with statistics of the training set. Deep learning models stop training once their loss on the “tuning” set stops improving. For rolling tasks, models of summaries are fit on every labeled timepoint, and models of time series except RETAIN predict every timepoint from all earlier ones.

The models are

  • “logistic”: a logistic regression for binary, multiclass and multilabel tasks,

  • “linear”: a ridge regression for regression tasks,

  • “gradient_boosting”: gradient boosted trees for every task except survival,

  • “random_forest”: a random forest for every task except survival,

  • “cox”: a Cox proportional hazards model for survival tasks,

  • “mlp”: a multilayer perceptron as in MLP,

  • “gru”, “lstm”, “grud”, “tcn”, “transformer” and “retain”: models of time series as in GRU, LSTM, GRUD, TCN, Transformer and RETAIN.

Deep learning models fit every kind of task and need PyTorch, which pip install ‘ehrapy[ml]’ installs.

Parameters:
  • edata (EHRData) – Central data object.

  • task (Task) – The prediction task.

  • model (Literal['logistic', 'linear', 'gradient_boosting', 'random_forest', 'cox', 'mlp', 'gru', 'lstm', 'grud', 'tcn', 'transformer', 'retain'] | BaseEstimator | DeepModel | Module | None, default: None) – Name of the model, a scikit-learn estimator, a configured deep learning model, or a torch module. An estimator for survival tasks is fit on the time and whether the event occurred and predicts a risk score. A torch module is a model of time series that maps the values, whether they were observed (mask) and the time since their last observation (time_since_observed), each of shape (observations, timepoints, variables), and the static covariates of shape (observations, covariates) to an embedding of shape (observations, features), or to an embedding and the attention to every timepoint. For rolling tasks, it returns an embedding of every timepoint of shape (observations, timepoints, features) that only reads earlier timepoints. If None, gradient boosting, or the Cox model for survival tasks.

  • trainer (Trainer | None, default: None) – How a deep learning model or torch module is trained, replacing the trainer of a configured deep learning model. If None, the trainer of a configured deep learning model or else the defaults of Trainer are used.

  • var_names (Iterable[str] | None, default: None) – Variables to compute features from. If None, all variables except the targets are used.

  • obs_keys (Iterable[str], default: ()) – Columns of obs to use as features, with categorical columns one-hot encoded.

  • layer (str | None, default: None) – Layer to read the variables from. If None, .X is used.

  • statistics (Iterable[Literal['min', 'max', 'mean', 'median', 'first', 'last', 'count', 'std', 'slope']], default: ('min', 'max', 'mean')) – Statistics that summarize every longitudinal variable over the observation window, see summarize_measurements().

  • split_key (str, default: 'split') – Column of obs with the sets from split(). The model is fit on the observations in “train” with all targets.

  • time_key (str, default: 'interval_start_offset') – Column of tem with the time of every timepoint, as numbers, time differences or dates, from which models of time series compute the time since the last observation. If tem has no such column, the timepoints are evenly spaced.

  • max_train_obs (int | None, default: 10000) – Maximum number of randomly chosen training and tuning observations the model is fit on. If None, all are used.

  • random_state (int, default: 0) – Seed for choosing the training observations and for the built-in models.

Return type:

Predictor

Returns:

The fitted model, to pass to predict().

Examples

>>> import ehrdata as ed
>>> import ehrapy as ep
>>> edata = ed.dt.ehrdata_blobs(n_observations=200, n_centers=2, base_timepoints=10)
>>> ep.ml.split(edata, stratify="cluster")
>>> task = ep.ml.Task("cluster", prediction_time=6)
>>> predictor = ep.ml.fit(edata, task, model="logistic")

A torch module that embeds the mean of every variable over time, trained for at most 5 epochs:

>>> import torch
>>> class Mean(torch.nn.Module):
...     def __init__(self, n_variables: int):
...         super().__init__()
...         self.linear = torch.nn.Linear(n_variables, 8)
...
...     def forward(self, values, mask, time_since_observed, static):
...         return self.linear(values.mean(dim=1))
>>> trainer = ep.ml.Trainer(max_epochs=5, device="cpu")
>>> predictor = ep.ml.fit(edata, task, model=Mean(edata.n_vars), trainer=trainer)