Sub topic 1
Why Define Training as Code
A model that trains well once is easy to get. A model that you can retrain next month, on a teammate's machine or in a scheduled job, and get the same result is harder. This chapter explains why that difference matters and what changes when you write training as versioned code instead of a sequence of manual steps. Later chapters cover each technique in detail.
Prerequisites
This chapter assumes you can:
- Write Python functions, import modules, and read a dataclass.
- Describe the basic machine learning loop: train on one split, tune on another, report on a held-out test set.
- Use a terminal and basic Git commands (commit, diff, branch).
- Read scikit-learn code such as
train_test_splitandRandomForestClassifier.
You do not need experience with orchestrators or experiment trackers. They appear only as pointers to later chapters.
What "manual" training looks like
Most models begin in a notebook. You load data, try a feature, fit a model, look at a score, change a cell, and fit again. This is a good way to explore. The trouble starts when the notebook becomes the only record of how a model was produced.
Here is a typical notebook, flattened into one script:
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = RandomForestClassifier(n_estimators=100).fit(X_train, y_train)
print(model.score(X_test, y_test))Run it three times and you will usually see three different accuracies. Neither train_test_split nor the forest has a seed, so each run draws a new split and builds different trees. If you report "0.93" to a colleague, nobody can reproduce that number, including you tomorrow.
The script also has problems that a notebook makes worse:
- Hidden state. Notebook cells share variables in the order you ran them, not the order they appear. If you edit the cell that defines
X_trainand forget to rerun the cell that fits the model, the model was trained on data that no longer matches the code on screen. - Values buried in cells. The test size, the number of trees, and the metric threshold live inside function calls. Changing them means editing code, and nothing records what they were last time.
- No entry point. The only way to run the work is to open the notebook and run all cells, so a scheduler or a CI job cannot call it.
- Poor diffs. A notebook stores outputs, execution counts, and metadata beside the code, so a Git diff of a one-line change can span hundreds of lines.
None of these is a flaw in notebooks as a tool for exploration. They are the reason a notebook is a poor definition of a process you need to repeat.
What "as code" means
Defining training as code means the process is described by source files that:
- Run from a single command with no manual clicking or cell ordering.
- Take every tunable value as an explicit input.
- Live in version control, so every change has an author, a date, and a diff.
- Produce the same outputs from the same inputs.
Here is the earlier script rewritten with those properties:
import argparse
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
def run(seed: int, n_estimators: int, test_size: float) -> float:
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=seed, stratify=y
)
model = RandomForestClassifier(n_estimators=n_estimators, random_state=seed)
model.fit(X_train, y_train)
return model.score(X_test, y_test)
def main() -> None:
parser = argparse.ArgumentParser(description="Train an iris classifier.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--n-estimators", type=int, default=100)
parser.add_argument("--test-size", type=float, default=0.2)
args = parser.parse_args()
accuracy = run(args.seed, args.n_estimators, args.test_size)
print(f"accuracy={accuracy:.3f}")
if __name__ == "__main__":
main()Save it as train.py and run it:
python train.py --seed 7 --n-estimators 200Three things changed. The seed is passed to both the split and the model, so the same arguments give the same accuracy on the same library versions. The tunable values are arguments rather than literals, so a run is described by its command line. And run is an ordinary function that a test, a scheduler, or another script can import and call.
This version is still one function doing everything. The next chapter splits it into stages. The point here is the shift in what you treat as the product: the code that makes the model, not only the model file.
The workflow, before and after
A manual workflow depends on a person. A coded workflow depends on a commit.
In the coded path, any run can be traced back to a commit and a set of parameters. In the manual path, model.pkl is a file with no history.
What you gain
| Concern | Manual notebook | Pipeline as code |
|---|---|---|
| Rerunning | Run all cells in the right order and hope | One command |
| Reproducing a result | Depends on memory and unsaved state | Same commit, config, and data version |
| Review | Opaque notebook diffs | Readable diffs in a pull request |
| Testing | Hard to import and call | Functions that tests can call |
| Automation | Needs a person to start it | Callable from a scheduler or CI |
| Collaboration | Merge conflicts in JSON | Normal code review |
| Auditing | "Which code made this model?" has no answer | Commit hash and parameters on record |
Each row corresponds to a later chapter. Reproducibility, testing, tracking, gating, and orchestration are all things you can build only once training is code.
Review and rollback
When training is code, a change to the model goes through a pull request. A reviewer sees that min_accuracy moved from 0.85 to 0.80, or that the split now stratifies by label. If a retrained model behaves worse in production, you can check out the previous commit, run it, and compare. With a notebook you can only compare against a screenshot or a vague memory.
Automation
A job that retrains weekly needs something to call. A script with a main function can be started from cron, a CI workflow, or an orchestrator. A notebook can be executed headlessly with tools such as papermill, but you are then running code that was designed for interactive use, and you inherit its hidden-state problems.
Testing
You can only test what you can import. A function run(seed, n_estimators, test_size) can be called from a test with small inputs. The test can check shapes, check that two runs agree, or check that a deliberately broken input fails loudly. A notebook cell cannot be called from a test without rewriting it as a function first, and that rewrite is the move this chapter recommends.
Failure modes this prevents
Concrete failures tend to look like these:
- The unreproducible best model. A model scored 0.96 in an unseeded run. Later runs score 0.91 to 0.95. Nobody knows whether a change helped or you only saw noise.
- Silent drift between code and artifact. A cell was edited after the model was saved. The saved model and the visible code no longer match.
- The one-person pipeline. Only one teammate knows the cell order and which cells to skip. When they are away, retraining stops.
- Untraceable regressions. A production model gets worse and there is no commit to compare with the one that was better.
Code does not remove these by itself. A script with no seed is as unreproducible as a notebook. What code gives you is a place to fix each problem once, in a form that persists.
Costs and trade-offs
Pipelines as code are not free, and the decision deserves criteria rather than dogma.
- Up-front effort. Turning a notebook into functions, adding arguments, and writing a first test takes time. For a one-off analysis that nobody will run again, this cost may never pay back.
- Slower exploration. Notebooks give fast feedback on ideas. A command-line run that reloads data each time is slower to iterate with.
- More structure to maintain. Modules, configs, and tests can drift or rot like any other code.
A reasonable rule is to explore in a notebook and move the logic to code as soon as one of these becomes true:
- Someone else will run it.
- It will run more than once, or on a schedule.
- A decision (shipping a model, publishing a number) depends on its result.
- You need to explain later why it produced what it did.
Moving to code does not mean abandoning notebooks. A common pattern keeps the logic in importable modules and uses a notebook only to call those functions and plot results. The notebook becomes a view of the pipeline, not its definition.
Common mistakes when starting out
- Wrapping a notebook in a function without changing it. Pasting all cells into one
def main():keeps the hidden coupling and the literals. Pull values out as parameters and give the function inputs and a return value. - Reading global state. A function that uses a module-level
dfbehaves differently depending on what ran before. Pass data in as arguments. - Scattering file paths. A path like
/Users/me/data.csvworks on one machine. Take paths as arguments or from configuration. - Seeding only one place. Seeding the split but not the model, or the reverse, leaves part of the run random. In the example above,
seedfeeds both. - Treating the script as finished once it runs once. Run it twice and compare results. That is the cheapest check that something is nondeterministic.
Where the next chapters go
The rest of this tutorial builds on run in train.py. The next chapter splits it into stages with explicit inputs and outputs. After that, you move values into a configuration object, control the sources of randomness, add tests, record each run, and gate promotion on a metric. Finally you hand the pipeline to a CLI, a CI job, or an orchestrator.
Summary of the argument
Training as code makes a model's origin a matter of record. You get repeatability from a single command, review through diffs, tests from importable functions, and automation from a callable entry point. The cost is up-front structure, so it pays off when a result will be reused, shared, or relied on.
Exercise
The script below trains a classifier. List three reasons it would be hard to run reliably from a scheduler, and name one change for each. from sklearn.datasets import loadiris from sklearn.linearmodel import LogisticRegression from sklearn.modelselection import traintestsplit X, y = loadiris(returnXy=True) Xtrain, Xtest, ytrain, ytest = traintestsplit(X, y, testsize=0.3) model = LogisticRegression(maxiter=200).fit(Xtrain, ytrain) print(model.score(Xtest, ytest))
Show answer
Any three of these: (1) The split is unseeded, so each run gives a different score. Pass randomstate to traintest_split (and to any model that uses randomness). (2) The values 0.3 and 200 are buried in calls, so a run cannot be described or changed without editing code. Make them parameters or command-line arguments. (3) There is no function or entry point, so another program cannot import and call it. Wrap the logic in a function and add a main guard. (4) The score is only printed, so nothing records it. Return it or write it to a file for a later step to read.
Exercise
Your teammate says, "We already have a notebook that works, so rewriting it as code is wasted effort." Give two situations where you would agree and two where you would disagree.
Show answer
Agree when the work is a one-off analysis that nobody will rerun, and when it is early exploration where you are still deciding what to build. Disagree when the training will run on a schedule or in CI, and when a decision such as shipping a model depends on its result and someone may later ask how it was produced. Disagree as well when more than one person needs to run it, or when you need tests.