Sub topic 16
Making predictions on new data
This chapter assumes you can build a scikit-learn Pipeline, split data into train and test sets, and read a classification report. It covers how a trained model scores new rows, and the errors that appear when new data differs from training data.
What prediction needs
A trained model is a function from feature rows to outputs. At prediction time it must receive rows with the same columns, the same order, and the same meaning as in training. Every preprocessing step must also run with the values it learned during training: scaler means, imputer medians, and encoder categories.
A fitted pipeline guarantees this. Calling predict on a pipeline passes the rows through each fitted step and then into the model. You never refit anything on new data.
Predicting with a fitted pipeline
The example trains on the breast cancer dataset, saves the pipeline, loads it again, and scores a new row.
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
joblib.dump(model, "model.joblib")
loaded = joblib.load("model.joblib")
new_row = X_test.iloc[[0]]
print(loaded.predict(new_row))
print(loaded.predict_proba(new_row))X_test.iloc[[0]] uses double brackets so the result is a one-row DataFrame. A single bracket returns a Series, which scikit-learn does not accept as a feature table.
predict returns the class label. predict_proba returns one probability per class, in the order of loaded.classes_. Here the columns are class 0 (malignant) and class 1 (benign).
Labels, probabilities and thresholds
For binary classification, predict applies a 0.5 threshold to the probability. If the costs of errors are unequal, you can apply your own threshold to predict_proba instead. Choose it using validation data, not the test set.
Common errors
- Missing or renamed columns. A pipeline fitted on a DataFrame checks column names. Missing or renamed columns raise an error, which is better than silently wrong output.
- Different column order. Reorder with
new_data[X_train.columns]before predicting if your source does not guarantee order. - Unseen categories. A plain
OneHotEncoderfails on a category it never saw. Sethandle_unknown="ignore"so unseen categories become all zeros. - Refitting on new data. Calling
fitorfit_transformon new rows replaces what the model learned. Usepredictandtransformonly. - Version mismatch. A file saved with
joblibshould be loaded with the same scikit-learn version. Pin versions in your deployment.
Batch and single-row prediction
Batch prediction scores a whole table at once, for example a nightly job. Single-row prediction serves one request at a time, for example from a web service. Both use the same predict call on the same saved pipeline, so the results agree.
Exercise
A pipeline was trained on a table with columns "age" and "city". A new request arrives with a city value that was not in the training data. The pipeline uses OneHotEncoder with default settings. What happens, and how do you fix it?
Show answer
The encoder raises an error because it has never seen that category. Fix it by creating the encoder with handle_unknown="ignore" and refitting the pipeline, so unseen categories are encoded as all zeros.
Exercise
Why should you call predict on new data but never fit_transform on the scaler?
Show answer
fit_transform recomputes the scaler's mean and variance from the new rows. The model was trained on features scaled with the training statistics, so the new rows would be scaled differently and the predictions would be wrong. The fitted scaler's transform, called through the pipeline, reuses the training statistics.