train_model
Note
This page is a reference documentation. It only explains the function signature, and not how to use it. Please refer to the Habitat Guide and Python API guide (v2.0) for usage.
- train_model(table: FeatureTable, spec: MLSpec, *, seed: int | None = None, test_size: float | None = None, stratify: bool = True, train_ids: Sequence[str] | None = None, test_ids: Sequence[str] | None = None) ModelResult[source]
Fit one pipeline on a table and score it, with an optional hold-out split.
Without split arguments the pipeline is fitted on every row and scored on those same rows. With
test_sizethe rows are first split into a training and a held-out side (stratified on the outcome unlessstratify=False, the v0.1randommethod); withtrain_ids/test_idsthe split follows the given row ids exactly (the v0.1custommethod). Under a split the pipeline sees the training rows ONLY, so preprocessing statistics and feature selection can never leak in from the held-out rows, and both sides are scored.- Parameters:
table – Feature table with a declared outcome.
spec – The modelling definition to fit.
seed – Optional seed override, folded into the spec (and therefore into the split shuffling, the component seeding, and the manifest) before anything runs.
test_size – Fraction of rows assigned to the held-out side;
Nonekeeps the no-split behaviour. Mutually exclusive with the id lists.stratify – Stratify the
test_sizesplit on the outcome when the endpoint family has strata; ignored for id-list splits and continuous endpoints (which have no strata).train_ids – Row ids (identifier columns joined as in
_row_ids()) forming the training side of a custom split. Must be given together withtest_ids.test_ids – Row ids forming the held-out side of a custom split.
- Returns:
The fitted pipeline, the training-set panel, and – under a split – the held-out panel plus both sides’ row ids.
- Raises:
HABITAPIError – If the table declares no outcome, the split arguments are contradictory, an id list is empty or names rows the table does not have, or the two id lists overlap.
Examples
>>> from habit.datasets import make_synthetic_feature_table >>> from habit.spec import MLSpec, Spec >>> import habit.recipes as recipes >>> table = make_synthetic_feature_table(n_rows=60, n_features=8, rng=42) >>> spec = MLSpec( ... name="demo", ... steps=(Spec("zscore"),), ... classifier=Spec("LogisticRegression", {"max_iter": 500}), ... metrics=(Spec("accuracy"), Spec("auc")), ... ) >>> result = recipes.train_model(table, spec, test_size=0.25, seed=42) >>> sorted(result.test_metrics) ['accuracy', 'auc']