Sub topic 2
Isolating the Environment
Assume you know basic Python, Jupyter, the command line, Git, and package installation. Reproducibility means another person can rerun your analysis and obtain the same result from the same inputs.
Isolating the environment
A virtual environment is a project-specific Python installation. It prevents packages for one project from changing another project’s results.
python -m venv .venv
source .venv/bin/activate
python -m pip install pandas matplotlibOn Windows, activate it with .venv\Scripts\activate. Keep the environment outside version control by adding .venv/ to .gitignore.
Pinning and recording dependencies
A dependency is a package your code needs. Record exact versions so future installations do not silently receive incompatible updates.
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txtRun these commands inside the project’s virtual environment. A frozen requirements file records more detail than a list such as pandas; it can contain a specific version such as pandas==2.2.2.
Seeding random number generators
Random-looking values come from a pseudorandom number generator. A seed is its initial state. Use one explicit generator instead of relying on global random state.
import numpy as np
SEED = 20240601
rng = np.random.default_rng(SEED)
sample = rng.normal(loc=0.0, scale=1.0, size=5)
print(sample)The same NumPy version and seed produce the same sequence. Record the seed with the run metadata.
Tracking data sources and verifying integrity
Data provenance records where data came from, when it was downloaded, and how it was transformed. A checksum is a short fingerprint of a file. Comparing a recorded SHA-256 checksum with a new checksum detects changed or corrupted input.
import hashlib
from pathlib import Path
def sha256_of(path):
digest = hashlib.sha256()
with Path(path).open("rb") as file:
for chunk in iter(lambda: file.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
print(sha256_of("data/raw/measurements.csv"))Store the printed value with the source URL and download date. Stop the analysis when the checksum differs from the recorded value.
Exercise
Why should a notebook use a project virtual environment and an explicit random-number generator?
Show answer
The environment controls package versions, while the generator and seed control random values without depending on hidden global state.