Reference library

ML engineering pipelines

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

25 matches
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

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 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 medium

How to Detect Data Drift with PSI in Python

Calculate the Population Stability Index (PSI) in Python to compare expected vs actual distributions and detect data drift in machine learning pipelines.

data drift psi monitoring
Python
import numpy as np

def calculate_psi(expected, actual, buckets=10):
    """Calculate Population Stability Index (PSI) between two distributions."""
    # Create bucket edges based on expected distribution percentiles
    edges = np.percentile(expected, np.linspace(0, 100, buckets + 1))
    edges[-1] = np.inf  # Ensur…
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 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 medium

How to Mock Kedro Pipeline Nodes in Python

Create a modular Kedro pipeline with node functions, namespacing, and input/output mapping to mock pipeline execution locally.

kedro pipeline modular
Python
from kedro.pipeline import Pipeline, node
from kedro.pipeline.modular_pipeline import pipeline as modular_pipeline


def preprocess(data: list) -> list:
    """Clean data by removing None values."""
    return [item for item in data if item is not None]


def transform(data: list) -> list:
    """Add 1 to each numeric…
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 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 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 medium

How to Stage ML Model Workflows with Python Classes

Defines a Stage class to model ML pipeline stages with variants and mocks, printing grammar for Model, Staging, and Production stages.

ml-pipelines stages model-deployment
Python
class Stage:
    def __init__(self, name):
        self.name = name
        self.mocks = []
        self.variants = []

    def add_mock(self, mock_name):
        self.mocks.append(mock_name)

    def add_variant(self, variant_name, productions=()):
        self.variants.append((variant_name, list(productions)))

    …
12 0 Open
ML engineering pipelines medium

How to mock an artifact store with local paths in Python for ML pipelines

Create a temporary local artifact store with dummy files and metadata to test ML pipeline code without real storage.

ml-pipelines mock tempfile
Python
import tempfile
from pathlib import Path
import json


def create_artifact_store_mock(base_path: Path = None):
    """Create a local artifact store mock directory structure."""
    if base_path is None:
        base_path = Path(tempfile.mkdtemp())

    store_layout = {
        "artifacts": [
            {"name": "mode…
13 0 Open
ML engineering pipelines easy

Load CSV Training Data Without Pandas in Python

This code loads a CSV file into a list of dictionaries using only the standard library, ideal for small ML training data without heavy dependencies.

csv data-loading standard-library
Python
import csv
from pathlib import Path

def load_csv(path):
    """Load CSV file into list of dicts without pandas."""
    rows = []
    with open(path, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append(dict(row))
    return rows

if __name__ == "__m…
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 easy

One Hot Encode Categories in Python

Convert a list of categorical strings into one-hot encoded numeric vectors using pure Python and NumPy.

one-hot encoding categorical numpy
Python
import numpy as np

categories = ["red", "green", "blue", "red", "blue", "green", "red"]

unique = sorted(set(categories))
lookup = {cat: i for i, cat in enumerate(unique)}

one_hot = []
for cat in categories:
    row = [0] * len(unique)
    row[lookup[cat]] = 1
    one_hot.append(row)

print("Categories:", categories…
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.