Train, test and save a first model

DevOps, Hands On30 minutesFreeSteps checked 23 November 2026By Cloud Hands On

In this task you'll see the whole machine learning lifecycle once: data, training, testing and a saved model.

A model is a function learnt from examples. Here it learns which SS Kaiser shop orders arrive late from distance, number of items, hour, weekend and warehouse. The lifecycle is always the same: get data, split off a test set the model never sees, train on the rest, evaluate on the test set, then save the model so something else can use it.

Always compare with a baseline: the score you'd get with no model at all, here always guessing the commonest answer. A model that only matches the baseline has learnt nothing. AUC (0.5 is guessing, 1.0 is perfect) shows how well it ranks risky orders above safe ones, which matters more than accuracy when one answer is much commoner.

Example. SS Kaiser's delivery team wanted to warn customers before a late delivery. A first model trained on a laptop in an afternoon scored an AUC of 0.78 against a baseline that was right 64% of the time, which was enough to justify building it properly.

Before you start

You need: Python 3.10 or newer, and about 500 MB of disk for MLflow and scikit-learn. No cloud account. Time: 30 minutes.

Where to look

  1. A new folder called mlops
  2. make_data.py
  3. train_basic.py
  4. A terminal

Steps

  1. Make a folder called mlops, open a terminal in it and run the set-up lines from Commands: a Python environment, switched on, with MLflow, scikit-learn and pandas installed.On Windows use py -m venv .venv if python isn't found.
  2. Save make_data.py and run the three data lines. It writes Example orders into a data folder: training orders, a holdout set and today's orders.The data is made up with a fixed seed, so your numbers match these steps.
  3. Save train_basic.py and run python train_basic.py. It prints accuracy about 0.72, AUC about 0.78 and a baseline accuracy about 0.64.The model beats the baseline, so it has learnt something real.
  4. See model.joblib and metrics.json in the folder: the saved model and its scores.
  5. Run it again: the same numbers, because the split uses a fixed random_state.Repeatable results are the first thing MLOps protects.

Commands

# One-off set-up, in a new folder called mlops
python -m venv .venv
# Windows:  .venv\Scripts\activate      macOS or Linux:  source .venv/bin/activate
pip install mlflow scikit-learn pandas

# make_data.py: makes an Example dataset of SS Kaiser shop orders, and whether each delivery was late.
# Made-up data with a fixed seed, so everyone gets the same file. --drift makes "next month's" orders look different.
import argparse, csv, os, random

p = argparse.ArgumentParser()
p.add_argument("--rows", type=int, default=5000)
p.add_argument("--seed", type=int, default=1)
p.add_argument("--drift", type=float, default=0.0, help="0 = like training data, 1 = a busy, far-away month")
p.add_argument("--out", default="data/orders.csv")
a = p.parse_args()
rng = random.Random(a.seed)
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)

with open(a.out, "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["distance_km", "items", "hour", "weekend", "warehouse", "late"])
    for _ in range(a.rows):
        distance = round(rng.gammavariate(2.0, 6.0 + 8.0 * a.drift), 1)       # drift: deliveries further away
        items = rng.randint(1, 8 + int(6 * a.drift))
        hour = rng.choice(range(8, 22)) if rng.random() > 0.3 * a.drift else rng.choice([17, 18, 19])
        weekend = int(rng.random() < 2 / 7)
        warehouse = rng.choice(["north", "south"])
        # drift also changes the pattern itself: a new courier fixes the south warehouse, and weekends get much busier
        risk = (-4.0 + 0.12 * distance + 0.18 * items + 1.2 * (hour >= 17)
                + (0.6 + 1.6 * a.drift) * weekend + (0.8 - 1.8 * a.drift) * (warehouse == "south"))
        late = int(rng.random() < 1 / (1 + 2.718281828 ** -risk))
        w.writerow([distance, items, hour, weekend, warehouse, late])
print(f"wrote {a.rows} rows to {a.out} (seed {a.seed}, drift {a.drift})")

# train_basic.py: the whole ML lifecycle in one small file: load, split, train, evaluate, save (task 1).
import json, sys
import joblib, pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

NUM, CAT = ["distance_km", "items", "hour", "weekend"], ["warehouse"]
df = pd.read_csv(sys.argv[1] if len(sys.argv) > 1 else "data/orders.csv")
X, y = df[NUM + CAT], df["late"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

model = Pipeline([
    ("prep", ColumnTransformer([("num", StandardScaler(), NUM), ("cat", OneHotEncoder(), CAT)])),
    ("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
metrics = {"accuracy": round(accuracy_score(y_test, model.predict(X_test)), 4),
           "auc": round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4),
           "baseline_accuracy": round(float(max(y_test.mean(), 1 - y_test.mean())), 4)}   # always guessing the commonest answer
joblib.dump(model, "model.joblib")
json.dump(metrics, open("metrics.json", "w"), indent=1)
print(metrics)

# Run it
python make_data.py                                              # 5,000 training orders
python make_data.py --rows 2000 --seed 7 --out data/holdout.csv  # a holdout set the model never trains on
python make_data.py --rows 1000 --seed 11 --out data/today.csv   # today's orders to score
python train_basic.py

Watch out for

Cost
Free: everything runs on your computer.
Security
Only load saved model files you made yourself: loading a pickled or joblib file can run code hidden inside it.
Common mistakes
Testing on the data you trained on, and reporting accuracy without a baseline.

Clean up

Keep the mlops folder for the next tasks in this section; delete it (and its .venv) at the end.

Words to know

Training set
The examples the model learns from.
Test set
Examples kept back to check the model on data it hasn't seen.
Baseline
The score with no real model, for example always guessing the commonest answer.
AUC
How well a model ranks positives above negatives: 0.5 is chance, 1.0 is perfect.

Tick off each step and track your progress in the guide.

Open this task in DevOps, Hands On

Keep going