Sub topic 7
Making predictions and scoring them
This chapter assumes you can build a feature matrix X and a label vector y, split them with train_test_split, and call fit on an estimator. It covers what happens after fitting: asking the model for predictions, reading probabilities, and measuring quality with score.
The predictor interface
A fitted classifier or regressor is a predictor. Predictors share a small set of methods:
| Method | Input | Output | Available on |
|---|---|---|---|
| `predict(X)` | 2D array, shape `(n_samples, n_features)` | 1D array of predicted labels or values, shape `(n_samples,)` | All classifiers and regressors |
| `predict_proba(X)` | Same | 2D array of class probabilities, shape `(n_samples, n_classes)` | Classifiers that estimate probabilities |
| `decision_function(X)` | Same | Real-valued scores, not probabilities | Many linear models and SVMs |
| `score(X, y)` | Features and true labels | One float | All classifiers and regressors |
The input to every method must have the same number of columns, in the same order, as the X you passed to fit. If it does not, scikit-learn raises a ValueError.
predict
predict returns one answer per row. For a classifier, each answer is a class label taken from the labels seen in fit. For a regressor, each answer is a number.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
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])
print(y_test[:5])
print(model.classes_) # [0 1 2]The classes_ attribute ends in an underscore because fit learned it. It lists the labels the model can output, in sorted order. You will need it to interpret predict_proba.
Predicting a single sample is a common source of errors. predict needs a 2D array, so a single row must keep its second dimension:
one_row = X_test[0].reshape(1, -1) # shape (1, 4)
print(model.predict(one_row))
# model.predict(X_test[0]) raises ValueError: Expected 2D array, got 1D arrayUsing X_test[:1] also works, because slicing keeps the row axis.
predict_proba
Many classifiers can report how confident they are. predict_proba returns one row per sample and one column per class. Each row sums to 1. Column j corresponds to model.classes_[j].
import numpy as np
proba = model.predict_proba(X_test[:3])
print(proba.shape) # (3, 3)
print(np.round(proba, 3))
print(proba.sum(axis=1)) # [1. 1. 1.]
print(model.classes_[proba.argmax(axis=1)])
print(model.predict(X_test[:3]))For most classifiers, predict picks the class with the highest probability. The last two lines should therefore print the same labels. Two details are worth knowing:
- Not every classifier offers
predict_proba.SVConly does so if you construct it withprobability=True, andLinearSVCnever does. Check withhasattr(model, "predict_proba"). - Probabilities from some models are poorly calibrated. A reported 0.9 does not always mean the model is right 90% of the time. Treat the numbers as a ranking of confidence unless you have calibrated them.
For binary problems, predict_proba still returns two columns. The second column is the probability of the positive class, which is classes_[1].
score
score(X, y) calls predict(X) internally and compares the result with y. The metric depends on the estimator type:
- Classifiers return accuracy, the fraction of predictions that match the true labels.
- Regressors return R², the coefficient of determination. A value of 1.0 is a perfect fit, 0.0 matches a model that always predicts the mean of
y, and negative values mean the model is worse than that baseline.
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_diabetes
Xd, yd = load_diabetes(return_X_y=True)
Xd_train, Xd_test, yd_train, yd_test = train_test_split(
Xd, yd, random_state=0
)
reg = LinearRegression().fit(Xd_train, yd_train)
print(reg.score(Xd_train, yd_train)) # R^2 on training data
print(reg.score(Xd_test, yd_test)) # R^2 on held-out dataAlways score on data the model did not train on. A training score only tells you how well the model memorized or fit what it already saw. The gap between training and test score is a quick check for overfitting.
Reproducing score by hand
Knowing what score does helps you debug it. For a classifier, it is equivalent to this:
accuracy = (model.predict(X_test) == y_test).mean()
print(accuracy)
print(model.score(X_test, y_test)) # same numberFor finer control, use the functions in sklearn.metrics. They take true values first and predictions second.
from sklearn.metrics import accuracy_score, confusion_matrix
print(accuracy_score(y_test, pred))
print(confusion_matrix(y_test, pred))Argument order matters for metrics that are not symmetric, such as precision and recall. Writing metric(y_true, y_pred) consistently avoids silent mistakes.
Common errors
- Feature count mismatch. The model was fitted on 4 columns and you pass 3. scikit-learn raises a
ValueErrorthat names both numbers. - Feature order mismatch with DataFrames. If you fit on a DataFrame, scikit-learn records the column names in
feature_names_in_. Passing a DataFrame with the same names in a different order raises an error. Passing a bare NumPy array skips that check, so a wrong order goes unnoticed and gives wrong predictions. - Calling predict before fit. The estimator raises
NotFittedError. This is a useful signal that the object has no learned attributes yet. - Scoring on training data and reporting it. The number looks good and says little about new data.
- Trusting accuracy on imbalanced data. If 95% of samples are one class, a model that always predicts that class scores 0.95. Look at the confusion matrix, precision, and recall as well.
- Misreading
predict_probacolumns. Column order followsclasses_, not the order in which labels appear in your data.
How predictors fit into the workflow
The sequence is the same for every supervised estimator. You configure it, call fit on training data, and then call predict or score on data it has not seen. Later chapters wrap this sequence in a Pipeline, which exposes the same predict, predict_proba, and score methods. Knowing the contract here means a pipeline behaves the way you already expect.
Exercises
Exercise
A logistic regression model was fitted on labels [0, 1, 2]. predict_proba(X_new) returns an array of shape (10, 3). What do the 10 and the 3 represent, and how do you find which class the second column refers to?
Show answer
The 10 is the number of samples in X_new, and the 3 is the number of classes. Column index 1 corresponds to model.classes_[1], which is the label 1 here. Row sums are 1.
Exercise
You fit a regressor and find reg.score(X_train, y_train) is 0.95 while reg.score(X_test, y_test) is 0.40. What does this suggest, and which number should you report as the expected performance on new data?
Show answer
The model fits the training data much better than unseen data, which points to overfitting. Report the test score of 0.40, because it was computed on data the model did not train on.
Exercise
Write one line of Python that computes the accuracy of a fitted classifier model on X_test and y_test without calling score.
Show answer
(model.predict(X_test) == y_test).mean()