Reference library

ML engineering pipelines

Feature prep, batch inference, model-serving hooks, and production ML workflow glue.

26 matches
ML engineering pipelines easy

Build a Mock Random Forest Classifier in Python

Create a simple random-forest-like classifier with random majority voting between trees, including fit, predict, and predict_proba methods.

random forest mock machine learning
Python
import random


class MockRandomForest:
    def __init__(self, n_trees=10, random_state=42):
        self.n_trees = n_trees
        self.random_state = random_state
        self.classes_ = None
        self._class_counts = None
        random.seed(random_state)

    def fit(self, X, y):
        self.classes_ = sorted(…
13 0 Open
ML engineering pipelines easy

Champion Challenger Deployment Mock in Python

Simulates an A/B champion-challenger ML deployment workflow — comparing two mock model accuracies and deciding which to promote to production.

ml deployment champion-challenger
Python
import random
import time

class ModelMocker:
    def __init__(self, name="Model", accuracy=0.85):
        self.name = name
        self.accuracy = accuracy

    def predict(self, data):
        """Simulate prediction with some randomness."""
        time.sleep(0.005)  # simulate compute time
        return 1 if rando…
13 0 Open
ML engineering pipelines easy

Create a Minimal Great Expectations Suite Mock in Python

Build a small Python class that mimics a Great Expectations suite, storing and serializing column expectations as JSON.

great-expectations mock testing
Python
import json


class GreatExpectationsSuite:
    """A minimal mock of a Great Expectations suite."""

    def __init__(self, suite_name, expectations=None):
        self.suite_name = suite_name
        self.expectations = expectations or []

    def add_expectation(self, expectation_type, column=None, kwargs=None):
   …
11 0 Open
ML engineering pipelines easy

Grid Search Hyperparameters in Python

Perform exhaustive grid search over hyperparameter combinations using itertools.product and a scoring function.

grid-search hyperparameters itertools
Python
import itertools

def grid_search(param_grid, score_fn):
    """Perform exhaustive grid search over hyperparameter combinations."""
    keys = param_grid.keys()
    names = list(keys)
    values = [param_grid[name] for name in names]
    results = []

    for combination in itertools.product(*values):
        params =…
14 0 Open
ML engineering pipelines easy

How to Build a Data Validation Schema in Python

Create a lightweight validation schema using dataclasses and lambda validators to check fields in a dictionary.

validation dataclasses ml-pipelines
Python
import re
from dataclasses import dataclass, field
from typing import Any, Callable


@dataclass
class Field:
    name: str
    validator: Callable[[Any], bool]
    required: bool = True

    def validate(self, value: Any) -> bool:
        if not self.required and value is None:
            return True
        return …
12 0 Open
ML engineering pipelines easy

How to Build a Mock TFX Pipeline in Python

Simulate a TFX-style ML pipeline with simple Python functions to understand component orchestration, data flow, and artifact passing.

tfx ml-pipeline orchestration
Python
# Mock TFX pipeline to illustrate component orchestration

def CsvExampleGen(data_path):
    """Mock component: Simulates reading CSV data."""
    print(f"ExampleGen: Reading from {data_path}")
    return {"records": 100, "name": "examples"}

def StatisticsGen(example_artifact):
    """Mock component: Simulates genera…
15 0 Open
ML engineering pipelines easy

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.

zenml ml pipeline
Python
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 eva…
13 0 Open
ML engineering pipelines easy

How to Compute a Confusion Matrix in Python

Compute a multi-class confusion matrix from true and predicted labels using pure Python dictionaries and nested lists, then format it for readable output.

confusion-matrix classification ml-metrics
Python
from collections import defaultdict

def compute_confusion_matrix(y_true, y_pred, labels):
    """Compute confusion matrix using Python dicts and nested lists."""
    label_index = {label: i for i, label in enumerate(labels)}
    matrix = [[0] * len(labels) for _ in range(len(labels))]
    
    for true, pred in zip(y…
14 0 Open
ML engineering pipelines easy

How to Create a Mock Metaflow Flow in Python

Build a minimal Metaflow flow with two sequential steps that pass data between them using instance attributes.

metaflow ml-pipelines workflow
Python
from metaflow import FlowSpec, step, current


class MockFlow(FlowSpec):
    """A minimal Metaflow flow to demonstrate basic steps and branching."""

    @step
    def start(self):
        self.category = "mock"
        print(f"Start step for {self.category} flow")
        self.next(self.process)

    @step
    def pr…
15 0 Open
ML engineering pipelines easy

How to Define Dagster ML Assets in Python

Define a chain of Dagster software-defined assets that compute raw features, normalized features, and predictions for an ML pipeline.

dagster ml-pipeline asset
Python
from dagster import asset


@asset
def raw_features():
    return {"sepal_length": [5.1, 4.9, 6.2], "sepal_width": [3.5, 3.0, 3.4]}


@asset
def normalized_features(raw_features):
    values = raw_features["sepal_length"]
    mean = sum(values) / len(values)
    std = (sum((x - mean) ** 2 for x in values) / len(values…
13 0 Open
ML engineering pipelines easy

How to Do Random Search for Hyperparameter Tuning in Python

A mock random search that samples hyperparameter combinations from a grid and ranks them by a dummy score, with a reproducible seed.

hyperparameter random-search ml
Python
import random

# Mock random search over a small hyperparameter grid
param_grid = {
    "learning_rate": [0.001, 0.01, 0.1],
    "batch_size": [16, 32, 64],
    "num_layers": [1, 2, 3]
}

def random_search(grid, n_iter=5, seed=42):
    """Perform random search over a hyperparameter grid."""
    random.seed(seed)
    k…
13 0 Open
ML engineering pipelines easy

How to Evaluate Accuracy, Precision, and Recall in Python

Compute accuracy, precision, and recall for a binary classification model using scikit-learn's metrics functions.

metrics classification scikit-learn
Python
from sklearn.metrics import accuracy_score, precision_score, recall_score

if __name__ == "__main__":
    y_true = [0, 1, 1, 0, 1, 0, 1, 1]
    y_pred = [0, 1, 0, 0, 1, 0, 1, 1]

    accuracy = accuracy_score(y_true, y_pred)
    precision = precision_score(y_true, y_pred)
    recall = recall_score(y_true, y_pred)

   …
13 0 Open
ML engineering pipelines easy

How to Generate Experiment Tracking Run IDs in Python

Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.

run-ids experiment-tracking ml-pipelines
Python
import random
import string
import time

def generate_run_id(prefix="exp"):
    timestamp = time.strftime("%Y%m%d_%H%M%S")
    suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
    return f"{prefix}_{timestamp}_{suffix}"

if __name__ == "__main__":
    # Simulate tracking three experiment r…
13 0 Open
ML engineering pipelines easy

How to Impute Missing Values with Mean in Python

Replace None values in a list with the mean of the existing values using Python's statistics module.

imputation missing-data statistics
Python
import statistics
from statistics import mean


def impute_mean(values):
    """Replace None with the mean of the non-None values."""
    # Filter out None to compute the mean of existing values
    valid = [v for v in values if v is not None]
    if not valid:
        return values  # nothing to impute if all are Non…
14 0 Open
ML engineering pipelines easy

How to Load CSV Training Data in Python Without Pandas

Load CSV training data using Python's standard library and mock it with io.StringIO for testing, returning headers and rows as dictionaries.

csv ml-pipelines io-stringio
Python
import csv
from pathlib import Path


def load_csv_training_data(file_path: str | Path) -> tuple[list[str], list[dict[str, str]]]:
    """Load CSV training data and return headers plus rows as dictionaries."""
    with open(file_path, mode="r", newline="", encoding="utf-8") as csv_file:
        reader = csv.DictReader…
14 0 Open
ML engineering pipelines easy

How to Load, Save, and Split JSON Data in Python

Provides helper functions to load, save, and split JSON dictionary data for simple ML pipeline preprocessing.

json data-splitting ml-pipeline
Python
import json
from pathlib import Path


def load_json_data(file_path):
    """Load JSON data from a file, returning an empty dict if missing."""
    path = Path(file_path)
    if path.exists():
        with path.open("r", encoding="utf-8") as f:
            return json.load(f)
    return {}


def save_json_data(data, f…
13 0 Open
ML engineering pipelines easy

How to Mock MLflow log_params and log_metrics in Python

Use unittest.mock to patch MLflow's log_param and log_metric, run the training function, and verify logging calls without touching a real tracking server.

mlflow mock testing
Python
from unittest.mock import Mock, patch
import mlflow


def train_model():
    mlflow.log_param("learning_rate", 0.01)
    mlflow.log_param("epochs", 10)
    mlflow.log_metric("accuracy", 0.95)
    mlflow.log_metric("loss", 0.05)
    return "Training completed"


if __name__ == "__main__":
    with patch("mlflow.log_par…
15 0 Open
ML engineering pipelines easy

How to Mock Shadow Mode Inference in Python

Simulates running multiple candidate models in shadow mode by adding randomized delays and returning their outputs alongside a primary model's output.

ml-pipeline shadow-mode simulation
Python
import random
import time


def shadow_mode_inference(candidates, mock_delay=0.1):
    """
    Simulates running multiple candidate models in 'shadow mode'
    by adding tiny randomized delays and returning their outputs
    alongside the primary model's output.
    """
    primary_output = "primary: answer"
    shado…
13 0 Open
ML engineering pipelines easy

How to Run Batch Predictions with a Mock Model in Python

Build a lightweight mock model class and run predictions across a batch of samples, returning results as a plain Python list.

numpy batch ml
Python
import numpy as np

class MockModel:
    def __init__(self, weights):
        self.weights = np.array(weights)

    def predict(self, X):
        return X @ self.weights

def predict_batch(model, batch):
    """Run predictions for a batch of samples and return results as a list."""
    return model.predict(np.array(ba…
14 0 Open
ML engineering pipelines easy

How to Save and Load a Mock Model with Pickle and joblib in Python

Serialize a custom machine learning model to a .joblib file with joblib.dump, reload it, and run a prediction with joblib.load.

joblib pickle model-serialization
Python
import joblib
from pathlib import Path

class MockModel:
    def __init__(self, weights):
        self.weights = weights

    def predict(self, features):
        return sum(w * f for w, f in zip(self.weights, features))


def save_model_pickle(model, filepath):
    with open(filepath, "wb") as f:
        joblib.dump(…
16 0 Open
ML engineering pipelines easy

How to Simulate an Airflow ML Pipeline in Python

Mock an Airflow ML pipeline in plain Python by defining steps, simulating their execution with delays, and returning a success summary.

airflow ml pipeline
Python
from datetime import datetime, timedelta
import time


class MLPipeline:
    def __init__(self, pipeline_name):
        self.pipeline_name = pipeline_name
        self.steps = []

    def add_step(self, step_name, duration_seconds):
        self.steps.append({"name": step_name, "duration": duration_seconds})

    def …
13 0 Open
ML engineering pipelines easy

How to Trigger Model Retraining on Drift in Python

Automatically detects accuracy drift in a mock ML model and triggers retraining when performance falls below a threshold.

ml drift-detection retraining
Python
import random
import time

class MockModel:
    def __init__(self, name):
        self.name = name
        self.accuracy = 0.85
        self.version = 1

    def train(self, data_size):
        # Simulate training time and accuracy improvement
        time.sleep(0.1)
        drift = random.uniform(-0.02, 0.02)
       …
16 0 Open
ML engineering pipelines easy

How to do feature selection with VarianceThreshold in Python

This code demonstrates how to use scikit-learn's VarianceThreshold to remove low-variance features from a NumPy array, keeping only those that vary enough to be useful for modeling.

feature selection sklearn machine learning
Python
import numpy as np
from sklearn.feature_selection import VarianceThreshold

def main():
    # Mock dataset: 4 samples, 5 features
    X = np.array([
        [0.1, 0.2, 1.0, 1.0, 0.5],
        [0.2, 0.2, 0.0, 1.0, 0.4],
        [0.1, 0.2, 1.0, 1.0, 0.6],
        [0.3, 0.2, 1.0, 0.0, 0.5]
    ])

    # Select features w…
14 0 Open
ML engineering pipelines easy

How to implement a canary traffic split in Python

Route incoming traffic between stable and canary model or service versions using a weight-based random split with deterministic testing.

canary traffic-split random
Python
import random


def canary_route(service_name: str, canary_weight: float = 0.2) -> str:
    """Route traffic between stable and canary versions based on weight."""
    rng = random.Random(42)  # deterministic for reproducible demo
    if rng.random() < canary_weight:
        return f"{service_name}-canary"
    return …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

ML engineering pipelines — Python code examples

What you will find here

This page collects ml engineering pipelines snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.