Thursday, December 3, 2026 | London 11°C · Drizzle
DailyGlimpse

AI

Building a Production-Grade ML Pipeline with ZenML: Custom Materializers, Metadata Tracking, and Hyperparameter Optimization

MarkTechPost 6 min read

Building a Production-Grade ML Pipeline with ZenML: Custom Materializers, Metadata Tracking, and Hyperparameter Optimization

In this tutorial, we walk through an end-to-end implementation of an advanced machine learning pipeline using ZenML. We begin by setting up the environment and initializing a ZenML project, then define a custom materializer that enables seamless serialization and metadata extraction for a domain-specific dataset object. As we progress, we build a modular pipeline that performs data loading, preprocessing, and a fan-out hyperparameter search across multiple models. We evaluate each candidate, log rich metadata at every step, and use a fan-in strategy to select and promote the best-performing model. Throughout the process, we leverage ZenML’s model control plane, artifact tracking, and caching mechanisms to ensure full reproducibility, transparency, and efficiency.

import os, sys, subprocess, json, shutil
from pathlib import Path

def _sh(cmd, check=True):
print(f"$ {' '.join(cmd)}")
return subprocess.run(cmd, check=check)

_sh([sys.executable, "-m", "pip", "install", "-q",
"zenml[server]", "scikit-learn", "pandas", "pyarrow"])

PROJECT = Path("/content/zenml_advanced_tutorial") if Path("/content").exists() \
else Path.cwd() / "zenml_advanced_tutorial"
if PROJECT.exists():
shutil.rmtree(PROJECT)
PROJECT.mkdir(parents=True)
os.chdir(PROJECT)

os.environ["ZENML_ANALYTICS_OPT_IN"] = "false"
os.environ["ZENML_LOGGING_VERBOSITY"] = "WARN"
_sh(["zenml", "init"], check=False)

We set up the entire environment by installing required libraries and initializing a ZenML project workspace. We create a clean working directory and configure environment variables to control logging and analytics behavior. Finally, we bootstrap the ZenML repository so that all subsequent pipeline operations are properly tracked and managed.

from typing import Annotated, Tuple, Dict, List, Any
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from sklearn.preprocessing import StandardScaler

from zenml import pipeline, step, log_metadata, Model, get_step_context
from zenml.client import Client
from zenml.materializers.base_materializer import BaseMaterializer
from zenml.enums import ArtifactType
from zenml.io import fileio

class DatasetBundle:
def __init__(self, X, y, feature_names, stats=None):
self.X = np.asarray(X)
self.y = np.asarray(y)
self.feature_names = list(feature_names)
self.stats = stats or {}

class DatasetBundleMaterializer(BaseMaterializer):
ASSOCIATED_TYPES = (DatasetBundle,)
ASSOCIATED_ARTIFACT_TYPE = ArtifactType.DATA

def load(self, data_type):
with fileio.open(os.path.join(self.uri, "X.npy"), "rb") as f:
X = np.load(f)
with fileio.open(os.path.join(self.uri, "y.npy"), "rb") as f:
y = np.load(f)
with fileio.open(os.path.join(self.uri, "meta.json"), "r") as f:
meta = json.loads(f.read())
return DatasetBundle(X, y, meta["feature_names"], meta["stats"])

def save(self, bundle):
with fileio.open(os.path.join(self.uri, "X.npy"), "wb") as f:
np.save(f, bundle.X)
with fileio.open(os.path.join(self.uri, "y.npy"), "wb") as f:
np.save(f, bundle.y)
with fileio.open(os.path.join(self.uri, "meta.json"), "w") as f:
f.write(json.dumps({
"feature_names": bundle.feature_names,
"stats": bundle.stats,
}))

def extract_metadata(self, bundle):
classes, counts = np.unique(bundle.y, return_counts=True)
return {
"n_samples": int(bundle.X.shape[0]),
"n_features": int(bundle.X.shape[1]),
"class_distribution": {str(c): int(n) for c, n in zip(classes, counts)},
}

We import all necessary libraries and define a custom data container along with its materializer. We implement logic to save, load, and extract metadata from our dataset, enabling seamless artifact handling in ZenML. This ensures that our data is not only stored efficiently but also enriched with meaningful, queryable metadata.

@step(enable_cache=True)
def load_data() -> Annotated[DatasetBundle, "raw_dataset"]:
data = load_breast_cancer()
return DatasetBundle(
data.data, data.target, data.feature_names,
stats={"source": "sklearn.datasets.load_breast_cancer"},
)

@step
def split_and_scale(
bundle: DatasetBundle,
test_size: float = 0.2,
random_state: int = 42,
) -> Tuple[
Annotated[np.ndarray, "X_train"],
Annotated[np.ndarray, "X_test"],
Annotated[np.ndarray, "y_train"],
Annotated[np.ndarray, "y_test"],
]:
X_tr, X_te, y_tr, y_te = train_test_split(
bundle.X, bundle.y, test_size=test_size,
random_state=random_state, stratify=bundle.y,
)
scaler = StandardScaler().fit(X_tr)
X_tr, X_te = scaler.transform(X_tr), scaler.transform(X_te)
log_metadata(metadata={"train_size": len(X_tr), "test_size": len(X_te)})
return X_tr, X_te, y_tr, y_te

@step
def train_candidate(
X_train: np.ndarray,
y_train: np.ndarray,
model_type: str = "random_forest",
n_estimators: int = 100,
max_depth: int = 5,
) -> Annotated[Any, "candidate_model"]:
if model_type == "random_forest":
m = RandomForestClassifier(n_estimators=n_estimators,
max_depth=max_depth, random_state=42)
elif model_type == "gradient_boosting":
m = GradientBoostingClassifier(n_estimators=n_estimators,
max_depth=max_depth, random_state=42)
else:
m = LogisticRegression(max_iter=2000, random_state=42)
m.fit(X_train, y_train)
log_metadata(metadata={
"model_type": model_type,
"hyperparameters": {"n_estimators": n_estimators, "max_depth": max_depth},
})
return m

We define core pipeline steps for loading data, splitting it, scaling features, and training model candidates. We ensure that data loading is cached for efficiency while logging key metadata during preprocessing and training. This forms the backbone of our pipeline, where each model is trained independently with its respective configuration.

@step
def evaluate_candidate(
model: Any,
X_test: np.ndarray,
y_test: np.ndarray,
label: str,
) -> Annotated[Dict[str, Any], "metrics"]:
preds = model.predict(X_test)
probs = (model.predict_proba(X_test)[:, 1]
if hasattr(model, "predict_proba") else preds)
metrics: Dict[str, Any] = {
"accuracy": float(accuracy_score(y_test, preds)),
"f1":       float(f1_score(y_test, preds)),
"roc_auc":  float(roc_auc_score(y_test, probs)),
"label":    label,
}
log_metadata(metadata=metrics)
return metrics

@step
def select_best(
metrics_list: List[Dict[str, Any]],
models: List[Any],
) -> Annotated[Any, "production_model"]:
best_idx = max(range(len(metrics_list)),
key=lambda i: metrics_list[i]["roc_auc"])
best = metrics_list[best_idx]

ctx = get_step_context()
try:
ctx.model.log_metadata({"chosen_candidate": best,
"candidate_index": best_idx})
except Exception as e:
print(f"Could not log metadata: {e}")
return models[best_idx]

We evaluate each candidate model on the test set, recording metrics like accuracy, F1 score, and ROC AUC. Then we select the best model based on ROC AUC and log the decision metadata. Finally, we promote the selected model as the production model.

@pipeline
def advanced_training_pipeline(
test_size: float = 0.2,
random_state: int = 42,
):
bundle = load_data()
X_train, X_test, y_train, y_test = split_and_scale(
bundle, test_size=test_size, random_state=random_state
)

# Fan-out: train multiple candidates
models = []
configs = [
{"model_type": "random_forest", "n_estimators": 100, "max_depth": 5},
{"model_type": "random_forest", "n_estimators": 200, "max_depth": 10},
{"model_type": "gradient_boosting", "n_estimators": 100, "max_depth": 5},
{"model_type": "logistic_regression", "n_estimators": 0, "max_depth": 0},
]
for config in configs:
models.append(train_candidate(
X_train, y_train,
model_type=config["model_type"],
n_estimators=config["n_estimators"],
max_depth=config["max_depth"],
))

# Evaluate each candidate
metrics_list = []
for i, (model, config) in enumerate(zip(models, configs)):
label = f"{config['model_type']}_n_est_{config['n_estimators']}_depth_{config['max_depth']}"
metrics = evaluate_candidate(model, X_test, y_test, label=label)
metrics_list.append(metrics)

# Fan-in: select best
best_model = select_best(metrics_list, models)
return best_model

if __name__ == "__main__":
pipeline_instance = advanced_training_pipeline()
pipeline_instance.run()

We assemble the complete pipeline with a fan-out and fan-in pattern. The pipeline iterates over a set of hyperparameter configurations, trains each candidate, evaluates them, and selects the best model. Running the pipeline triggers the entire workflow with automatic caching and metadata logging.

This tutorial demonstrates how to build a production-grade ML pipeline using ZenML with custom materializers, comprehensive metadata tracking, and hyperparameter optimization. The resulting pipeline is fully reproducible, transparent, and efficient, suitable for real-world deployment.

React