Your first reproducible ML notebook with a naive baseline
Load and profile a small dataset in a pinned Jupyter environment and show a trained model beating a dummy baseline.
By Invicly Tech, , in AI and Machine Learning with Python. About 10 minutes to read.
In short
Your first notebook should prove two things: that anyone can rerun it and get the same numbers, and that a trained model beats a naive baseline. You pin the environment in a virtual environment, load and profile a small dataset with pandas, fix random seeds, and compare a DummyClassifier with a simple logistic regression on the same test split. If the model does not clearly win, you have learned something important before spending more effort.
Explained simply
A notebook is a document that mixes code, results and notes. Jupyter is the most common tool for this. It is great for exploring data, but it is easy to make a notebook that only works on your machine, in the order you happened to run the cells. This topic shows how to avoid that.
Start by creating a virtual environment, which is a private folder of Python packages for this project. Install what you need and save the exact versions in a requirements file. Anyone can then rebuild the same setup and get the same results.
Next, load a small dataset and look at it before modelling. How many rows and columns? What types? Any missing values? How common is each class? This is called profiling, and it often reveals problems that would quietly ruin a model.
Finally, compare two things on the same test data: a dummy model that ignores the inputs and always predicts the most common answer, and a simple real model. If the real model does not clearly beat the dummy, the inputs may not contain a useful signal yet.
Press Play on a diagram to walk through it one step at a time.
- 1Create venv
python -m venv .venv, then install and pin packages.
- 2Load and profile
Shape, types, missing values, class balance.
- 3Split with a seed
train_test_split with random_state and stratify.
- 4Fit the dummy
DummyClassifier predicts the most common class.
- 5Fit a simple model
Scaled logistic regression on the same split.
- 6Compare and record
Both scores, package versions and the seed.
- 1Results table
Baseline and model scores with the seed used.
- 2Notebook cells
Run top to bottom after a kernel restart.
- 3Data file
Fixed source, recorded row count or hash.
- 4Pinned packages
requirements.txt from pip freeze.
- 5Python version
Recorded, for example Python 3.12.
In depth
Setting up a pinned environment
Create the environment inside the project folder so it is easy to find and delete. On Linux or macOS run python3 -m venv .venv and then source .venv/bin/activate; on Windows run .venv\Scripts\activate. Install JupyterLab, pandas, scikit-learn and matplotlib, then write pip freeze to requirements.txt and commit that file to Git.
Register the environment as a Jupyter kernel with python -m ipykernel install --user --name ml-path, then choose that kernel in the notebook. Add .venv to .gitignore; the folder can be rebuilt from requirements.txt. To roll back, deactivate the environment and delete the .venv folder; nothing outside the project changes.
- python3 -m venv .venv
- pip install jupyterlab pandas scikit-learn matplotlib
- pip freeze > requirements.txt
- python -m ipykernel install --user --name ml-path
- Cleanup: deactivate, then delete .venv
Profiling a dataset with pandas
Profiling means checking the basics before you trust the data. df.shape gives rows and columns. df.info() lists column types and non-null counts, which shows missing values and numbers stored as text. df.describe() summarises numeric columns, where impossible values such as negative ages stand out. df.isna().sum() counts missing values per column, and y.value_counts(normalize=True) shows class balance.
For the breast cancer dataset that ships with scikit-learn, you should see 569 rows, 30 numeric features, no missing values and about 63 percent benign and 37 percent malignant cases. Write these numbers in a markdown cell. If a later run shows something different, you know the data changed.
Seeds and repeatable runs
Many steps use randomness: shuffling rows, splitting data, initialising some models. A seed fixes the random sequence so the same code gives the same result. In scikit-learn, pass random_state=42 (any fixed integer works) to train_test_split and to any estimator that accepts it. For NumPy, create a generator with rng = np.random.default_rng(42) and use it for all random draws.
Seeds make results repeatable, not correct. A score that changes a lot when you change the seed is fragile; later modules use cross-validation to measure that spread. Before sharing, restart the kernel and run all cells top to bottom to confirm the numbers match.
- random_state on every split and random estimator
- np.random.default_rng(seed) for NumPy draws
- Restart kernel and run all before sharing
Baseline versus model, honestly compared
Fit both on the same training rows and score both on the same test rows. DummyClassifier with strategy="most_frequent" gives the accuracy of always predicting the majority class. A pipeline of StandardScaler and LogisticRegression is a sensible first real model: fast, stable and easy to inspect.
Record both numbers, the seed, the test size and the package versions in a small results table. On the breast cancer data, expect the dummy near 0.63 and the logistic regression well above 0.9, though exact values depend on the split. If the gap were tiny, you would check the features and labels before trying fancier models.
- Notebook to Training split: Fit DummyClassifier1Fit DummyClassifier
- Notebook to Training split: Fit scaled logistic regression2Fit scaled logistic regression
- Notebook to Test split: Score the dummy3Score the dummy
- Notebook to Test split: Score the model4Score the model
- Test split to Notebook: Two accuracies on identical rows5Two accuracies on identical rows
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Create a venv and pin packages~35m
- 2Load and profile a dataset with pandas~35m
- 3Fix random seeds~35m
- 4Fit a DummyClassifier baseline~35m
- 5Compare it with a simple trained model~35m
Key points
- Pin package versions in requirements.txt so the notebook runs the same next month.
- Profile before modelling: row count, column types, missing values and class balance.
- Fix random_state on every split and model that uses randomness.
- A DummyClassifier shows the score you get by knowing nothing about the inputs.
- Report the baseline and the model side by side on the same test set.
Key terms
Tap a card to flip it. 0/5 known
Examples
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
dummy = DummyClassifier(strategy="most_frequent").fit(X_tr, y_tr)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
print("dummy accuracy:", round(dummy.score(X_te, y_te), 3))
print("model accuracy:", round(model.score(X_te, y_te), 3))The dummy scores about 0.63 because about 63 percent of rows are the benign class; the model should score far higher.
Profiling the breast cancer dataset
Step 1: load the data as a DataFrame. Step 2: print shape and missing values. Step 3: check class balance. Expected evidence: (569, 30), zero missing values, and a class split of roughly 0.63 for class 1 (benign) and 0.37 for class 0 (malignant). Note that in this dataset the target 0 means malignant, which matters later when you choose which class is positive.
from sklearn.datasets import load_breast_cancer
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print(X.shape)
print("missing values:", int(X.isna().sum().sum()))
print(y.value_counts(normalize=True).round(3))
print(X.describe().T[["mean", "min", "max"]].head())Recording the environment next to the results
After the comparison, store everything needed to rerun it. Step 1: capture the Python and library versions. Step 2: store the seed and both scores. Step 3: save the dictionary as JSON next to the notebook and commit it. A month later, a different score with the same versions points to a data change; a different score with new versions points to a library change.
import json, platform, sklearn, pandas
results = {
"python": platform.python_version(),
"scikit_learn": sklearn.__version__,
"pandas": pandas.__version__,
"seed": 42,
"dummy_accuracy": 0.629, # replace with your run's value
"model_accuracy": 0.972, # replace with your run's value
}
with open("results.json", "w") as f:
json.dump(results, f, indent=2)Quick reference
- python3 -m venv .venv && source .venv/bin/activate
- pip freeze > requirements.txt, then commit it; add .venv to .gitignore
- Profile: df.shape, df.info(), df.describe(), df.isna().sum()
- Class balance: y.value_counts(normalize=True)
- train_test_split(..., stratify=y, random_state=42) keeps class shares and repeats the split
- DummyClassifier(strategy="most_frequent") is the score of knowing nothing
- Restart kernel and run all cells before you trust or share a result
Common mistakes
- Installing packages globally, so the notebook breaks when another project upgrades them.
- Running cells out of order; restart the kernel and run all cells before trusting a result.
- Comparing the model and the baseline on different splits, which makes the comparison meaningless.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a virtual environment, install pandas and scikit-learn, and save pinned versions to requirements.txt.
- Exercise 2medium
Load the wine dataset from scikit-learn, print its shape and class balance, and fit a DummyClassifier baseline on a stratified split.
- Exercise 3hard
Measure how stable the model's advantage is: repeat the dummy-versus-logistic comparison on the breast cancer data with seeds 0 to 9 and report the mean and spread of the gap.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use Jupyter or plain Python scripts for ML?
- Use notebooks to explore and explain, and move stable code into scripts or modules once it works. Later modules package the pipeline as tested Python code.
- What random seed should I use?
- Any fixed integer works; 0 and 42 are common. What matters is that you record it and that your conclusions hold across a few different seeds.
- What is a DummyClassifier for?
- It gives the score of a model that ignores the inputs, such as always predicting the most common class. Any real model must beat it clearly.
- Do I need a GPU to start machine learning?
- No. Classical models on small and medium tabular datasets train in seconds on a laptop CPU, and this whole path runs without a GPU.