Sub topic 1
Why define training as code
Prerequisites
This chapter assumes you know Python functions and dataclasses, can run a training script with scikit-learn, and can use Git and the command line. You should also know the train, validate, and test steps of a basic machine learning workflow.
Why define training as code
A notebook where you run cells in any order produces results you cannot reproduce. Someone may have changed a parameter in cell 4, skipped cell 2, or trained on a different file. A pipeline is a training workflow written as versioned code. Each run follows the same steps, and Git records every change to those steps.
Code also makes review possible. A colleague can read a diff of a pipeline change, which is harder to do with a notebook's hidden state.
Breaking training into stages
A stage is one step of the workflow, such as loading data, splitting it, training, or evaluating. Each stage should be a plain function that declares its inputs and outputs. Explicit interfaces let you test a stage alone and swap one stage without touching the others.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def load_data():
return load_iris(return_X_y=True)
def split(X, y, test_size, seed):
return train_test_split(
X, y, test_size=test_size, random_state=seed, stratify=y
)Each function receives everything it needs as arguments. None of them reads a global variable.
Keeping configuration out of your logic
Hard-coded values such as test_size=0.2 scattered through the code make runs hard to compare. Put every tunable value in one frozen dataclass and pass it to the stages. Freezing it prevents a stage from changing a setting mid-run.
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100> Note: keep secrets such as API keys out of the config file. Read them from environment variables instead.
Exercise
Why does a frozen dataclass help when a stage receives the configuration?
Show answer
A frozen dataclass cannot be changed after creation. Every stage sees the same values for the whole run, so two runs with the same config object behave the same way.