Machine learning with scikit-learn
Machine learning means learning a rule from examples instead of writing it by hand. With scikit-learn the workflow is always the same: split data into training and test sets, fit a model on the training data, predict on the test data and measure how often it's right. Every model shares this fit / predict interface.
Features and labels
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape, y.shape)
print(iris.feature_names)
print(X[0], "->", iris.target_names[y[0]])(150, 4) (150,) ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] [5.1 3.5 1.4 0.2] -> setosa
X holds the features — the measurements the model can see, one row per flower. y holds the labels — the answer we want it to learn: which of three iris species it is.
Train, predict, measure
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print(len(X_train), "train /", len(X_test), "test")
print("accuracy:", round(accuracy_score(y_test, predictions), 3))112 train / 38 test accuracy: 0.895
- Never measure a model on the data it learned from — that's like grading students on questions they've already seen.
random_statemakes the split and the model repeatable.stratify=ykeeps the same mix of species in both sets.
Where does it go wrong?
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = DecisionTreeClassifier(max_depth=3, random_state=42).fit(X_train, y_train)
print(confusion_matrix(y_test, model.predict(X_test)))[[12 0 0] [ 0 12 1] [ 0 3 10]]
Rows are the true species, columns the predicted ones. Numbers on the diagonal are correct; anything else shows which species get confused with which.
Pipelines: scaling plus a model
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
scores = cross_val_score(pipe, X, y, cv=5)
print(scores.round(2))
print("mean accuracy:", round(scores.mean(), 3))[0.97 1. 0.93 0.9 1. ] mean accuracy: 0.96
A pipeline chains preparation steps and a model so they're always applied together, in the right order. Cross-validation trains and tests five times on different splits, giving a more honest score than a single split.
Predicting numbers: regression
import numpy as np
from sklearn.linear_model import LinearRegression
size_m2 = np.array([[50], [70], [90], [110], [130]])
price_k = np.array([210, 280, 355, 420, 500])
reg = LinearRegression().fit(size_m2, price_k)
print(round(reg.coef_[0], 2), "k per extra m2")
print(round(reg.predict([[100]])[0]), "k for 100 m2")3.6 k per extra m2 389 k for 100 m2
Practice
Compute accuracy by hand. With y_true = [0, 1, 1, 2, 2, 2, 0, 1] and y_pred = [0, 1, 2, 2, 2, 1, 0, 1], print how many predictions are correct, then the accuracy rounded to 3 decimals.
6 0.75