End-to-End MLOps Tutorial in Python — Part 1: Set Up a Reproducible Machine Learning Project
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.
- Part 1: Set Up a Reproducible Machine Learning Project (you are here)
- Part 2: Version Data and Models with DVC (coming soon)
- Part 3: Build a Reproducible Training Pipeline with DVC (coming soon)
- Part 4: Validate Data in the Pipeline with Pandera (coming soon)
- Part 5: Track Pipeline Experiments with DVC and MLflow (coming soon)
- Part 6: Continuous Integration for Machine Learning with GitHub Actions (coming soon)
- Part 7: Serve the Model as an API with FastAPI and Docker (coming soon)
- Part 8: Continuous Delivery of the Model Image with GitHub Actions (coming soon)
- Part 9: Monitor Data Drift and Model Performance with Evidently (coming soon)
- Part 10: Automate Monitoring and Retraining with Prefect (coming soon)
- 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:
| Level | What 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 automation | The training steps run as an automated pipeline that retrains the model on new data, with automatic data and model checks |
| 2: CI/CD pipeline automation | The 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:

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:
| Pinned | How this part does it |
|---|---|
| The Python version and every package | uv records Python 3.15 in .python-version and the exact version of each package in uv.lock |
| The data | The download is checked against a SHA-256 checksum, so a changed file stops the run |
| The settings | Every setting lives in one file, params.yaml, and is checked when it's read |
| The randomness | The 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
| Tool | Version |
|---|---|
| Python | 3.15.2 |
| uv | 0.13.10 |
| scikit-learn | 1.9.1 |
| pandas | 3.1.1 |
| pydantic | 2.14.4 |
| PyYAML | 6.0.4 |
| skops | 0.16.0 |
| Git | 2.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:
uv --version
uv 0.13.10 (e3e7c1eac 2026-11-24 aarch64-apple-darwin)
- Git, to commit and clone the project. Check it:
git --version
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:
uv init --package --name bike-demand-forecast --python 3.15 dewiride-bike-demand-forecast
Initialized project `bike-demand-forecast` at `/Users/you/source/dewiride-bike-demand-forecast`

| Option | What it does |
|---|---|
--package | Creates an installable package with a src/ folder, the layout production projects use |
--name bike-demand-forecast | The package's name; its code lives in src/bike_demand_forecast |
--python 3.15 | Requires Python 3.15 or newer, and writes 3.15 to a .python-version file |
dewiride-bike-demand-forecast | The 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:
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/
├── .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:
uv add pandas scikit-learn skops pyyaml pydantic
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

uv created a virtual environment in .venv, installed the five packages and the 16 they depend on, and wrote two files:
pyproject.tomlnow lists the five packages, with a minimum version for each.uv.lockrecords 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:
# 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

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: 42is the fourth pin, andearly_stopping: falseis 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:
"""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:
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
DataParamsaccepts only anhttps://address and a checksum of exactly 64 hexadecimal characters.SplitParamsreads the two dates (YAML hands them over as real dates) and checks, intest_comes_after_train, that the test period comes after the training period.ModelParamssets a lower limit on each number and requiresearly_stoppingto betrueorfalse.
Finish the file with the model for the whole file and the function that reads it:
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:
"""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))

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:
"""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:
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_rentalsreads the CSV file withdtedayas a real date, so it can be compared.split_by_datekeeps the hours up totrain_endfor training and the hours after it, up totest_end, for testing. The dates fromparams.yamlare Python dates, and pandas 3 won't compare them with a date column directly, sopd.Timestampconverts them first.
Here's the complete file:
"""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

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:
"""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:
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:
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:
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:
"""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))

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:
"""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:
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: 42fixes 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: falseis 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 inparams.yaml.
Last, inside main, the scores and the two files:
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 scores: MAE, the average error in bikes per hour; RMSE, which weighs big misses more; and R², the share of the variation the model explains. How to Calculate MAE, RMSE and R² in scikit-learn explains each one.
models/model.skops: the trained model, saved with skops, which loads only types you trust. How to Save and Load a scikit-learn Model with skops shows how.metrics.json: the scores, rounded to four decimals and written as JSON. This small file is what the next steps compare.
Here's the complete file:
"""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())

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:
[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.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/mlops/2026/mlops-p1-09-scripts-code.webp)
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:
"""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
uv run download
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 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:
- macOS / Linux
- Windows (PowerShell)
head -n 3 data/raw/hour.csv
Get-Content data/raw/hour.csv -TotalCount 3
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

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
uv run train
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:
cat metrics.json
{
"mae": 32.5558,
"rmse": 51.7738,
"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:
# 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:
git status
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)

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:
git add .
git commit -m "Set up a reproducible bike demand forecast project"
[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

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.
cd ..
git clone dewiride-bike-demand-forecast bike-demand-check
cd bike-demand-check
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:
uv sync --locked
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:
uv run download
uv run train
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:
git status
On branch main
Your branch is up to date with 'origin/main'.
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.
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/
├── .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:
- macOS / Linux
- Windows (PowerShell)
cd ..
rm -rf bike-demand-check
cd ..
Remove-Item -Recurse -Force 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
| Mistake | What happens | Do this instead |
|---|---|---|
| A random train/test split on hourly data | The model trains on hours that come after the ones it's tested on, and its test score looks better than real use will be | Split by date, as split_by_date does |
Training with casual and registered as features | They add up to cnt, so the model just adds them up and the test score means nothing | Leave them out, as FEATURES does |
Leaving uv.lock out of Git | Every clone resolves its own versions, and results can drift | Commit uv.lock |
| Changing a setting inside the code | The change hides from anyone reading params.yaml | Keep every setting in params.yaml |
Misspelling a key, such as learning_rat | Before anything runs, pydantic reports 2 validation errors for Params: model.learning_rate Field required and model.learning_rat Extra inputs are not permitted | Fix the key the errors name |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
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 changed | Don'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 number | Put it back in double quotes; the fixes post explains why |
Download failed: followed by CERTIFICATE_VERIFY_FAILED, on macOS | The Python from python.org has no certificates installed yet | Follow 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 folder | Check Step 8, and run from the project folder |
FileNotFoundError: [Errno 2] No such file or directory: 'data/raw/hour.csv' when training | The data hasn't been downloaded in this folder | Run uv run download first |
uv sync --locked says the lockfile needs to be updated | pyproject.toml changed after uv.lock was written | Run 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
- MLOps: Continuous delivery and automation pipelines in machine learning — Google's guide, with the three maturity levels.
- MLOps maturity model — Microsoft's five levels.
- Locking and syncing — uv's lock file and
--locked. - Controlling randomness — scikit-learn's guide to reproducible results.
- Bike Sharing dataset — the data, its columns and its licence.
Next → Part 2: Version Data and Models with DVC (coming soon)
