Sub topic 2
Breaking Training into Stages with Clear Interfaces
This chapter assumes you know Python functions, dataclasses, modules, basic machine learning, Git, and the command line. It also assumes you understand the usual training workflow: prepare data, split it, train a model, and measure its quality.
A training pipeline is a sequence of small stages. Each stage does one job and communicates through explicit inputs and outputs. This structure makes the workflow easier to test, change, retry, and run outside a notebook.
From notebook cells to stages
A notebook often hides dependencies. One cell creates a variable, another changes it, and a later cell uses the changed value. The complete workflow exists only in the order and state of the notebook session.
A pipeline makes each dependency visible:
- A data-loading stage returns features and labels.
- A splitting stage receives features and labels and returns training and test data.
- A training stage receives training data and returns a fitted model.
- An evaluation stage receives the model and test data and returns metrics.
Each stage should be a function with a narrow responsibility. Its inputs and outputs form its interface. An interface is the agreed shape and meaning of data passed between parts of a system.
A useful stage should not depend on hidden notebook variables, global mutable state, or an implicit current directory. If a stage needs a value, accept it as an argument. If it creates a result that another stage needs, return it or save it through a defined artifact interface.
Define interfaces with Python functions
The following example uses the Iris dataset and a random forest classifier. Each function has one clear role.
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
def load_data():
"""Return features and labels."""
return load_iris(return_X_y=True)
def split_data(X, y, test_size=0.2, seed=42):
"""Create reproducible, stratified training and test sets."""
return train_test_split(
X,
y,
test_size=test_size,
random_state=seed,
stratify=y,
)
def train_model(X_train, y_train, n_estimators=100, seed=42):
"""Fit and return a model."""
model = RandomForestClassifier(
n_estimators=n_estimators,
random_state=seed,
)
return model.fit(X_train, y_train)
def evaluate_model(model, X_test, y_test):
"""Return evaluation metrics."""
predictions = model.predict(X_test)
return {"accuracy": accuracy_score(y_test, predictions)}The returned value from split_data has four parts. The caller must know their order. For larger systems, a named structure such as a dataclass can make this contract clearer. The important point is that the contract is deliberate and documented.
Compose the stages
A pipeline function coordinates the stages without implementing their internal details.
def run_pipeline():
X, y = load_data()
X_train, X_test, y_train, y_test = split_data(X, y)
model = train_model(X_train, y_train)
metrics = evaluate_model(model, X_test, y_test)
return model, metrics
if __name__ == "__main__":
model, metrics = run_pipeline()
print(f"accuracy={metrics['accuracy']:.3f}")The coordinator makes the dependency order explicit. Evaluation depends on both the trained model and the test data, while training depends only on the training data. This distinction matters when the workflow grows. For example, preprocessing might feed both training and evaluation, and a separate validation stage might run before final testing.
Design useful stage boundaries
A stage boundary is useful when the stage can be understood, tested, and rerun independently. Good boundaries often match actions that have different inputs, costs, or failure modes.
Use these questions when choosing a boundary:
- What data does this stage require?
- What does it produce?
- Can another stage use the result without knowing its internal steps?
- Can the stage run twice without corrupting its output?
- Does the stage need a fixed random seed or configuration value?
- Should its output be stored as a file or passed in memory?
Avoid stages that do too much, such as train_everything(), or stages that are too small to express a meaningful operation, such as a function that only assigns one local variable. The right size depends on the workflow and the cost of testing or rerunning each part.
Exercise
In the example, which stage should change if you replace the random forest with logistic regression, while leaving data loading and evaluation unchanged?
Show answer
The train_model stage should change. Its interface can remain the same: it receives training features and labels and returns a fitted model with a predict method.