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.
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
- Open a terminal in your project folder and switch on the virtual environment (
.venv\Scripts\Activate.ps1on Windows PowerShell,source .venv/bin/activateon macOS and Linux). - Install the packages:
pip install scikit-learn matplotlib
- 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__)
- 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
Pipelinehelps 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_statewherever 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_scoreto choose the number of neighbours, andGridSearchCVto search several settings at once. - Use
confusion_matrix,precision_score,recall_scoreandprecision_recall_curveon 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
- A virtual machine lab on your own computer
- A Linux practice machine
- A network lab with free simulators and virtual routers
- A packet-capture lab with Wireshark and tcpdump
- A network-services lab: DHCP, DNS, proxy, load balancer, time and failover
- A Windows Server and Active Directory lab
- A developer workstation: editor, Git, Python and Node
- A container and Kubernetes lab
- A monitoring lab with Prometheus and Grafana
- A security operations (SOC) practice lab
- An isolated security lab for authorised practice
- A cloud lab that cannot surprise you with a bill
- An embedded and microcontroller lab: simulators first, hardware second
- An electronics lab: simulate first, then build on a breadboard
- A Raspberry Pi lab, with or without a Pi
- A home automation lab with Home Assistant and MQTT
- An audio, video, streaming and show-control lab
- A data lab: Python, pandas and Jupyter on your own computer
- An LLM lab: a free local model, embeddings and a test harness
- A TypeScript lab: Node.js, the compiler and a test runner
- A web deployment lab: Git, a free host and environment settings
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.