Sub topic 16
Making predictions on new data
This chapter covers the last step before deployment: using a trained model on rows it has never seen. It assumes you can build a scikit-learn Pipeline, you know what fit and predict do, and you have read the chapters on pipelines and the final test evaluation.
What a prediction needs
A prediction is a function call on a fitted object. Training produces state: scaler means, encoder categories, imputer medians, and model coefficients. Predicting reuses that state and never recomputes it. If you remember one rule, make it this one: call fit once on training data, then call only predict, predict_proba or transform afterwards.
A fitted Pipeline bundles all of that state. Calling pipeline.predict(new_rows) runs each preprocessing step's transform with the values learned during training, then passes the result to the model. This is why the pipeline chapter insisted on one path for training and prediction.
predict versus predict_proba
For a classifier, predict returns class labels. predict_proba returns one probability per class, in the order given by model.classes_. Never assume that column 1 is the class you care about. Look it up.
The label from predict is usually the class with the highest probability, which for two classes means a threshold of 0.5. That default is rarely the right business choice. If a missed positive costs far more than a false alarm, lower the threshold. Choose the threshold on validation data using the metric you picked earlier, not on the test set. Store the chosen value with the model so that serving applies the same one.
Probabilities from some models are poorly calibrated. A random forest that outputs 0.9 does not necessarily mean 90% of such cases are positive. If you show probabilities to users or multiply them by costs, check calibration with sklearn.calibration.calibration_curve or wrap the model in CalibratedClassifierCV.
For regression, predict returns a number. Consider also returning an error range from the validation residuals, because a single number hides uncertainty.
Saving and loading the model
Training and serving usually run in different processes. Save the fitted pipeline with joblib, and save the input contract next to it: the expected column names, the threshold, and the library version.
import joblib
import sklearn
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)
artifact = {
"model": model,
"columns": list(X_train.columns),
"threshold": 0.5,
"positive_class": 1,
"sklearn_version": sklearn.__version__,
}
joblib.dump(artifact, "model.joblib")
print("saved with scikit-learn", sklearn.__version__)In this dataset, class 1 means benign and class 0 means malignant. Naming positive_class explicitly in the artifact avoids silent confusion later.
Two cautions apply to saved models.
- A joblib file is a pickle. Loading it can run arbitrary code, so load only files you created or trust.
- A pickle is tied to the library version. Loading a model saved under a different scikit-learn version can fail or, worse, give different results. Pin the version in your serving environment and compare it against the stored value on load.
A prediction function with input checks
Serving code should validate input before it reaches the model. A pipeline given a DataFrame with missing or misnamed columns will raise an error at best. At worst, with NumPy arrays, it will quietly use the wrong column order. Wrapping the pipeline in one function gives the rest of your system a single entry point.
import joblib
import pandas as pd
import sklearn
from sklearn.datasets import load_breast_cancer
artifact = joblib.load("model.joblib")
model = artifact["model"]
columns = artifact["columns"]
threshold = artifact["threshold"]
positive_index = list(model.classes_).index(artifact["positive_class"])
if artifact["sklearn_version"] != sklearn.__version__:
raise RuntimeError(
f"Model saved with {artifact['sklearn_version']}, "
f"running {sklearn.__version__}"
)
def predict_rows(records):
frame = pd.DataFrame(records)
missing = [c for c in columns if c not in frame.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
frame = frame[columns] # fixes column order, drops extras
probability = model.predict_proba(frame)[:, positive_index]
return pd.DataFrame({
"probability": probability,
"label": (probability >= threshold).astype(int),
})
sample = load_breast_cancer(as_frame=True).data.iloc[:3]
print(predict_rows(sample.to_dict(orient="records")))Selecting frame[columns] handles a common failure: a caller sends the right fields in a different order. Since scikit-learn 1.0, estimators fitted on a DataFrame remember feature_names_in_ and warn or raise when names differ. Do not rely on that alone. An explicit check gives your callers a clear error message.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: X has 30 features, but ... expecting 31` | The input schema differs from training. | Validate columns against the saved list before calling the model. |
| `Expected 2D array, got 1D array` | A single row was passed as a flat list or Series. | Use `X.iloc[[0]]` or `pd.DataFrame([row])`. |
| Warning about missing feature names | The model was fitted on a DataFrame but predicted on an array. | Pass a DataFrame with the same column names. |
| `Found unknown categories` | The encoder has the default `handle_unknown="error"`. | Set `handle_unknown="ignore"` and monitor how often it happens. |
| Predictions look plausible but are wrong | Column order changed, or `fit_transform` was called at prediction time. | Select columns by name and never refit on new data. |
| Inverted labels | Column 1 of `predict_proba` was assumed to be the positive class. | Look up the position in `model.classes_`. |
| Load fails or results shift after an upgrade | The scikit-learn version differs from the training environment. | Pin versions and check them on load. |
Training-serving skew
Training-serving skew means the features seen in production are computed differently from the features used in training. The model code is identical, but the inputs are not. Typical causes:
- Training read a cleaned CSV, while production reads raw database rows with different units, date formats or null markers.
- A feature was built with pandas code in a notebook and reimplemented by hand in the service.
- A lookup value, such as an average over the last 30 days, was computed with information that does not exist at prediction time.
The defense is to put every transformation that the model depends on inside the pipeline, using ColumnTransformer and FunctionTransformer. Anything left outside needs to run from the same shared code in both environments. A good test is to save a few raw rows and their expected outputs, then check in a unit test that the loaded pipeline reproduces them exactly.
Missing values need a decision too. If the pipeline includes a SimpleImputer, it fills gaps using training statistics, which is the right behavior. If it does not, a null in a new row raises an error in most models. Decide whether a failed request or an imputed value is acceptable for your use case.
Batch and online prediction
Batch prediction scores many rows on a schedule, such as a nightly job that writes scores to a table. It is simple, and one vectorized predict call is fast. Online prediction scores one or a few rows per request. Load the model once when the service starts, not on every request, because loading costs far more than predicting. Scoring a single row is cheap for linear models and small trees but can be slow for large ensembles, so measure latency before promising it.
In both modes, log the input, the model version, the probability and the timestamp. Without these logs, you cannot debug a bad prediction, and you cannot compare predictions with outcomes once the true labels arrive. That comparison is the basis of the monitoring chapter.
Exercise
A teammate loads a saved pipeline and calls model.predict_proba(row)[:, 1] to get the probability of "fraud". The labels in training were ["ok", "fraud"] strings, and scores look inverted for some retrained versions of the model. What is the likely cause, and how do you fix it?
Show answer
Column 1 is not guaranteed to be "fraud". The columns follow model.classes_, which is sorted: with the labels ["ok", "fraud"] it is ["fraud", "ok"], so column 1 is "ok". Retraining on data with different labels can change the order again. Look up the index with list(model.classes_).index("fraud") and use that column, or store the positive class name with the model, as the artifact in this chapter does.
Exercise
Your service receives JSON with the right fields but in a different order from training, and sometimes an extra "request_id" field. Using a DataFrame, how do you make the pipeline robust to both, and what check should come first?
Show answer
First check that every expected column is present and raise a clear error listing any that are missing. Then select the columns by name, frame = frame[columns], using the list saved at training time. This fixes the order and drops extras such as "request_id" before the data reaches the pipeline.