AutoImprove#

pyhealth.autoimprove improves a pipeline for you. You give it training and validation splits and your current configuration. A few agents then take turns proposing changes: the model, its arguments and the training settings. Each proposal is trained on the training split and scored on the validation split. The agents see each other’s results and work through four strategies in turn: explore, refine, crossover and contrast. The design follows codegen-classroom.

Proposals come from an LLM (LLMProposer, with ClaudeLLM or any llm(system, prompt) -> str callable), or from random search (RandomProposer), which needs no API key.

After each cycle, the LLM proposer rewrites a short list of lessons from the results. Later prompts build on those lessons, and so do later runs that pass lessons_path. The search therefore improves the guidance it runs on, as well as the pipeline.

from pyhealth.autoimprove import (
    AutoImprover, ClaudeLLM, LLMProposer, PipelineConfig,
)
from pyhealth.datasets import PatientSplit

train, val, test = dataset.set_task(task, split=PatientSplit((0.7, 0.1, 0.2)))
improver = AutoImprover(
    train, val, LLMProposer(ClaudeLLM()),
    baseline=PipelineConfig("RNN", {"hidden_dim": 128}, {"epochs": 10}),
    n_agents=3, n_cycles=5, run_dir="runs/mortality",
    cv_folds=5,                  # score by patient-grouped CV
)
result = improver.run()          # resumes if runs/mortality has trials
print(result.summary())          # validation leaderboard
print(improver.evaluate_on_test(test))  # best vs baseline, once, on test

Choosing a config you can trust#

A search ranks many configs on the same data, so the top score is partly luck. On a small validation split this luck can dominate: the winner looks best on validation and does worse on test. Two options guard against it.

  • cv_folds=5 scores every trial by patient-grouped cross-validation over the training split (patient_folds()). The validation split is then used only for early stopping. Each trial trains cv_folds models.

  • promote_se=1.0 (the default with cv_folds) decides which trial is selected. All trials share the same folds, so each is compared with the baseline fold by fold. The selection is the trial whose gain has the highest lower bound, the mean minus one standard error of the per-fold differences (select_trial()). A config with a higher mean but an inconsistent gain loses to a steadier one, and the baseline stays selected unless some trial’s bound is above 0.

Lessons saved to lessons_path are stored per search, keyed by the inputs, the label and the models in the search space. A run reads only the lessons learned on the same kind of search, and the lessons may mention only models that the space allows.

Models that cannot read your inputs#

Not every model reads every input type. XGBoost, for example, needs fixed-width columns and rejects code sequences. Before searching, the improver gives each model in the space one training step on a few training samples (check_models()). Models that fail are removed from the space, logged with the error, and listed in ImproveResult.dropped_models, so no trial is spent on them. If the baseline’s model fails, run() stops with the error instead. Pass check=False to skip the check.

Safety and data#

  • Proposals are data, never code. Every proposal is a JSON config, checked against a SearchSpace before anything runs. Unknown models are rejected, unknown arguments are dropped, and out-of-range numbers are clipped. Nothing the LLM writes is executed.

  • Prompts hold aggregates only. They contain the search space, the input and label schema, split sizes, the training positive count and validation scores. They never contain patient records. Your data use agreement still decides whether you may send even these to an external service.

  • The test split is never used during the search. Validation scores are selected on many times, so they are optimistic, especially with few positive samples (the improver warns below 30). evaluate_on_test() retrains the best and the baseline configs and compares them on test. For binary labels it reports patient-level bootstrap intervals and a paired difference. return_predictions=True also returns the test predictions, for other metrics without training again.

API Reference#

Automatic, guided improvement of PyHealth pipelines.

An AutoImprover searches over model, argument and training choices, guided by an LLM (LLMProposer) or at random (RandomProposer), scoring every proposal on validation patients and keeping the test split for one final comparison.

class pyhealth.autoimprove.AutoImprover(train_dataset, val_dataset, proposer, baseline=None, space=None, metric=None, report_metrics=(), n_agents=3, n_cycles=5, patience=2, max_trials=None, time_budget=None, seed=0, device=None, run_dir=None, lessons_path=None, cv_folds=None, promote_se=1.0, check=True)[source]#

Bases: object

Improves a PyHealth pipeline automatically, by guided search.

A small population of agents takes turns proposing configurations (model, arguments, training settings). Each one is checked against the search space, trained on the training split and scored on the validation split. The agents see each other’s results and follow rotating strategies (explore, refine, crossover, contrast), as in codegen-classroom. After every cycle the proposer rewrites a short list of lessons from the results, which later prompts (and later runs, with lessons_path) build on. The loop stops after n_cycles, after patience cycles without progress (no new selection and no better best score), or when the trial or time budget runs out.

The test split is never used during the search. Call evaluate_on_test() once afterwards to compare the best config with the starting one on held-out patients.

Proposals are data, never code: nothing a proposer returns is executed.

Parameters:
  • train_dataset (SampleDataset) – Training samples, e.g. from set_task(task, split=PatientSplit(...)).

  • val_dataset (SampleDataset) – Validation samples, used to score every trial (or, with cv_folds, only for early stopping).

  • proposer (Proposer) – Where proposals come from, e.g. LLMProposer(ClaudeLLM()) or RandomProposer().

  • baseline (Optional[PipelineConfig]) – The current pipeline, tried first so later trials are compared with it.

  • space (Optional[SearchSpace]) – Allowed models and ranges. Defaults to SearchSpace(). pos_weight is dropped from it unless the label is binary or multilabel, the label types it applies to.

  • metric (Optional[str]) – Validation metric to optimise. Defaults by label type (DEFAULT_METRIC).

  • report_metrics (Sequence[str]) – Extra validation metrics to record.

  • n_agents (int) – Number of agents.

  • n_cycles (int) – Most cycles; each agent proposes once per cycle.

  • patience (int) – Cycles without progress before stopping. A cycle makes progress if the selected trial changes or some trial beats the best score so far. Counting new best scores too keeps a search going while it finds better configs whose gains are still too noisy to be selected.

  • max_trials (Optional[int]) – Most trials in total (the baseline included).

  • time_budget (Optional[float]) – Most seconds for the whole search.

  • seed (int) – Training seed, the same for every trial so scores compare fairly. It also fixes the cv_folds folds.

  • cv_folds (Optional[int]) – Score each trial by patient-grouped cross-validation with this many folds of train_dataset instead of on val_dataset. Much less noisy when the validation split is small, at the cost of cv_folds trainings per trial.

  • device (Optional[str]) – Torch device for training.

  • run_dir (Optional[str]) – Directory for trials.jsonl, lessons.json and meta.json. A run with the same directory resumes where the last one stopped. meta.json records the settings the trials depend on (metric, cv_folds, promote_se, seed, baseline, search space and data sizes); resuming with any of them changed raises ValueError rather than mixing old and new trials. Budgets (n_cycles, max_trials, …) may change.

  • lessons_path (Optional[str]) – A JSON file of lessons to reuse across runs. Lessons are stored per search space and task (inputs, label, models and their arguments), so a run only reads lessons learned on the same kind of search.

  • promote_se (Optional[float]) – With cv_folds, every trial is compared with the baseline on the shared folds, and the selection is the trial whose gain has the highest lower bound, mean minus promote_se standard errors. The baseline stays selected unless some bound is above 0. None selects the best mean, as does a run without a baseline (or whose baseline trial failed), since there is nothing to compare with.

  • check (bool) – Before searching, give every model in the space one training step on a few training samples (check_models()) and remove the ones that fail, e.g. a model that cannot read one of the task’s input types, so no trial is spent on them. They are listed in ImproveResult.dropped_models.

Examples

>>> from pyhealth.autoimprove import (AutoImprover, ClaudeLLM,
...     LLMProposer, PipelineConfig)
>>> improver = AutoImprover(
...     train_ds, val_ds, LLMProposer(ClaudeLLM()),
...     baseline=PipelineConfig("RNN", {"hidden_dim": 128}, {"epochs": 10}),
...     n_agents=3, n_cycles=5, run_dir="runs/mortality",
... )  
>>> result = improver.run()  
>>> print(result.summary())  
>>> improver.evaluate_on_test(test_ds)  
run()[source]#

Runs the search and returns its trials and lessons.

Return type:

ImproveResult

result()[source]#

The current state as an ImproveResult.

Return type:

ImproveResult

evaluate_on_test(test_dataset, n_boot=1000, return_predictions=False)[source]#

Retrains the best and the baseline configs and scores them on test.

Run this once, after the search. For binary labels the result holds patient-level bootstrap intervals (bootstrap_ci) and a paired bootstrap interval for best minus baseline (paired_bootstrap_diff). Other label types get the metric’s value on test.

Parameters:
  • test_dataset (SampleDataset) – Held-out samples, never seen by the search.

  • n_boot (int) – Bootstrap resamples.

  • return_predictions (bool) – Also return the test predictions, e.g. to compute other metrics without training again.

Return type:

dict[str, Any]

Returns:

{"best": {...}, "baseline": {...}, "difference": {...}}; baseline and difference are present when a baseline was given, and difference only for binary labels. With return_predictions, "predictions" holds y_true, patient_ids and each config’s y_prob under its name.

Examples

>>> improver.evaluate_on_test(test_ds)  
class pyhealth.autoimprove.ClaudeLLM(model='claude-opus-5-5', effort='high', max_tokens=16000, fallback=True, client=None)[source]#

Bases: object

Calls Claude through the Anthropic SDK.

Credentials come from the environment (ANTHROPIC_API_KEY or an ant auth login profile). Only the prompts built by the proposer are sent: the search space, dataset sizes and schema, aggregate label counts and validation scores. A failed trial is described by its exception type and the code line that raised it, without the message. No patient records are sent.

The request uses the server-side fallback beta and output_config, which need anthropic>=1.15 (MIN_ANTHROPIC).

Parameters:
  • model (str) – Claude model id.

  • effort (str) – Reasoning effort, "low" to "max".

  • max_tokens (int) – Upper bound on the reply length.

  • fallback (bool) – Retry on another model if this one declines the request (server-side fallback).

  • client (Any) – An anthropic.Anthropic client; created when omitted.

Examples

>>> from pyhealth.autoimprove import ClaudeLLM, LLMProposer
>>> proposer = LLMProposer(ClaudeLLM())  
class pyhealth.autoimprove.ImproveResult(trials, best, baseline, lessons, maximize, dropped_models=<factory>)[source]#

Bases: object

The outcome of AutoImprover.run().

Parameters:
  • trials (list[Trial]) – Every trial, in the order run.

  • best (Optional[Trial]) – The selected trial: the best score, or with paired selection (cv_folds, promote_se and a baseline) the trial with the highest lower bound on its fold-by-fold gain over the baseline.

  • baseline (Optional[Trial]) – The trial of the starting config, if one was given.

  • lessons (list[str]) – The lessons at the end of the run.

  • maximize (bool) – Whether larger scores are better.

  • dropped_models (dict[str, str]) – Models removed from the space before the search because they did not run on the training data, with the error.

Examples

>>> trial = Trial(0, -1, "baseline", "baseline", PipelineConfig("MLP"),
...               metric_name="pr_auc", score=0.3)
>>> result = ImproveResult([trial], trial, trial, [], maximize=True)
>>> result.leaderboard(k=1)[0].score
0.3
trials: list[pyhealth.autoimprove.improver.Trial]#
best: pyhealth.autoimprove.improver.Trial | None#
baseline: pyhealth.autoimprove.improver.Trial | None#
lessons: list[str]#
maximize: bool#
dropped_models: dict[str, str]#
leaderboard(k=10)[source]#

The k best finished trials, best first.

Return type:

list[Trial]

summary(k=10)[source]#

A markdown table of the leaderboard.

Examples

>>> print(result.summary())  
Return type:

str

class pyhealth.autoimprove.LLMProposer(llm, max_attempts=3, max_lessons=10)[source]#

Bases: Proposer

Asks an LLM for configurations, with results and lessons as context.

Each prompt holds the task summary, the search space, the agent’s own trials, the leaderboard, the worst trials, the lessons learned so far and one improvement strategy (STRATEGIES). After each cycle, reflect() asks the LLM to rewrite the lessons from the new results. The lessons are passed to every later prompt and can be saved and reused across runs, so the improver also improves the guidance it works from.

Parameters:
  • llm (Callable[str, str, str]) – Backend, e.g. ClaudeLLM, or any callable llm(system, prompt) -> str.

  • max_attempts (int) – Requests per proposal before giving up on unparseable replies.

  • max_lessons (int) – Most lessons kept.

Examples

>>> from pyhealth.autoimprove import ClaudeLLM, LLMProposer
>>> proposer = LLMProposer(ClaudeLLM())  
propose(context)[source]#

Returns one configuration (it is validated by the improver).

Return type:

PipelineConfig

reflect(trials, lessons, metric, space=None)[source]#

Updates the lessons after a cycle. The default keeps them as they are.

Return type:

list[str]

class pyhealth.autoimprove.ModelSpec(target, params=<factory>, trainer='torch')[source]#

Bases: object

A model the improver may use, and its tunable constructor arguments.

Parameters:
  • target (str) – Import path of the model class, e.g. "pyhealth.models.RNN".

  • params (dict[str, Param]) – Tunable constructor arguments.

  • trainer (str) – "torch" for models trained with Trainer, "fit" for models with their own fit method (the gradient-boosted trees).

Examples

>>> spec = ModelSpec("pyhealth.models.RNN", {"hidden_dim": Param("int", 16, 256)})
>>> spec.load().__name__
'RNN'
target: str#
params: dict[str, pyhealth.autoimprove.space.Param]#
trainer: str = 'torch'#
load()[source]#

Imports and returns the model class.

Return type:

type

class pyhealth.autoimprove.Param(kind, low=None, high=None, choices=(), log=False, default=None)[source]#

Bases: object

The allowed values of one argument.

Parameters:
  • kind (str) – "int", "float" or "choice".

  • low (Optional[float]) – Smallest value (int and float).

  • high (Optional[float]) – Largest value (int and float).

  • choices (Sequence[Any]) – Allowed values (choice).

  • log (bool) – Sample float values on a log scale.

  • default (Any) – Value used when a proposal leaves the argument out.

Examples

>>> Param("int", 16, 256, default=128).check(1000)
(256, 'clipped to 256')
>>> Param("choice", choices=("GRU", "LSTM"), default="GRU").check("RNN")
('GRU', "'RNN' is not one of ['GRU', 'LSTM']; used 'GRU'")
kind: str#
low: float | None = None#
high: float | None = None#
choices: Sequence[Any] = ()#
log: bool = False#
default: Any = None#
check(value)[source]#

Returns the value made valid, and a note if it had to change.

Return type:

tuple[Any, Optional[str]]

sample(rng)[source]#

Draws a random allowed value.

Return type:

Any

describe()[source]#

A short description for prompts, e.g. int in [16, 256].

Return type:

str

class pyhealth.autoimprove.PipelineConfig(model, model_params=<factory>, train_params=<factory>, rationale='')[source]#

Bases: object

One pipeline to try: a model, its arguments and how to train it.

Parameters:
  • model (str) – A model name from the search space, e.g. "RNN".

  • model_params (dict[str, Any]) – Constructor arguments for the model.

  • train_params (dict[str, Any]) – Training settings (epochs, lr, weight_decay, batch_size, pos_weight).

  • rationale (str) – Why the proposer chose it, kept for the report.

Examples

>>> config = PipelineConfig("RNN", {"hidden_dim": 64}, {"lr": 1e-3})
>>> config.key()
'{"model": "RNN", "model_params": {"hidden_dim": 64}, "train_params": {"lr": 0.001}}'
model: str#
model_params: dict[str, Any]#
train_params: dict[str, Any]#
rationale: str = ''#
to_dict()[source]#

The configuration without its rationale, as plain JSON types.

Return type:

dict[str, Any]

key()[source]#

A canonical string, so that repeated proposals are recognised.

Return type:

str

classmethod from_dict(data)[source]#

Builds a config from a dict such as one parsed from JSON.

Raises:

TypeError – If model_params or train_params is not a dict.

Return type:

PipelineConfig

class pyhealth.autoimprove.Proposer[source]#

Bases: ABC

Proposes the next configuration to try.

Examples

>>> class AlwaysMLP(Proposer):
...     def propose(self, context):
...         return PipelineConfig("MLP", rationale="a fixed choice")
>>> AlwaysMLP().propose(None).model
'MLP'
abstract propose(context)[source]#

Returns one configuration (it is validated by the improver).

Return type:

PipelineConfig

reflect(trials, lessons, metric, space=None)[source]#

Updates the lessons after a cycle. The default keeps them as they are.

Return type:

list[str]

class pyhealth.autoimprove.RandomProposer(seed=0)[source]#

Bases: Proposer

Random search over the space: a baseline that needs no LLM.

Parameters:

seed (int) – Seed for the random draws.

Examples

>>> from pyhealth.autoimprove import RandomProposer, SearchSpace
>>> from pyhealth.autoimprove.proposers import ProposalContext
>>> context = ProposalContext("a0", "explore", SearchSpace(), "", "pr_auc", True)
>>> RandomProposer(seed=0).propose(context).model in SearchSpace().models
True
propose(context)[source]#

Returns one configuration (it is validated by the improver).

Return type:

PipelineConfig

reflect(trials, lessons, metric, space=None)#

Updates the lessons after a cycle. The default keeps them as they are.

Return type:

list[str]

class pyhealth.autoimprove.SearchSpace(models=None, train_params=None)[source]#

Bases: object

The models and argument ranges an improver may propose.

Parameters:
  • models (Optional[dict[str, ModelSpec]]) – Model name to ModelSpec. Defaults to DEFAULT_MODELS.

  • train_params (Optional[dict[str, Param]]) – Training settings for "torch" models. Defaults to TRAIN_PARAMS.

Examples

>>> space = SearchSpace()
>>> config, notes = space.validate(
...     PipelineConfig("RNN", {"hidden_dim": 999, "colour": "red"}, {})
... )
>>> config.model_params["hidden_dim"], notes
(256, ['hidden_dim: clipped to 256', 'colour: not an argument of RNN; dropped'])
validate(config)[source]#

Makes a proposal valid, listing every change that was needed.

Unknown arguments are dropped, numbers outside their range are clipped, and invalid choices fall back to the default.

Raises:

ValueError – If the model is not in the space.

Return type:

tuple[PipelineConfig, list[str]]

sample(rng)[source]#

Draws a random valid configuration.

Return type:

PipelineConfig

describe()[source]#

The space in plain text, for an LLM prompt.

Return type:

str

class pyhealth.autoimprove.Trial(trial_id, cycle, agent, strategy, config, metric_name='', score=None, metrics=<factory>, notes=<factory>, seconds=0.0, n_params=0, error=None, fold_scores=<factory>, error_brief=None)[source]#

Bases: object

One proposed configuration and how it did on validation.

error holds the full error text and is kept in trials.jsonl. error_brief leaves out the exception’s message, which can quote a raw value from a sample, and is the form shown to a proposer.

Examples

>>> trial = Trial(0, 0, "baseline", "baseline", PipelineConfig("RNN"),
...               metric_name="pr_auc", score=0.3)
>>> Trial.from_dict(trial.to_dict()).score
0.3
trial_id: int#
cycle: int#
agent: str#
strategy: str#
config: PipelineConfig#
metric_name: str = ''#
score: float | None = None#
metrics: dict[str, float]#
notes: list[str]#
seconds: float = 0.0#
n_params: int = 0#
error: str | None = None#
fold_scores: list[float]#
error_brief: str | None = None#
to_dict()[source]#

The trial as JSON-ready types.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]#

Rebuilds a trial saved with to_dict().

Return type:

Trial

pyhealth.autoimprove.check_models(space, dataset, n_samples=32, seed=0, device=None)[source]#

Checks that every model in a space runs on a dataset’s inputs.

Each model is built with its default arguments and takes one training step on n_samples samples (taking each label value in turn when the label is a single number, so a binary sample has both classes): a forward and backward pass for torch models, a fit and a forward pass for fit models. A model that fails here would fail every trial, e.g. a model that cannot read one of the task’s input types.

Parameters:
  • space (SearchSpace) – The models to check.

  • dataset (SampleDataset) – Samples with the task’s inputs, e.g. the training split.

  • n_samples (int) – How many samples to try.

  • seed (int) – Seed for weight initialisation.

  • device (Optional[str]) – Torch device for torch models.

Return type:

dict[str, Optional[str]]

Returns:

Model name to None if it ran, else the error (describe_error()).

Examples

>>> check_models(with_xgboost(SearchSpace()), code_seq_ds)  
{'CNN': None, ..., 'XGBoost': "ValueError: Field 'conditions' uses ..."}
pyhealth.autoimprove.describe_error(error, message=True)[source]#

An error as text, with the line that raised it.

A bare assert has no message, so the failing line is the only clue a proposer gets about what to change. With message=False the message is left out: an exception raised while reading a sample can quote a raw value, so this is the form shown to a proposer.

Examples

>>> try:
...     assert 197 % 4 == 0
... except AssertionError as e:
...     print(describe_error(e))  
AssertionError: (no message) at ...: assert 197 % 4 == 0
>>> def parse(value):
...     return int(value)
>>> try:
...     parse("a raw value")
... except ValueError as e:
...     print(describe_error(e, message=False))  
ValueError at ...: return int(value)
Return type:

str

pyhealth.autoimprove.paired_gain(candidate, incumbent, maximize)[source]#

Mean and standard error of the fold-by-fold gain of one config over another.

Examples

>>> paired_gain([0.5, 0.6, 0.7], [0.4, 0.5, 0.6], maximize=True)
(0.1, 0.0)
Return type:

tuple[float, float]

pyhealth.autoimprove.patient_folds(dataset, n_folds, seed=0)[source]#

Splits a dataset’s sample indices into folds by patient.

Every sample of a patient lands in the same fold, so a patient with several samples never sits on both sides of a fold. Patients are shuffled with seed. When the label is 0/1 and the dataset has at most MAX_LABEL_SCAN (50,000) samples, the patients with a positive sample are dealt first, each to the fold with the fewest of them, so every fold has positives if at least n_folds patients do. The other patients go to the currently smallest fold, which keeps fold sizes close when patients have different numbers of samples.

Raises:

ValueError – If there are fewer patients than folds.

Examples

>>> folds = patient_folds(train_ds, 5)  
>>> sum(len(f) for f in folds) == len(train_ds)  
True
Return type:

list[ndarray]

pyhealth.autoimprove.predict(model, dataset, batch_size=256)[source]#

Returns labels, predicted probabilities and patient ids for a dataset.

Examples

>>> y_true, y_prob, patient_ids = predict(model, test_ds)  
Return type:

tuple[ndarray, ndarray, list]

pyhealth.autoimprove.run_config(config, space, train_dataset, val_dataset, metric, report_metrics=(), seed=0, device=None)[source]#

Trains a config on the training set and scores it on validation.

Return type:

dict[str, Any]

Returns:

{"metrics": {...}, "seconds": float, "n_params": int}.

Examples

>>> run_config(config, space, train_ds, val_ds, "pr_auc")  
{'metrics': {'pr_auc': 0.41}, 'seconds': 12.3, 'n_params': 51521}
pyhealth.autoimprove.run_config_cv(config, space, train_dataset, val_dataset, metric, folds, report_metrics=(), seed=0, device=None)[source]#

Scores a config by patient-grouped cross-validation on the training set.

For each fold, the config is trained on the other folds and scored on the held-out fold. val_dataset is used only for early stopping, so no fold is scored by a model that saw it. Each metric is the mean over folds; <metric>_sd holds the spread between folds, and fold_scores the per-fold values of metric (for paired comparisons between configs scored on the same folds).

Scoring on every training patient gives a much less noisy estimate than one small validation split, at the cost of training len(folds) models per trial. Processors are not refitted per fold.

Returns:

{…}, “fold_scores”: […], “seconds”: float, “n_params”: int}``.

Return type:

``{“metrics”

Examples

>>> folds = patient_folds(train_ds, 5)  
>>> run_config_cv(config, space, train_ds, val_ds, "pr_auc", folds)  
{'metrics': {'pr_auc': 0.47, 'pr_auc_sd': 0.03}, 'seconds': 61.0, 'n_params': 51521}
pyhealth.autoimprove.score(model, dataset, metrics)[source]#

Computes metrics for a trained model on a dataset.

Examples

>>> score(model, val_ds, ["pr_auc", "roc_auc"])  
{'pr_auc': 0.41, 'roc_auc': 0.78}
Return type:

dict[str, float]

pyhealth.autoimprove.select_trial(trials, maximize, promote_se=None)[source]#

The trial a search would deploy.

Without promote_se: the best score. With it, every trial is compared with the baseline trial (agent == "baseline") on the shared folds, and the trial with the highest lower bound on its gain, mean - promote_se * se, is selected if that bound is above 0; otherwise the baseline stays selected. Trials without fold scores matching the baseline’s are not candidates. Without a finished baseline trial with fold scores there is nothing to compare with, and the best score is selected. Ties go to the lower trial_id, so the result does not depend on the order the trials ran in.

Examples

>>> a = Trial(0, -1, "baseline", "baseline", PipelineConfig("RNN"),
...           score=0.50, fold_scores=[0.48, 0.50, 0.52])
>>> b = Trial(1, 0, "agent0", "explore", PipelineConfig("MLP"),
...           score=0.52, fold_scores=[0.40, 0.58, 0.58])
>>> select_trial([a, b], True).trial_id, select_trial([a, b], True, 1.0).trial_id
(1, 0)
Return type:

Optional[Trial]

pyhealth.autoimprove.train_pipeline(config, space, train_dataset, val_dataset, metric, seed=0, device=None)[source]#

Builds and trains the model a config describes.

Training uses only train_dataset. val_dataset is used for early stopping (torch models) or early-stopping rounds (fit models). The global torch random state is restored afterwards.

Parameters:
  • config (PipelineConfig) – A config already checked by space.validate.

  • space (SearchSpace) – The search space the config belongs to.

  • train_dataset (SampleDataset) – Training samples.

  • val_dataset (SampleDataset) – Validation samples.

  • metric (str) – Metric monitored for early stopping.

  • seed (int) – Seed for weight initialisation and shuffling.

  • device (Optional[str]) – Torch device; defaults to CUDA when available.

Return type:

Module

Returns:

The trained model.

Examples

>>> model = train_pipeline(config, space, train_ds, val_ds, "pr_auc")  
pyhealth.autoimprove.with_xgboost(space)[source]#

Adds XGBoostModel to a search space.

XGBoost needs fixed-width (tabular) inputs, so it is not in the default space. Add it when the task’s features are tensors.

Examples

>>> "XGBoost" in with_xgboost(SearchSpace()).models
True
Return type:

SearchSpace