From Notebook to Production Code

Refactor exploratory notebooks into a tested, configurable Python package that anyone on the team can run.

Intermediate · about 8 hours · difficulty 2/5

Learn first: scikit-learn Pipelines and Model Persistence, Git for ML Projects

Notebooks are wonderful for exploration and terrible as the only home of a model. Hidden state, out-of-order cells and copy-pasted code make results impossible to reproduce. The first MLOps skill is moving working ideas into ordinary, well-structured code.

Project structure

  • A src/ package with modules for data loading, features, training, evaluation and inference.
  • Configuration in YAML or dataclasses (Hydra and Pydantic are popular) instead of constants scattered through code.
  • Entry points such as python -m project.train --config configs/base.yaml.
  • Pinned dependencies with uv, Poetry or a lock file, and a README explaining how to run everything.

Code quality

  • Type hints and a linter/formatter (Ruff) keep code readable.
  • Logging instead of print statements.
  • Seeds and deterministic settings where practical.

Testing ML code

Traditional unit tests still apply: feature functions, data validation, metric calculations. Add ML-specific checks:

  • Shape and dtype tests for model inputs and outputs.
  • Overfit-one-batch tests that prove the training loop can learn.
  • Data validation of schema, ranges and null rates (Pandera or Great Expectations).
  • Behavioural tests: invariances (a name change should not flip sentiment) and directional expectations.

Keep notebooks for exploration and reports, importing functions from the package so logic lives in one place.

Good enough to move on when a teammate can clone your repo, install it, run training from one command, and see the same metrics with tests passing in CI.

Key concepts

  • Package layout and entry points
  • Config files (Hydra, Pydantic)
  • Dependency pinning
  • Linting and type hints
  • Unit tests with pytest
  • Data validation checks
  • Behavioural model tests

Mini project

Take one of your earlier notebook projects and refactor it into a package with a config file, a train command, a predict command, pytest tests for features and data validation, and a GitHub Actions workflow that runs them.

Check yourself

Name three kinds of bugs a notebook-only workflow hides, and describe one test that is specific to ML code rather than normal software.

Free resources