The Python ML Toolkit and How Examples Run Here
Machine learning in Python rests on a small stack of libraries that work together. You will meet all of them in this track, so it pays to know from the start what each one is for and how the examples on this site are executed.
The stack
| Library | Role | Where you learn it |
|---|---|---|
| NumPy | fast arrays of numbers; vectors, matrices, random numbers | NumPy |
| pandas | tables with named columns of mixed types; loading, cleaning, grouping | pandas |
| Matplotlib | plots of data, losses and decision regions | Matplotlib |
| SciPy | statistics, optimisation, sparse matrices | SciPy |
| scikit-learn | classical ML: preprocessing, models, metrics, pipelines | this track and Machine Learning |
| XGBoost, LightGBM | gradient-boosted trees for tabular data | Classical ML Algorithms |
| PyTorch | deep learning: tensors, automatic gradients, neural network layers | Deep Learning |
| Hugging Face | pretrained transformer models and data sets | NLP, Transformers & LLMs |
| OpenCV, scikit-image | image processing | Computer Vision |
The libraries pass data to each other as NumPy arrays (or pandas tables that convert to them), so you can load a table with pandas, clean it, hand the numbers to scikit-learn, and plot the results with Matplotlib.
The shape of ML data
Almost every library in the stack uses the same convention for a data set:
Xis a two-dimensional array with one row per example (also called a sample, instance or observation) and one column per feature (an input variable). Its shape is(n_samples, n_features).yis a one-dimensional array with one label (the answer to predict, also called the target) per row.
The next example shows the whole stack in one place: pandas holds the table, NumPy holds the numbers, scikit-learn learns from them.
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
iris = load_iris(as_frame=True)
df = iris.frame # pandas: a table with named columns
print(df.shape)
print(df.head(3).to_string())
X = df[iris.feature_names].to_numpy() # NumPy: the numbers a model sees
y = df["target"].to_numpy()
print("X:", X.shape, X.dtype, " y:", y.shape)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
model = DecisionTreeClassifier(max_depth=3, random_state=0) # scikit-learn: an estimator
model.fit(X_train, y_train) # learn from examples
print("predictions:", model.predict(X_test[:5])) # use what was learned
print("true labels:", y_test[:5])
print("test accuracy:", round(model.score(X_test, y_test), 3))(150, 5)
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
0 5.1 3.5 1.4 0.2 0
1 4.9 3.0 1.4 0.2 0
2 4.7 3.2 1.3 0.2 0
X: (150, 4) float64 y: (150,)
predictions: [2 2 0 0 1]
true labels: [2 2 0 0 1]
test accuracy: 0.956
The iris data set has 150 flowers, four measurements each, and a species label 0, 1 or 2. The tree was trained on 105 of them and tested on the other 45, of which it classified 0.956 (43 flowers) correctly.
The estimator pattern
Every scikit-learn model, and every preprocessing step, follows the same small interface. Learn it once and you can use any of them:
| Call | Meaning |
|---|---|
model = SomeModel(settings) |
create the model and choose its hyperparameters (settings you pick, such as max_depth=3) |
model.fit(X_train, y_train) |
training: learn the parameters from the examples |
model.predict(X_new) |
inference: apply what was learned to new rows |
model.predict_proba(X_new) |
class probabilities, for classifiers that have them |
model.score(X_test, y_test) |
a default metric: accuracy for classifiers, for regressors |
scaler.fit(X_train) then scaler.transform(X) |
preprocessing steps learn from training data, then transform any data |
Learned values are stored on the model in attributes ending in an underscore, such as coef_, intercept_ or classes_. The underscore means "this exists only after fit".
Reproducibility: fixed seeds
Many steps in ML use randomness: shuffling before a split, initial weights, random sub-samples. To get the same result every time, the examples fix the seed: np.random.default_rng(0) for NumPy, random_state=0 for scikit-learn, torch.manual_seed(0) for PyTorch. Change a seed and rerun an example to see how much a result depends on chance; this is one of the most useful habits you can build.
How the examples on this site run
- In your browser. Python examples run in Pyodide, a full Python 3.13 compiled to WebAssembly, with NumPy, pandas, Matplotlib, SciPy, scikit-learn, XGBoost, LightGBM, statsmodels, OpenCV and more. Nothing is sent to a server. The first run on a page takes a few seconds while the packages load; later runs are fast. You can edit any example and run it again.
- Recorded. PyTorch, Hugging Face and some MLOps tools cannot run inside a browser. Examples that import them carry a grey Recorded badge: the output shown was produced by running exactly that code on a computer (CPU only) and is checked automatically, but editing the code does not re-run it. To experiment with them, copy the code to your own Python installation.
- Data. Examples use small data sets that ship with scikit-learn (
load_iris,load_digits,load_breast_cancer,load_wine,load_diabetes) or data generated in the code, so they work offline and give the same numbers everywhere.
Note: In Pyodide, NumPy's default integer type is 32-bit (
int32), while on a 64-bit desktop it isint64. It rarely matters, but it explains a differentdtypeif you run an example on your own machine.
Practice
- In the example, change
max_depth=3tomax_depth=1and run it. What happens to the test accuracy, and why might a tree with a single question not separate three species?
Answer
A depth-1 tree asks one question and has only two leaves, so it can predict at most two of the three species. One species is always wrong, and the test accuracy drops to about two thirds.
- What are the shapes of
X_trainandy_trainin the example?
Answer
test_size=0.3 puts 45 of the 150 rows in the test set, so X_train has shape (105, 4) and y_train has shape (105,).
Test yourself
In the usual convention, what does one row of X hold?
- One feature for all examples
- One example with all its features
- The labels
- The model's parameters
Which call is the training step for a scikit-learn model?
model.predict(X)model.fit(X, y)model.score(X, y)model.transform(X)
What does a trailing underscore in an attribute name such as coef_ tell you?
- It is private
- It is a hyperparameter
- It is learned during
fit - It is deprecated
Why does an example with a grey Recorded badge not change its output when you edit the code?
- Its library (e.g. PyTorch) cannot run in the browser, so the saved output of the original code is shown
- Recorded examples are broken
- The browser caches the first result
- Editing is disabled for all ML examples