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=5scores 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 trainscv_foldsmodels.promote_se=1.0(the default withcv_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
SearchSpacebefore 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=Truealso 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:
objectImproves 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 aftern_cycles, afterpatiencecycles 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. fromset_task(task, split=PatientSplit(...)).val_dataset (
SampleDataset) – Validation samples, used to score every trial (or, withcv_folds, only for early stopping).proposer (
Proposer) – Where proposals come from, e.g.LLMProposer(ClaudeLLM())orRandomProposer().baseline (
Optional[PipelineConfig]) – The current pipeline, tried first so later trials are compared with it.space (
Optional[SearchSpace]) – Allowed models and ranges. Defaults toSearchSpace().pos_weightis 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 thecv_foldsfolds.cv_folds (
Optional[int]) – Score each trial by patient-grouped cross-validation with this many folds oftrain_datasetinstead of onval_dataset. Much less noisy when the validation split is small, at the cost ofcv_foldstrainings per trial.device (
Optional[str]) – Torch device for training.run_dir (
Optional[str]) – Directory fortrials.jsonl,lessons.jsonandmeta.json. A run with the same directory resumes where the last one stopped.meta.jsonrecords the settings the trials depend on (metric,cv_folds,promote_se, seed, baseline, search space and data sizes); resuming with any of them changed raisesValueErrorrather 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]) – Withcv_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 minuspromote_sestandard errors. The baseline stays selected unless some bound is above 0.Noneselects 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 inImproveResult.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)
- result()[source]#
The current state as an
ImproveResult.- Return type:
- 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:
- Returns:
{"best": {...}, "baseline": {...}, "difference": {...}};baselineanddifferenceare present when a baseline was given, anddifferenceonly for binary labels. Withreturn_predictions,"predictions"holdsy_true,patient_idsand each config’sy_probunder 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:
objectCalls Claude through the Anthropic SDK.
Credentials come from the environment (
ANTHROPIC_API_KEYor anant auth loginprofile). 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 needanthropic>=1.15(MIN_ANTHROPIC).- Parameters:
Examples
>>> from pyhealth.autoimprove import ClaudeLLM, LLMProposer >>> proposer = LLMProposer(ClaudeLLM())
- class pyhealth.autoimprove.ImproveResult(trials, best, baseline, lessons, maximize, dropped_models=<factory>)[source]#
Bases:
objectThe outcome of
AutoImprover.run().- Parameters:
best (
Optional[Trial]) – The selected trial: the best score, or with paired selection (cv_folds,promote_seand 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.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]#
- baseline: pyhealth.autoimprove.improver.Trial | None#
- class pyhealth.autoimprove.LLMProposer(llm, max_attempts=3, max_lessons=10)[source]#
Bases:
ProposerAsks 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:
Examples
>>> from pyhealth.autoimprove import ClaudeLLM, LLMProposer >>> proposer = LLMProposer(ClaudeLLM())
- class pyhealth.autoimprove.ModelSpec(target, params=<factory>, trainer='torch')[source]#
Bases:
objectA model the improver may use, and its tunable constructor arguments.
- Parameters:
Examples
>>> spec = ModelSpec("pyhealth.models.RNN", {"hidden_dim": Param("int", 16, 256)}) >>> spec.load().__name__ 'RNN'
- params: dict[str, pyhealth.autoimprove.space.Param]#
- class pyhealth.autoimprove.Param(kind, low=None, high=None, choices=(), log=False, default=None)[source]#
Bases:
objectThe allowed values of one argument.
- Parameters:
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'")
- class pyhealth.autoimprove.PipelineConfig(model, model_params=<factory>, train_params=<factory>, rationale='')[source]#
Bases:
objectOne pipeline to try: a model, its arguments and how to train it.
- Parameters:
Examples
>>> config = PipelineConfig("RNN", {"hidden_dim": 64}, {"lr": 1e-3}) >>> config.key() '{"model": "RNN", "model_params": {"hidden_dim": 64}, "train_params": {"lr": 0.001}}'
- class pyhealth.autoimprove.Proposer[source]#
Bases:
ABCProposes 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'
- class pyhealth.autoimprove.RandomProposer(seed=0)[source]#
Bases:
ProposerRandom 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
- class pyhealth.autoimprove.SearchSpace(models=None, train_params=None)[source]#
Bases:
objectThe models and argument ranges an improver may propose.
- Parameters:
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:
- 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:
objectOne proposed configuration and how it did on validation.
errorholds the full error text and is kept intrials.jsonl.error_briefleaves 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
- config: PipelineConfig#
- 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_samplessamples (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 fortorchmodels, a fit and a forward pass forfitmodels. 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 fortorchmodels.
- Return type:
- Returns:
Model name to
Noneif 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
asserthas no message, so the failing line is the only clue a proposer gets about what to change. Withmessage=Falsethe 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:
- 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)
- 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 mostMAX_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 leastn_foldspatients 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)
- 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.
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_datasetis used only for early stopping, so no fold is scored by a model that saw it. Each metric is the mean over folds;<metric>_sdholds the spread between folds, andfold_scoresthe per-fold values ofmetric(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
metricsfor a trained model on a dataset.Examples
>>> score(model, val_ds, ["pr_auc", "roc_auc"]) {'pr_auc': 0.41, 'roc_auc': 0.78}
- 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 lowertrial_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_datasetis used for early stopping (torchmodels) or early-stopping rounds (fitmodels). The global torch random state is restored afterwards.- Parameters:
config (
PipelineConfig) – A config already checked byspace.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
XGBoostModelto 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: