Reference library

ML engineering pipelines

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

20 matches
ML engineering pipelines medium

Bayesian Optimization in Python: A Simplified Mock Implementation

A toy Bayesian optimization loop with a Gaussian process prior, expected improvement acquisition, and noisy sampling to find a function's minimum.

bayesian-optimization gaussian-process hyperparameter-tuning
Python
import random
import math

class BayesianOptimizer:
    def __init__(self, noise=0.1):
        self.noise = noise
        self.observations = []
    
    def objective(self, x):
        return (math.sin(3*x) + 0.5*x) / (1 + x**2)
    
    def gaussian_process_prior(self, x1, x2, length_scale=0.5):
        return math.…
11 0 Open
ML engineering pipelines easy

Build a Data Helper Class in Python for ML Pipelines

A beginner-friendly Python class that summarizes, filters, and exports ML dataset rows as JSON.

data-helper ml-pipeline json
Python
from typing import List, Dict, Any
import json

class DataHelper:
    """Beginner-friendly helpers for ML data pipelines."""
    
    def __init__(self, data: List[Dict[str, Any]]):
        self.data = data
        self.keys = list(data[0].keys()) if data else []
    
    def summary(self) -> Dict[str, Any]:
        "…
15 0 Open
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

Compare Model A vs Model B Metrics in Python

A script that simulates and compares metrics between two ML models, showing a formatted diff table for quick insight.

model comparison mock metrics
Python
import random


def compare_a_b(samples=5):
    """Mock comparison of model A vs model B predictions."""
    metrics = ["accuracy", "precision", "recall", "f1"]
    print(f"{'Metric':<12}{'Model A':>10}{'Model B':>10}{'Diff':>10}")
    print("-" * 42)

    random.seed(42)
    for metric in metrics:
        a = round(r…
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

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 medium

How to Build a Mock ML Pipeline with Prefect in Python

Create a lightweight Prefect flow with mock preprocessing, training, and evaluation tasks to prototype an ML pipeline end-to-end.

prefect machine-learning pipeline
Python
from prefect import task, flow
from datetime import datetime


@task
def preprocess_data(raw_value: float) -> float:
    """Mock preprocessing: normalize the input value."""
    return raw_value / 100.0


@task
def train_model(features: float) -> dict:
    """Mock training: return a fake model artifact."""
    return …
12 0 Open
ML engineering pipelines easy

How to Build a Mock Offline Feature Store in Python

Build an in-memory mock of an offline feature store with a dict-based FeatureStore class for storing and retrieving ML features by entity ID.

feature-store ml-pipeline mock
Python
from datetime import datetime
from collections import defaultdict


class FeatureStore:
    """Simple in-memory mock of an offline feature store."""

    def __init__(self):
        self._features = defaultdict(dict)

    def ingest(self, entity_id, feature_name, value, timestamp=None):
        ts = timestamp or datet…
14 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 medium

How to Build an sklearn Pipeline with ColumnTransformer in Python

A mock example showing how to chain preprocessing and a regression model into a single sklearn Pipeline, scaling numeric features and one-hot encoding categorical features with ColumnTransformer.

sklearn pipeline columntransformer
Python
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression

# Mock dataset
X = np.array([[1, 'red'], [2, 'blue'], [3, 'red'], [4, 'green'], [5, 'blue']], dtype=o…
13 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 medium

How to Create a Mock ONNX Model in Python

Build and export a minimal mock ONNX model with a Reshape and Gemm layer using the onnx helper API.

onnx model-export mlops
Python
import onnx
import numpy as np
from onnx import helper, TensorProto

def create_mock_model():
    # Define input and output tensors
    input_tensor = helper.make_tensor_value_info('input', TensorProto.FLOAT, [1, 3, 224, 224])
    output_tensor = helper.make_tensor_value_info('output', TensorProto.FLOAT, [1, 10])

   …
16 0 Open
ML engineering pipelines medium

How to Mock MLflow Model Registration in Python

Build a lightweight in-memory mock of MLflow's MlflowClient to test model registration, versioning, and stage transitions without a tracking server.

mlflow mocking model-registry
Python
from mlflow.tracking import MlflowClient
from mlflow.entities import ModelVersion, Model


class MockMlflowClient:
    """Minimal mock of MlflowClient's model registration methods."""
    
    def __init__(self):
        self.registered_models = {}
        self.model_versions = {}
    
    def register_model(self, mod…
14 0 Open
ML engineering pipelines medium

How to Mock a Kubeflow Pipeline in Python

Build a minimal in-memory mock of a Kubeflow pipeline DAG using dataclasses and OrderedDict to chain component functions.

kubeflow pipelines mlops
Python
from typing import Dict, Any
from dataclasses import dataclass, field
from collections import OrderedDict


@dataclass
class KubeflowPipelineMock:
    """A minimal mock of a Kubeflow pipeline DAG."""
    name: str
    components: OrderedDict[str, callable] = field(default_factory=OrderedDict)

    def add_component(se…
14 0 Open
ML engineering pipelines easy

How to Mock train_test_split in Python for Unit Testing

Build a lightweight mock of sklearn's train_test_split to unit test ML pipeline code without needing the full library or deterministic random state.

train_test_split mock unit-testing
Python
import numpy as np
from sklearn.model_selection import train_test_split
from unittest.mock import patch

def mock_train_test_split(X, y, test_size=0.25, random_state=None, **kwargs):
    """A simple mock implementation of train_test_split."""
    n_samples = len(X)
    n_test = int(n_samples * test_size)
    n_train =…
12 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 medium

How to Train a Gradient Boosting Regressor in Python

Build and evaluate a scikit-learn GradientBoostingRegressor on a synthetic dataset, printing test MSE and feature importances.

sklearn gradient-boosting regression
Python
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error

def train_gradient_boosting_mock():
    # Toy regression dataset
    np.random.seed(42)
    X = np.random.rand(100, 3) * 10
    y = 2 * X[:, 0] - 1.5 * X[:, 1] + 0.5 * X[:, 2] + np.random.normal(0,…
13 0 Open
ML engineering pipelines medium

Mock a Flyte ML workflow in Python

Build a lightweight mock of a Flyte ML pipeline with dataclasses and a simple execution loop that passes outputs between tasks.

flyte ml-pipeline dataclass
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import time


@dataclass
class FlyteTask:
    name: str
    inputs: Dict = field(default_factory=dict)
    outputs: Dict = field(default_factory=dict)

    def run(self) -> Dict:
        time.sleep(0.1)  # simulate work
        return sel…
16 0 Open
ML engineering pipelines medium

Training Pipeline Orchestration Mock DAG in Python

Build a mock DAG orchestrator that runs ML pipeline stages in dependency order using topological sorting (Kahn's algorithm).

dag pipeline topological-sort
Python
from collections import deque
from dataclasses import dataclass, field


@dataclass
class DAGNode:
    name: str
    task: callable
    dependencies: list[str] = field(default_factory=list)


class MockDAG:
    def __init__(self, nodes: list[DAGNode]):
        self.nodes = {n.name: n for n in nodes}
        self.execu…
13 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.