Sub topic 7
Making predictions and scoring them
This chapter assumes you can build X and y, split them with train_test_split, and call fit on an estimator. Here you will use a fitted model to predict, then measure how good those predictions are.
What a predictor offers
A predictor is an estimator that has learned a mapping from X to y. After fit, it exposes these methods:
predict(X)returns one predicted label or value per row ofX.predict_proba(X)returns class probabilities. Most classifiers have it, but not all. For example,SVChas it only if you passprobability=True.score(X, y)returns a single number that summarizes quality on the data you give it.
All of them need X with the same number of columns as the training data. Calling any of them before fit raises a NotFittedError.
Predicting labels
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
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=0, stratify=y
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(pred.shape) # (38,)
print(pred[:5], y_test[:5]) # predictions next to the true labelspred is a 1D array with one entry per test row, the same shape as y_test. Because pred and y_test line up, you can compare them directly.
Predicting probabilities
proba = model.predict_proba(X_test[:3])
print(proba.shape) # (3, 3): one row per sample, one column per class
print(proba.sum(axis=1)) # each row sums to 1
print(model.classes_) # column order of probaEach column of predict_proba matches a class in classes_, in that order. For classifiers, predict normally returns the class with the highest probability. Some models, such as SVC, can differ slightly because they compute predict differently.
What score means
score(X_test, y_test) calls predict on X_test and compares the result to y_test. The metric depends on the estimator type:
| Estimator type | Default `score` | Better is |
|---|---|---|
| Classifier | Accuracy, the fraction of correct labels | Higher |
| Regressor | R², the coefficient of determination | Higher, with 1.0 the best |
print(model.score(X_test, y_test))The result is accuracy because this is a classifier. R² can be negative for a regressor that does worse than always predicting the mean of y.
Common errors
- Scoring on training data.
model.score(X_train, y_train)shows how well the model remembers, not how well it generalizes. Report the held-out score. - Wrong number of columns. Passing
Xwith a different feature count than in training raises aValueError. - Passing a single row as 1D.
predict(X_test[0])fails because the input must be 2D. UseX_test[:1]orX_test[0].reshape(1, -1). - Trusting accuracy on imbalanced classes. If 95% of the labels are one class, a model that always predicts it scores 0.95. Look at other metrics, such as those in
sklearn.metrics, when classes are uneven.
Using other metrics
You can compute a metric explicitly instead of relying on the default score:
from sklearn.metrics import accuracy_score, confusion_matrix
print(accuracy_score(y_test, pred))
print(confusion_matrix(y_test, pred))accuracy_score takes the true labels first and the predictions second. The result matches model.score for a classifier.
Exercise
You call model.predict_proba(X_test) on a 3-class classifier with 38 test rows. What shape does the result have, and how do you find which class each column belongs to?
Show answer
The shape is (38, 3), with one row per sample and one column per class. The model.classes_ attribute lists the classes in the same order as the columns.
Exercise
A regressor's score on the test set returns -0.4. What does that tell you?
Show answer
For regressors score is R². A negative value means the model predicts worse than a constant model that always outputs the mean of y. The model, features, or settings need to be reconsidered.