Skip to main content

End-to-End MLOps Tutorial in Python — Part 1: Set Up a Reproducible Machine Learning Project

· 37 min read
Jagdish Kumawat
Founder @ Dewiride

A model that scores well once on your laptop isn't yet a model you can run in production. Someone else has to be able to rebuild it, a server has to retrain it on new data, and you have to know when it stops being good enough. That work is called MLOps. In this first part you set up a bike-sharing demand project that anyone can clone and train to exactly the same result.

This is Part 1 of an 11-part series.

  1. Part 1: Set Up a Reproducible Machine Learning Project (you are here)
  2. Part 2: Version Data and Models with DVC (coming soon)
  3. Part 3: Build a Reproducible Training Pipeline with DVC (coming soon)
  4. Part 4: Validate Data in the Pipeline with Pandera (coming soon)
  5. Part 5: Track Pipeline Experiments with DVC and MLflow (coming soon)
  6. Part 6: Continuous Integration for Machine Learning with GitHub Actions (coming soon)
  7. Part 7: Serve the Model as an API with FastAPI and Docker (coming soon)
  8. Part 8: Continuous Delivery of the Model Image with GitHub Actions (coming soon)
  9. Part 9: Monitor Data Drift and Model Performance with Evidently (coming soon)
  10. Part 10: Automate Monitoring and Retraining with Prefect (coming soon)
  11. Part 11: Production Checklist and Recap (coming soon)

Every command and output on this page is real, captured while building the project.

What You'll Have at the End of the Series​

Each part adds one MLOps practice to the same project, with free, open-source tools on your own computer, plus GitHub for the automated checks. By the end of Part 11 you'll know how to:

  • make training reproducible: the same code, data and settings always give the same model (this part);
  • version your data and models with DVC, the way Git versions code (Part 2);
  • turn the training steps into a pipeline that reruns only what changed (Part 3);
  • check the data before training and stop the pipeline when it's wrong (Part 4);
  • track every experiment in MLflow and trace each model back to its code, data and settings (Part 5);
  • test every change automatically on GitHub before it's merged (Part 6);
  • serve the model as a web API in a Docker container that logs every prediction (Part 7);
  • package and release each new model automatically (Part 8);
  • detect when the world changes and the model starts to get worse (Part 9);
  • retrain on a schedule when the monitoring says so (Part 10);
  • run all of it safely, with a production checklist (Part 11).

A second series, coming later, does the same with Azure Machine Learning in the cloud.

What MLOps Is​

Google's MLOps guide defines it as "an ML engineering culture and practice that aims at unifying ML system development (Dev) and ML system operation (Ops)." In plain words: the habits and tools that take a model from one person's experiment to a service that keeps working.

It borrows a lot from DevOps, the way software teams build, test and release code. But machine learning adds two problems software doesn't have:

  • The data is part of the program. The same code trained on different data gives a different model, so data has to be versioned and checked like code.
  • Models decay. The guide puts it this way: "models can decay in more ways than conventional software systems". The world changes, the data changes with it, and a model that was right last year slowly gets worse.

That's why MLOps adds a third practice to continuous integration (CI) and continuous delivery (CD). Google calls it continuous training (CT): "concerned with automatically retraining and serving the models."

How Far Along a Team Is: the Maturity Levels​

The guide describes three levels:

LevelWhat it looks like
0: Manual process"Every step is manual, including data analysis, data preparation, model training, and validation." Models are handed over as files and rarely retrained
1: ML pipeline automationThe training steps run as an automated pipeline that retrains the model on new data, with automatic data and model checks
2: CI/CD pipeline automationThe pipeline itself is built, tested and deployed automatically whenever its code changes

Microsoft's MLOps maturity model splits the same journey into five levels, from "No MLOps" to "Full MLOps automated operations", where "Drift or regression signals trigger automatic retraining".

Most projects start at level 0. This series takes one project, step by step, to automated retraining with automated releases.

Where the Series Goes​

This part builds the first box: a project whose training run can be repeated exactly. Everything after it depends on that.

The Example Project​

The series is about MLOps, not about one model, so the model stays simple and the project grows around it. It predicts how many bikes a bike-sharing scheme rents in an hour.

  • The data: the UCI Bike Sharing dataset: two years of hourly rentals from Capital Bikeshare in Washington, D.C., with the weather and the calendar for each hour. Its file has 17,379 rows, from 1 January 2011 to 31 December 2012.
  • The target: cnt, the number of bikes rented in that hour.
  • The features: the season, month, hour, holiday and weekday flags, the weather type, temperature, "feels like" temperature, humidity and wind speed.
  • The model: a gradient boosting model from scikit-learn.

The dataset's own notes ask for this credit: Fanaee-T, Hadi, and Gama, Joao, "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence (2013), Springer. UCI publishes it under the CC BY 4.0 licence, as Fanaee-T, H. (2013). Bike Sharing [Dataset]. UCI Machine Learning Repository. https://doi.org/10.24432/C5W894.

Why This Data Suits an MLOps Series​

The model learns from 2011 and is then used on 2012, the months it has never seen. That's exactly the situation a deployed model is in:

A bar chart of bike rentals per month from January 2011 to December 2012. January to October 2011 are blue and labelled Training, November and December 2011 are orange and labelled Test, and all of 2012 is green and labelled Production. Rentals rise from about 38,000 in January 2011 to about 143,000 in June 2011, and reach about 219,000 in September 2012.

Demand swings with the seasons, and it grew a lot in 2012: an average of 143.8 rentals an hour in 2011, and 234.7 in 2012. A model trained on 2011 will really fall behind in 2012. Later parts catch that and retrain, with real data, nothing simulated.

What Reproducible Means Here​

A training run is reproducible when anyone, anywhere, can repeat it and get the same model. That takes four things pinned down:

PinnedHow this part does it
The Python version and every packageuv records Python 3.15 in .python-version and the exact version of each package in uv.lock
The dataThe download is checked against a SHA-256 checksum, so a changed file stops the run
The settingsEvery setting lives in one file, params.yaml, and is checked when it's read
The randomnessThe model gets a fixed random_state

At the end of this part you'll clone the project into a new folder, rebuild it and train again, and Git will confirm that the result didn't change by a single digit.

Versions Used​

ToolVersion
Python3.15.2
uv0.13.10
scikit-learn1.9.1
pandas3.1.1
pydantic2.14.4
PyYAML6.0.4
skops0.16.0
Git2.56.1

What This Part Costs​

Nothing. Python, uv, Git and every package in this part are free, open-source software, and everything runs on your own computer.

Prerequisites​

  • uv, which creates Python projects and installs packages. It also downloads Python 3.15 for you if your computer doesn't have it; uv's documentation says "By default, uv will automatically download Python versions if they cannot be found on the system." Check uv:
Terminal
uv --version
Output
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
  • Git, to commit and clone the project. Check it:
Terminal
git --version
Output
git version 2.56.1
  • An internet connection, for the packages and the dataset.

Every command on this page works the same in Terminal (macOS), PowerShell (Windows) and Linux shells, unless a step shows a tab for each.

Step 1: Create the Project​

Open a terminal in the folder where you keep your code, for example a source folder in your home folder, and create the project:

Terminal
uv init --package --name bike-demand-forecast --python 3.15 dewiride-bike-demand-forecast
Output
Initialized project `bike-demand-forecast` at `/Users/you/source/dewiride-bike-demand-forecast`

The terminal after uv init: Initialized project bike-demand-forecast at /Users/you/source/dewiride-bike-demand-forecast.

OptionWhat it does
--packageCreates an installable package with a src/ folder, the layout production projects use
--name bike-demand-forecastThe package's name; its code lives in src/bike_demand_forecast
--python 3.15Requires Python 3.15 or newer, and writes 3.15 to a .python-version file
dewiride-bike-demand-forecastThe folder to create

How to Create a Python Project with uv explains every uv init option. uv also made the folder a Git repository. Move into it and name its branch main, the name GitHub uses, before the first commit:

Terminal
cd dewiride-bike-demand-forecast
git branch -m main

git branch -m main prints nothing. Your project now looks like this:

dewiride-bike-demand-forecast/
dewiride-bike-demand-forecast/
├── .git/
├── .gitignore
├── .python-version 3.15
├── README.md
├── pyproject.toml
└── src/
└── bike_demand_forecast/
└── __init__.py

.python-version is the first pin: whoever runs this project gets Python 3.15.

Step 2: Add the Packages​

The project needs pandas to read the data, scikit-learn to train the model, skops to save it safely, PyYAML to read the settings file and pydantic to check it:

Terminal
uv add pandas scikit-learn skops pyyaml pydantic
Output
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 21 packages in 1.70s
Built bike-demand-forecast @ file:///Users/you/source/dewiride-bike-demand-forecast
Prepared 21 packages in 5.26s
Installed 21 packages in 87ms
+ annotated-types==0.8.0
+ bike-demand-forecast==0.1.0 (from file:///Users/you/source/dewiride-bike-demand-forecast)
+ cloudpickle==3.1.3
+ joblib==1.6.0
+ narwhals==2.30.0
+ numpy==2.5.5
+ packaging==26.4
+ pandas==3.1.1
+ prettytable==3.19.0
+ pydantic==2.14.4
+ pydantic-core==2.50.5
+ python-dateutil==4.0.0
+ pyyaml==6.0.4
+ scikit-learn==1.9.1
+ scipy==1.18.1
+ skops==0.16.0
+ threadpoolctl==3.8.0
+ typing-extensions==4.16.0
+ typing-inspection==0.4.5
+ tzdata==2026.6
+ wcwidth==0.9.5

The terminal after uv add: uv used CPython 3.15.2, created .venv, resolved 21 packages and installed them, including pandas 3.1.1, scikit-learn 1.9.1, skops 0.16.0, pyyaml 6.0.4 and pydantic 2.14.4.

uv created a virtual environment in .venv, installed the five packages and the 16 they depend on, and wrote two files:

  • pyproject.toml now lists the five packages, with a minimum version for each.
  • uv.lock records the exact version of all 21, the second pin. Whoever installs from it gets these versions, not whatever is newest that day.

How to Add a Package to a Python Project with uv covers uv add in detail. Your versions may be newer than these if you run it later; your own uv.lock will pin whatever you get.

Step 3: Put Every Setting in params.yaml​

Every value a run depends on goes into one file: where the data comes from, how the data is split, and the model's settings. Then a change to any of them shows up in Git, and no setting hides inside the code. Create params.yaml in the project's top folder:

params.yaml
# Every setting the bike demand pipeline uses.
# Change values here, never in the code, so each change shows up in Git.

data:
url: https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip
sha256: "b70182d0d0508e9abbb79306ce5c0cec34869000f8220175ac83d11dbe845401"
file: hour.csv

split:
train_end: 2011-10-31 # the model learns from every hour up to this day
test_end: 2011-12-31 # and is scored on the hours after it, up to this day

model:
learning_rate: 0.1
max_iter: 300
max_leaf_nodes: 31
min_samples_leaf: 20
early_stopping: false
random_state: 42

params.yaml in a macOS-style code window: a data section with the dataset's url, its sha256 checksum and the file hour.csv; a split section with train_end 2011-10-31 and test_end 2011-12-31; and a model section with learning_rate, max_iter, max_leaf_nodes, min_samples_leaf, early_stopping false and random_state 42.

  • data: the dataset's zip file on UCI's site, the SHA-256 checksum the download must match, and the file inside the zip to use. I took the checksum from the official zip; it's the third pin. It's in double quotes so that YAML always reads it as text: a checksum made only of digits would otherwise turn into a number, as Fixed: "Input should be a valid string" When pydantic Reads a Number from YAML shows.
  • split: the model learns from January to October 2011 and is tested on November and December 2011. 2012 stays unseen.
  • model: the model's settings, passed to scikit-learn as they are. random_state: 42 is the fourth pin, and early_stopping: false is explained in Step 7.

Step 4: Check the Settings When They're Read​

A typo in params.yaml should stop the program at once with a clear message, not cause a strange result an hour later. pydantic models describe each section of the file, its types and its limits. How to Validate a YAML Settings File in Python with pydantic shows the technique on its own. Create src/bike_demand_forecast/params.py, starting with a base class for every section:

src/bike_demand_forecast/params.py
"""Read params.yaml and check every value before the pipeline uses it."""

from datetime import date
from pathlib import Path
from typing import Self

import yaml
from pydantic import BaseModel, ConfigDict, Field, model_validator

PARAMS_FILE = Path("params.yaml")


class Section(BaseModel):
"""A section of params.yaml: an unknown or misspelled key is an error."""

model_config = ConfigDict(extra="forbid")

extra="forbid" makes every section refuse keys it doesn't know, so learning_rat: 0.1 fails instead of being ignored while the model quietly uses its default.

Add one model per section of the file, below it:

src/bike_demand_forecast/params.py (add below Section)
class DataParams(Section):
url: str = Field(pattern=r"^https://")
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
file: str = Field(min_length=1)


class SplitParams(Section):
train_end: date
test_end: date

@model_validator(mode="after")
def test_comes_after_train(self) -> Self:
if self.test_end <= self.train_end:
raise ValueError("test_end must be later than train_end")
return self


class ModelParams(Section):
learning_rate: float = Field(gt=0)
max_iter: int = Field(gt=0)
max_leaf_nodes: int = Field(ge=2)
min_samples_leaf: int = Field(ge=1)
early_stopping: bool
random_state: int
  • DataParams accepts only an https:// address and a checksum of exactly 64 hexadecimal characters.
  • SplitParams reads the two dates (YAML hands them over as real dates) and checks, in test_comes_after_train, that the test period comes after the training period.
  • ModelParams sets a lower limit on each number and requires early_stopping to be true or false.

Finish the file with the model for the whole file and the function that reads it:

src/bike_demand_forecast/params.py (add at the end)
class Params(Section):
data: DataParams
split: SplitParams
model: ModelParams


def load_params(path: Path = PARAMS_FILE) -> Params:
"""Read the parameters file. Any wrong value raises a ValidationError."""
with path.open(encoding="utf-8") as file:
return Params.model_validate(yaml.safe_load(file))

yaml.safe_load reads the file into dictionaries, and Params.model_validate checks all of it, section by section. Here's the complete file:

src/bike_demand_forecast/params.py
"""Read params.yaml and check every value before the pipeline uses it."""

from datetime import date
from pathlib import Path
from typing import Self

import yaml
from pydantic import BaseModel, ConfigDict, Field, model_validator

PARAMS_FILE = Path("params.yaml")


class Section(BaseModel):
"""A section of params.yaml: an unknown or misspelled key is an error."""

model_config = ConfigDict(extra="forbid")


class DataParams(Section):
url: str = Field(pattern=r"^https://")
sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
file: str = Field(min_length=1)


class SplitParams(Section):
train_end: date
test_end: date

@model_validator(mode="after")
def test_comes_after_train(self) -> Self:
if self.test_end <= self.train_end:
raise ValueError("test_end must be later than train_end")
return self


class ModelParams(Section):
learning_rate: float = Field(gt=0)
max_iter: int = Field(gt=0)
max_leaf_nodes: int = Field(ge=2)
min_samples_leaf: int = Field(ge=1)
early_stopping: bool
random_state: int


class Params(Section):
data: DataParams
split: SplitParams
model: ModelParams


def load_params(path: Path = PARAMS_FILE) -> Params:
"""Read the parameters file. Any wrong value raises a ValidationError."""
with path.open(encoding="utf-8") as file:
return Params.model_validate(yaml.safe_load(file))

The complete params.py in a macOS-style code window: the Section base class with extra="forbid", the DataParams, SplitParams and ModelParams models with their checks, the Params model and the load_params function.

Step 5: Load the Data and Split It by Date​

The data is hourly and happens over time, so it can't be split at random: a random split would let the model learn from December and then be tested on November. The split is by date instead, at train_end. How to Split Time Series Data into Training and Test Sets by Date shows why with a small example.

Not every column may be used, either. In this dataset, casual and registered count the two kinds of riders, and they add up to cnt on every row, so a model given them would simply add them up. yr says which year it is, so a model trained on 2011 alone has nothing to learn from it. instant is a row number. Create src/bike_demand_forecast/data.py, starting with the settings it shares with the other files:

src/bike_demand_forecast/data.py
"""Load the hourly rentals and split them into a training period and a test period."""

from datetime import date
from pathlib import Path

import pandas as pd

RAW_DIR = Path("data/raw")
TARGET = "cnt"

# The columns the model learns from. Left out: instant (a row number), dteday (used
# only to split), yr (which year it is), and casual and registered, which add up to
# cnt and would give the answer away.
FEATURES = [
"season",
"mnth",
"hr",
"holiday",
"weekday",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
]

Then the two functions, below it:

src/bike_demand_forecast/data.py (add at the end)
def load_rentals(path: Path) -> pd.DataFrame:
"""Read the hourly CSV file, with dteday as a real date."""
return pd.read_csv(path, parse_dates=["dteday"])


def split_by_date(
rentals: pd.DataFrame, train_end: date, test_end: date
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Train on the hours up to train_end; test on the hours after it, to test_end."""
day = rentals["dteday"]
train = rentals[day <= pd.Timestamp(train_end)]
test = rentals[(day > pd.Timestamp(train_end)) & (day <= pd.Timestamp(test_end))]
return train, test
  • load_rentals reads the CSV file with dteday as a real date, so it can be compared.
  • split_by_date keeps the hours up to train_end for training and the hours after it, up to test_end, for testing. The dates from params.yaml are Python dates, and pandas 3 won't compare them with a date column directly, so pd.Timestamp converts them first.

Here's the complete file:

src/bike_demand_forecast/data.py
"""Load the hourly rentals and split them into a training period and a test period."""

from datetime import date
from pathlib import Path

import pandas as pd

RAW_DIR = Path("data/raw")
TARGET = "cnt"

# The columns the model learns from. Left out: instant (a row number), dteday (used
# only to split), yr (which year it is), and casual and registered, which add up to
# cnt and would give the answer away.
FEATURES = [
"season",
"mnth",
"hr",
"holiday",
"weekday",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
]


def load_rentals(path: Path) -> pd.DataFrame:
"""Read the hourly CSV file, with dteday as a real date."""
return pd.read_csv(path, parse_dates=["dteday"])


def split_by_date(
rentals: pd.DataFrame, train_end: date, test_end: date
) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Train on the hours up to train_end; test on the hours after it, to test_end."""
day = rentals["dteday"]
train = rentals[day <= pd.Timestamp(train_end)]
test = rentals[(day > pd.Timestamp(train_end)) & (day <= pd.Timestamp(test_end))]
return train, test

The complete data.py in a macOS-style code window: RAW_DIR, TARGET and the FEATURES list with a comment about the columns left out, then load_rentals and split_by_date.

Step 6: Write the Download Command​

The download command fetches the zip file, refuses it unless its SHA-256 checksum matches the one in params.yaml, and saves the CSV file from inside it. Create src/bike_demand_forecast/download.py, starting with the imports and the logger:

src/bike_demand_forecast/download.py
"""Download the dataset, check its SHA-256 checksum and save the CSV file."""

import hashlib
import io
import logging
import sys
import urllib.error
import urllib.request
import zipfile

from bike_demand_forecast.data import RAW_DIR
from bike_demand_forecast.params import load_params

log = logging.getLogger(__name__)

Then the main function, which the command runs. First it downloads the zip file into memory, and stops with a clear message if the network fails:

src/bike_demand_forecast/download.py (add at the end)
def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params().data

log.info("Downloading %s", params.url)
try:
with urllib.request.urlopen(params.url, timeout=60) as response:
archive = response.read()
except urllib.error.URLError as error:
log.error("Download failed: %s", error)
sys.exit(1)

Next, inside main, the check that pins the data. If the file isn't byte for byte the one the checksum was taken from, the command stops with exit code 1:

src/bike_demand_forecast/download.py (add inside main)
checksum = hashlib.sha256(archive).hexdigest()
if checksum != params.sha256:
log.error("Checksum mismatch: expected %s, got %s", params.sha256, checksum)
sys.exit(1)
log.info("Checksum matches: %s", checksum)

Last, inside main, it opens the zip file from memory, takes out hour.csv and saves it in data/raw:

src/bike_demand_forecast/download.py (add inside main)
with zipfile.ZipFile(io.BytesIO(archive)) as zip_file:
content = zip_file.read(params.file)

RAW_DIR.mkdir(parents=True, exist_ok=True)
target = RAW_DIR / params.file
target.write_bytes(content)
log.info("Saved %s (%d bytes)", target.as_posix(), len(content))

as_posix() prints the path with forward slashes on every system, so the message reads the same on Windows. Here's the complete file:

src/bike_demand_forecast/download.py
"""Download the dataset, check its SHA-256 checksum and save the CSV file."""

import hashlib
import io
import logging
import sys
import urllib.error
import urllib.request
import zipfile

from bike_demand_forecast.data import RAW_DIR
from bike_demand_forecast.params import load_params

log = logging.getLogger(__name__)


def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params().data

log.info("Downloading %s", params.url)
try:
with urllib.request.urlopen(params.url, timeout=60) as response:
archive = response.read()
except urllib.error.URLError as error:
log.error("Download failed: %s", error)
sys.exit(1)

checksum = hashlib.sha256(archive).hexdigest()
if checksum != params.sha256:
log.error("Checksum mismatch: expected %s, got %s", params.sha256, checksum)
sys.exit(1)
log.info("Checksum matches: %s", checksum)

with zipfile.ZipFile(io.BytesIO(archive)) as zip_file:
content = zip_file.read(params.file)

RAW_DIR.mkdir(parents=True, exist_ok=True)
target = RAW_DIR / params.file
target.write_bytes(content)
log.info("Saved %s (%d bytes)", target.as_posix(), len(content))

The complete download.py in a macOS-style code window: the imports, a logger, and a main function that downloads the zip file, checks its SHA-256 checksum against params.yaml, and saves hour.csv into data/raw.

Step 7: Write the Training Command​

The training command reads the settings and the data, splits them, trains the model, scores it on the test period and saves two files: the model, and its scores. Create src/bike_demand_forecast/train.py, starting with the imports and the two output files:

src/bike_demand_forecast/train.py
"""Train the demand model on the training period and score it on the test period."""

import json
import logging
from pathlib import Path

import skops.io as sio
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score, root_mean_squared_error

from bike_demand_forecast.data import (
FEATURES,
RAW_DIR,
TARGET,
load_rentals,
split_by_date,
)
from bike_demand_forecast.params import load_params

MODEL_FILE = Path("models/model.skops")
METRICS_FILE = Path("metrics.json")

log = logging.getLogger(__name__)

Then main, which loads, splits, trains and predicts:

src/bike_demand_forecast/train.py (add at the end)
def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params()

rentals = load_rentals(RAW_DIR / params.data.file)
train, test = split_by_date(rentals, params.split.train_end, params.split.test_end)
log.info("Training on %d hours, testing on %d hours", len(train), len(test))

model = HistGradientBoostingRegressor(**params.model.model_dump())
model.fit(train[FEATURES], train[TARGET])
predicted = model.predict(test[FEATURES])

params.model.model_dump() turns the model section into a dictionary, and ** passes each entry as a setting of HistGradientBoostingRegressor, so the model's settings come only from params.yaml. How to Train a Gradient Boosting Regression Model with HistGradientBoostingRegressor covers the model itself.

Two of those settings exist for reproducibility:

  • random_state: 42 fixes the model's random choices. How to Get the Same Results Every Run with random_state in scikit-learn shows what happens without it.
  • early_stopping: false is there because the default, "auto", turns early stopping on by itself once the training data has more than 10,000 rows. The training period has 7,185 hours today, but retraining on more months in later parts would pass 10,000 and change how the model trains, without any change to the code or the settings. Writing it down keeps that decision in params.yaml.

Last, inside main, the scores and the two files:

src/bike_demand_forecast/train.py (add inside main)
metrics = {
"mae": round(mean_absolute_error(test[TARGET], predicted), 4),
"rmse": round(root_mean_squared_error(test[TARGET], predicted), 4),
"r2": round(r2_score(test[TARGET], predicted), 4),
}
MODEL_FILE.parent.mkdir(parents=True, exist_ok=True)
sio.dump(model, MODEL_FILE)
METRICS_FILE.write_text(json.dumps(metrics, indent=2) + "\n")
log.info("Saved %s and %s", MODEL_FILE.as_posix(), METRICS_FILE)
log.info("Test MAE %.2f, RMSE %.2f, R2 %.4f", *metrics.values())

Here's the complete file:

src/bike_demand_forecast/train.py
"""Train the demand model on the training period and score it on the test period."""

import json
import logging
from pathlib import Path

import skops.io as sio
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score, root_mean_squared_error

from bike_demand_forecast.data import (
FEATURES,
RAW_DIR,
TARGET,
load_rentals,
split_by_date,
)
from bike_demand_forecast.params import load_params

MODEL_FILE = Path("models/model.skops")
METRICS_FILE = Path("metrics.json")

log = logging.getLogger(__name__)


def main() -> None:
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s: %(message)s"
)
params = load_params()

rentals = load_rentals(RAW_DIR / params.data.file)
train, test = split_by_date(rentals, params.split.train_end, params.split.test_end)
log.info("Training on %d hours, testing on %d hours", len(train), len(test))

model = HistGradientBoostingRegressor(**params.model.model_dump())
model.fit(train[FEATURES], train[TARGET])
predicted = model.predict(test[FEATURES])

metrics = {
"mae": round(mean_absolute_error(test[TARGET], predicted), 4),
"rmse": round(root_mean_squared_error(test[TARGET], predicted), 4),
"r2": round(r2_score(test[TARGET], predicted), 4),
}
MODEL_FILE.parent.mkdir(parents=True, exist_ok=True)
sio.dump(model, MODEL_FILE)
METRICS_FILE.write_text(json.dumps(metrics, indent=2) + "\n")
log.info("Saved %s and %s", MODEL_FILE.as_posix(), METRICS_FILE)
log.info("Test MAE %.2f, RMSE %.2f, R2 %.4f", *metrics.values())

The complete train.py in a macOS-style code window: imports, MODEL_FILE and METRICS_FILE, and a main function that loads the settings and the data, splits them by date, trains a HistGradientBoostingRegressor from params.model, and saves the model and metrics.json.

Step 8: Register the Two Commands​

uv init gave the project one sample command. Open pyproject.toml and replace its [project.scripts] section with the two commands this project needs:

pyproject.toml ([project.scripts])
[project.scripts]
download = "bike_demand_forecast.download:main"
train = "bike_demand_forecast.train:main"

The [project.scripts] section of pyproject.toml in a macOS-style code window: download runs bike_demand_forecast.download and train runs bike_demand_forecast.train.

Each line names a command and the function it runs. How to Run a Python Script with uv run shows how uv run finds these commands. The sample command pointed at a main function in __init__.py, which is no longer needed, so replace that file's contents with one line that describes the package:

src/bike_demand_forecast/__init__.py
"""Bike-sharing demand forecast: an end-to-end MLOps example project."""

While you have pyproject.toml open, you can also replace its description with one that says what the project does, as I did: "Forecast hourly bike-sharing demand, built with MLOps practices".

Step 9: Download the Data​

Terminal
uv run download
Output
Built bike-demand-forecast @ file:///Users/you/source/dewiride-bike-demand-forecast
Uninstalled 1 package in 1ms
Installed 1 package in 2ms
INFO bike_demand_forecast.download: Downloading https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip
INFO bike_demand_forecast.download: Checksum matches: b70182d0d0508e9abbb79306ce5c0cec34869000f8220175ac83d11dbe845401
INFO bike_demand_forecast.download: Saved data/raw/hour.csv (1156736 bytes)

The terminal after uv run download: uv rebuilt the project, then the command downloaded the zip file, confirmed that its checksum matches, and saved data/raw/hour.csv with 1,156,736 bytes.

The first three lines are uv rebuilding the project, because pyproject.toml changed. Then the command did its three jobs: downloaded the zip file, confirmed the checksum, and saved data/raw/hour.csv. Look at the first rows of the file:

Terminal
head -n 3 data/raw/hour.csv
Output
instant,dteday,season,yr,mnth,hr,holiday,weekday,workingday,weathersit,temp,atemp,hum,windspeed,casual,registered,cnt
1,2011-01-01,1,0,1,0,0,6,0,1,0.24,0.2879,0.81,0,3,13,16
2,2011-01-01,1,0,1,1,0,6,0,1,0.22,0.2727,0.8,0,8,32,40

The first three lines of hour.csv: the header with instant, dteday, season and the other columns up to cnt, then the rows for midnight and 1 am on 1 January 2011, with 16 and 40 rentals.

Both shells print the same three lines. One row per hour: in the first hour of 2011, 3 casual riders and 13 registered riders rented bikes, 16 in all. The weather values are scaled to between 0 and 1.

Step 10: Train the Model​

Terminal
uv run train
Output
INFO bike_demand_forecast.train: Training on 7185 hours, testing on 1460 hours
INFO bike_demand_forecast.train: Saved models/model.skops and metrics.json
INFO bike_demand_forecast.train: Test MAE 32.56, RMSE 51.77, R2 0.8011

Then look at the scores it saved:

Terminal
cat metrics.json
Output
{
"mae": 32.5558,
"rmse": 51.7738,
"r2": 0.8011
}

The terminal after uv run train and cat metrics.json: training on 7,185 hours and testing on 1,460, the model and metrics saved, and the scores MAE 32.5558, RMSE 51.7738 and R2 0.8011.

The model trained on 7,185 hours, January to October 2011, and was tested on 1,460 hours, November and December 2011. On the test hours, its predictions were off by 32.56 bikes on average, and it explained about 80 % of the variation in demand (R² 0.8011). That's the first baseline; later parts track how it changes. cat works in PowerShell too.

Step 11: Keep Data and Models Out of Git, Then Commit​

The data can be downloaded again and the model trained again, so neither belongs in Git; Part 2 versions them with a tool made for large files. Open .gitignore, which uv created, and add two lines at the end:

.gitignore (add at the end)
# Data and models: the pipeline downloads and creates them
/data/
/models/

How to Ignore a Folder in Git with .gitignore explains the slashes. Check what Git would add:

Terminal
git status
Output
On branch main

No commits yet

Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
.python-version
README.md
metrics.json
params.yaml
pyproject.toml
src/
uv.lock

nothing added to commit but untracked files present (use "git add" to track)

The terminal after git status: on branch main with no commits yet, and eight untracked entries: .gitignore, .python-version, README.md, metrics.json, params.yaml, pyproject.toml, src and uv.lock. The data and models folders aren't listed.

data/ and models/ aren't listed. Everything a run needs is: the code, params.yaml, .python-version and uv.lock. metrics.json is there too, on purpose: committing it means Git can tell you later whether a run changed the results. How to See What Changed in a Git Repository Before You Commit (git status and git diff) explains this output. Commit it all:

Terminal
git add .
git commit -m "Set up a reproducible bike demand forecast project"
Output
[main (root-commit) d8022ef] Set up a reproducible bike demand forecast project
12 files changed, 634 insertions(+)
create mode 100644 .gitignore
create mode 100644 .python-version
create mode 100644 README.md
create mode 100644 metrics.json
create mode 100644 params.yaml
create mode 100644 pyproject.toml
create mode 100644 src/bike_demand_forecast/__init__.py
create mode 100644 src/bike_demand_forecast/data.py
create mode 100644 src/bike_demand_forecast/download.py
create mode 100644 src/bike_demand_forecast/params.py
create mode 100644 src/bike_demand_forecast/train.py
create mode 100644 uv.lock

The terminal after git commit: the root commit d8022ef on main with 12 files and 634 lines added, from .gitignore to uv.lock.

Your commit gets its own hash; mine was d8022ef. How to Create a Git Repository and Make Your First Commit covers git add and git commit.

Step 12: Rebuild the Project from a Clean Copy​

This is the test of everything above: does someone who starts from the commit alone get the same model? Clone the project into a new folder next to it. The clone has only what you committed: no .venv, no data, no model.

Terminal
cd ..
git clone dewiride-bike-demand-forecast bike-demand-check
cd bike-demand-check
Output
Cloning into 'bike-demand-check'...
done.

How to Clone a Local Git Repository into Another Folder explains this command. Now install exactly the locked versions:

Terminal
uv sync --locked
Output
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Resolved 21 packages in 10ms
Built bike-demand-forecast @ file:///Users/you/source/bike-demand-check
Prepared 1 package in 19ms
Installed 21 packages in 212ms
+ annotated-types==0.8.0
+ bike-demand-forecast==0.1.0 (from file:///Users/you/source/bike-demand-check)
+ cloudpickle==3.1.3
+ joblib==1.6.0
+ narwhals==2.30.0
+ numpy==2.5.5
+ packaging==26.4
+ pandas==3.1.1
+ prettytable==3.19.0
+ pydantic==2.14.4
+ pydantic-core==2.50.5
+ python-dateutil==4.0.0
+ pyyaml==6.0.4
+ scikit-learn==1.9.1
+ scipy==1.18.1
+ skops==0.16.0
+ threadpoolctl==3.8.0
+ typing-extensions==4.16.0
+ typing-inspection==0.4.5
+ tzdata==2026.6
+ wcwidth==0.9.5

--locked installs the versions in uv.lock and would stop with an error if the lock didn't match pyproject.toml. The same 21 packages, at the same versions, came back. How to Install the Exact Locked Versions with uv sync --locked covers --locked in detail. Then download and train, exactly as before:

Terminal
uv run download
uv run train
Output
INFO bike_demand_forecast.download: Downloading https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip
INFO bike_demand_forecast.download: Checksum matches: b70182d0d0508e9abbb79306ce5c0cec34869000f8220175ac83d11dbe845401
INFO bike_demand_forecast.download: Saved data/raw/hour.csv (1156736 bytes)
INFO bike_demand_forecast.train: Training on 7185 hours, testing on 1460 hours
INFO bike_demand_forecast.train: Saved models/model.skops and metrics.json
INFO bike_demand_forecast.train: Test MAE 32.56, RMSE 51.77, R2 0.8011

Training wrote a new metrics.json in the clone. Ask Git whether it differs from the committed one:

Terminal
git status
Output
On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean

The clone's terminal: download confirmed the same checksum, training reported the same 7,185 and 1,460 hours and the same MAE 32.56, RMSE 51.77 and R2 0.8011, and git status says nothing to commit, working tree clean.

"nothing to commit, working tree clean": the new metrics.json is identical to the committed one, digit for digit. Same Python, same packages, same data, same settings, same model results. That's a reproducible training run.

The model file itself isn't byte-for-byte identical

Git ignores models/, so it didn't compare the model files, and they would differ: skops writes Python object ids and the time of saving into every file, so the same model saved twice gives two different files. The model inside is the same, and so are its scores. Why a skops File Changes Every Time You Save the Same Model shows it. That's why this series judges a model by its results, as metrics.json does here, and not by its file's hash.

Your Project Now Looks Like This​

dewiride-bike-demand-forecast/
dewiride-bike-demand-forecast/
├── .git/
├── .gitignore ignores .venv, data/ and models/
├── .python-version 3.15
├── .venv/ the packages (ignored)
├── README.md
├── data/
│ └── raw/
│ └── hour.csv downloaded, checksum-checked (ignored)
├── metrics.json the test scores (committed)
├── models/
│ └── model.skops the trained model (ignored)
├── params.yaml every setting
├── pyproject.toml the packages and the two commands
├── src/
│ └── bike_demand_forecast/
│ ├── __init__.py
│ ├── data.py load and split by date
│ ├── download.py download and check the data
│ ├── params.py read and check params.yaml
│ └── train.py train, score and save
└── uv.lock the exact version of every package

Clean Up the Check Folder​

The clone was only for the check. Go back to the folder that holds both projects and delete it:

Terminal
cd ..
rm -rf bike-demand-check

Keep dewiride-bike-demand-forecast: every later part builds on it. Nothing runs in the background, so there's nothing to stop.

Common Mistakes​

MistakeWhat happensDo this instead
A random train/test split on hourly dataThe model trains on hours that come after the ones it's tested on, and its test score looks better than real use will beSplit by date, as split_by_date does
Training with casual and registered as featuresThey add up to cnt, so the model just adds them up and the test score means nothingLeave them out, as FEATURES does
Leaving uv.lock out of GitEvery clone resolves its own versions, and results can driftCommit uv.lock
Changing a setting inside the codeThe change hides from anyone reading params.yamlKeep every setting in params.yaml
Misspelling a key, such as learning_ratBefore anything runs, pydantic reports 2 validation errors for Params: model.learning_rate Field required and model.learning_rat Extra inputs are not permittedFix the key the errors name

Troubleshooting​

SymptomLikely causeFix
ERROR bike_demand_forecast.download: Checksum mismatch: expected ..., got ...The downloaded file isn't the one the checksum was taken from, or the checksum in params.yaml was changedDon't change the checksum to match the file; find out why they differ
data.sha256 Input should be a valid string [type=string_type ...]The checksum in params.yaml lost its quotes and is all digits, so YAML read it as a numberPut it back in double quotes; the fixes post explains why
Download failed: followed by CERTIFICATE_VERIFY_FAILED, on macOSThe Python from python.org has no certificates installed yetFollow Fixed: SSL CERTIFICATE_VERIFY_FAILED in Python on macOS
error: Failed to spawn: and the command's name, then cause: No such file or directory (os error 2)The command is misspelled, missing from [project.scripts], or run outside the project folderCheck Step 8, and run from the project folder
FileNotFoundError: [Errno 2] No such file or directory: 'data/raw/hour.csv' when trainingThe data hasn't been downloaded in this folderRun uv run download first
uv sync --locked says the lockfile needs to be updatedpyproject.toml changed after uv.lock was writtenRun uv lock, then commit both files

FAQ​

Why not just a notebook?​

A notebook is great for exploring, but its results depend on which cells ran and in what order. The commands here always run the same steps in the same order, and the later parts turn them into an automated pipeline.

Will I get exactly 32.5558 too?​

The clone on this computer did, digit for digit, from the same uv.lock. Part 6 runs the same training on GitHub's servers, so you'll see the comparison there.

Why is metrics.json committed but the model isn't?​

The metrics file is tiny and tells you at a glance whether a run changed the results. The model file is large and can always be retrained; Part 2 versions it with DVC.

Why the dewiride- folder name?​

It's the name of the finished project the series builds. The package itself is called bike-demand-forecast, so you can name the folder whatever you like.

Conclusion​

You built a project where every input to a training run is pinned: Python 3.15 in .python-version, 21 packages in uv.lock, the data by its SHA-256 checksum, and every setting in a checked params.yaml, with a fixed random_state. The proof was the clean clone: it installed the same packages, downloaded the same file, trained the same model and wrote a metrics.json that Git couldn't tell apart from the committed one.

In Part 2 you'll put the data and the model under version control with DVC, so each commit of the project knows exactly which data and which model belong to it.

Additional Resources​


Next → Part 2: Version Data and Models with DVC (coming soon)