ML engineering pipelines
Feature prep, batch inference, model-serving hooks, and production ML workflow glue.
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.
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 …
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.
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…
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.
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…
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.
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…
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.
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…
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.
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)))
…
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.
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…
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.
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…
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).
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…
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.