A machine learning lab: scikit-learn, notebooks and honest experiments

Add scikit-learn and matplotlib to your Python environment, repeat the course's models with the real library, plot training against test error and keep your experiments organised so that every result can be reproduced.

  • Time: 30 to 45 minutes
  • Cost: free software, your own computer

What you need

The course builds every model by hand with NumPy and pandas, so that you see what a library does. Real projects use a library, and setting one up on your own computer lets you check your hand-built results against it and try your own datasets.

You need the environment from the data lab guide (Python, a virtual environment, pandas, NumPy and Jupyter) and two more free packages:

  • scikit-learn: the standard Python library for classical machine learning, with ready-made models, splitting tools and measures.
  • matplotlib: for plots, such as training error against test error.

Set it up

  1. Open a terminal in your project folder and switch on the virtual environment (.venv\Scripts\Activate.ps1 on Windows PowerShell, source .venv/bin/activate on macOS and Linux).
  2. Install the packages:
pip install scikit-learn matplotlib
  1. Start jupyter lab, create a notebook and make the first cell record what you are running, so every experiment says which versions produced it:
import sklearn, numpy, pandas
print(sklearn.__version__, numpy.__version__, pandas.__version__)
  1. Save one of the course’s trip files as a CSV next to your notebook and load it with pd.read_csv.

Check that it works

Repeat the straight-line case with the library and compare it with your hand-built answer:

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

n_train = int(len(df) * 0.75)
train, test = df.iloc[:n_train], df.iloc[n_train:]
cols = ["distance_km", "parcels", "weight_kg", "rain"]
model = LinearRegression().fit(train[cols], train["minutes"])
print(mean_absolute_error(test["minutes"], model.predict(test[cols])))

The number should match your test_mae_multi to rounding. Then try the neighbours case with KNeighborsRegressor(n_neighbors=5) inside a pipeline that includes StandardScaler, and the baseline with DummyRegressor. If the numbers agree with your own, you understand what the library does.

Practise safely

  • Use public or invented data while you learn, and never put real customer or staff records into a notebook you share. Notebooks keep their output.
  • Split before you do anything else, and fit scalers and models on the training part only. Scikit-learn’s Pipeline helps keep you honest, because it fits every step on the training data alone.
  • Never choose settings by looking at the test score. Use a validation split or cross_val_score, and use the test set once.
  • Set random_state wherever a function uses randomness, so that a result can be repeated.
  • Treat a score that is too good to be true as a bug until you have checked every column for leakage.

Go further

  • Plot training and test error against model complexity with matplotlib to draw your own validation curve.
  • Try cross_val_score to choose the number of neighbours, and GridSearchCV to search several settings at once.
  • Use confusion_matrix, precision_score, recall_score and precision_recall_curve on the late-trip problem, and compare them with your hand-made counts.
  • Keep experiments in a Git repository with a short log: the question, the data version, the settings, the result and what you decided.
  • Enter a beginner-friendly public competition or work through an open dataset, and write a model card for it.

Courses that use this lab

Other lab guides

Software changes quickly. Menu names and version numbers may differ a little from what you see; the ideas and the check at the end of each section stay the same. Always download from the project's own website, and read the licence terms for your situation.