Hyper-parameter tuning
Running a hyperparameter tuning trial with ZenML.
Last updated
Was this helpful?
Was this helpful?
from typing import Annotated
from sklearn.base import ClassifierMixin
from zenml import step
MODEL_OUTPUT = "model"
@step
def train_step(learning_rate: float) -> Annotated[ClassifierMixin, MODEL_OUTPUT]:
"""Train a model with the given learning‑rate."""
# <your training code goes here>
...from zenml import pipeline
from zenml import get_step_context, step
from zenml.client import Client
@step
def selection_step(step_prefix: str, output_name: str):
"""Pick the best model among all training steps."""
run = Client().get_pipeline_run(get_step_context().pipeline_run.name)
trained_models = {}
for step_name, step_info in run.steps.items():
if step_name.startswith(step_prefix):
model = step_info.outputs[output_name][0].load()
lr = step_info.config.parameters["learning_rate"]
trained_models[lr] = model
# <evaluate and select your favorite model here>
@pipeline
def hp_tuning_pipeline(step_count: int = 4):
after = []
for i in range(step_count):
train_step(learning_rate=i * 0.0001, id=f"train_step_{i}")
after.append(f"train_step_{i}")
selection_step(step_prefix="train_step_", output_name=MODEL_OUTPUT, after=after)if __name__ == "__main__":
hp_tuning_pipeline(step_count=4)()from zenml.client import Client
run = Client().get_pipeline("hp_tuning_pipeline").last_run
best_model = run.steps["selection_step"].outputs["best_model"].load()