How to Build a Simple ML Pipeline with ZenML in Python

Build a mock machine learning pipeline with ZenML steps for data loading, training, and evaluation, and run it to print the final accuracy.

Easy Python 3.9+ Aug 9, 2026 ML engineering pipelines 13 views 0 copies

Requires third-party packages — install first
pip install zenml

Python code

35 lines
Python 3.9+
from zenml import pipeline, step


@step
def load_data() -> dict:
    """Simulate loading data from a source."""
    return {"accuracy": 0.0, "loss": 1.0}


@step
def train_model(data: dict) -> dict:
    """Simulate training a model."""
    data["accuracy"] = 0.95
    data["loss"] = 0.1
    return data


@step
def evaluate_model(model: dict) -> float:
    """Simulate evaluating the model."""
    return model["accuracy"]


@pipeline
def ml_pipeline() -> float:
    """Define the machine learning pipeline."""
    data = load_data()
    trained_model = train_model(data)
    accuracy = evaluate_model(trained_model)
    return accuracy


if __name__ == "__main__":
    result = ml_pipeline()
    print(f"Pipeline accuracy: {result:.2f}")

Output

stdout
Pipeline accuracy: 0.95

How it works

ZenML decorators @step and @pipeline turn plain functions into reusable pipeline components. Each step receives typed inputs and returns outputs that are automatically passed to the next step. The pipeline runs steps sequentially in the order defined, and you can call the pipeline function to execute it. This example mocks real ML work but demonstrates the core structure for production pipelines.

Common mistakes

  • Forgetting to call the pipeline function inside `if __name__ == "__main__"`.
  • Passing wrong types between steps, causing ZenML type validation errors.
  • Not installing ZenML with `pip install zenml` before running the script.

Variations

  1. Use `@step` with `enable_cache=False` to force re-execution each run.
  2. Add a `config` object to parameterize steps for different runs.

Real-world use cases

  • Automating a training pipeline that loads CSV data, trains a model, and logs metrics to a dashboard.
  • Orchestrating batch inference jobs that preprocess data, run predictions, and store results in a database.
  • Building a CI/CD ML workflow where each commit triggers a pipeline run to test new model versions.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from ML engineering pipelines

Related tutorials and quizzes for this topic.