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

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

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 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 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 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 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 ROC AUC in Python

Compute ROC AUC from scratch in Python using pairwise comparisons between positive and negative score distributions, ideal for testing ML models without sklearn.

machine-learning model-evaluation auc
Python
import random
from math import comb


def mock_roc_auc(scores, labels):
    """Compute mock ROC AUC by simulating a classifier's score distribution."""
    random.seed(42)
    n = len(labels)
    pos_scores = [scores[i] for i in range(n) if labels[i] == 1]
    neg_scores = [scores[i] for i in range(n) if labels[i] == …
12 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 PyTorch Model State Dict in Python

This code demonstrates how to save a PyTorch model's state dict to a file and load it back into a new model instance, verifying weights match.

pytorch state-dict model
Python
import torch
import torch.nn as nn

class SimpleNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(4, 8)
        self.fc2 = nn.Linear(8, 2)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        return self.fc2(x)

if __name__ == "__main__":
    model = Simp…
13 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 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 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 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
ML engineering pipelines medium

K-Fold Cross Validation in Python: A Simple Implementation

Implements k-fold cross validation from scratch, splitting data into folds and computing MSE scores for a baseline mean-predictor model.

cross-validation ml model-evaluation
Python
import random
from statistics import mean


def cross_validation_scores(data, labels, k=5, seed=42):
    random.seed(seed)
    indices = list(range(len(data)))
    random.shuffle(indices)
    fold_size = len(indices) // k
    folds = []
    for i in range(k):
        if i == k - 1:
            folds.append(indices[i *…
16 0 Open
ML engineering pipelines easy

Model registry version mock in Python

A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.

ml-engineering model-registry versioning
Python
class ModelRegistry:
    def __init__(self):
        self.models = {}

    def register(self, name, version, model_type, metrics=None):
        if name not in self.models:
            self.models[name] = []
        entry = {
            "version": version,
            "model_type": model_type,
            "metrics": m…
13 0 Open
ML engineering pipelines medium

Train Logistic Regression From Scratch in Python

Trains a binary logistic regression model using gradient descent on mock data, printing learned weights and probabilities.

logistic-regression machine-learning gradient-descent
Python
import numpy as np

# Mock data: 2 features, binary classification
X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
y = np.array([0, 0, 1, 1, 1])

# Add bias term (column of ones)
X_b = np.c_[np.ones((X.shape[0], 1)), X]

# Initialize parameters
theta = np.zeros(X_b.shape[1])

# Hyperparameters
learning_rate = 0…
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.