Sub topic 3
The estimator API: fit, predict, score
This chapter assumes you can write basic Python and use NumPy arrays and their shapes. It also assumes you know what a linear model is, from the earlier chapters of this tutorial. Here we look at the interface scikit-learn gives every model. Once you know it, you can swap LinearRegression for Ridge, Lasso or a whole pipeline without changing the surrounding code.
What an estimator is
In scikit-learn, an estimator is any object that learns something from data. You create it with settings, call fit to learn from data, and then use the learned state. LinearRegression, Ridge, StandardScaler and Pipeline are all estimators.
Three kinds of values live on an estimator:
- Hyperparameters are settings you choose before fitting, such as
alphaforRidge. They are passed to the constructor and stored unchanged. - Learned attributes are computed by
fit. Their names end in an underscore, such ascoef_andintercept_. - Methods such as
fit,predict,scoreandget_paramswork with the first two.
The constructor never looks at data. This is why you can build a model before you have any, and why clone can make a fresh copy from the hyperparameters alone.
The three core methods
| Method | Input | Output | What it does |
|---|---|---|---|
| `fit(X, y)` | Features `X`, targets `y` | The estimator itself | Learns parameters and stores them as attributes ending in `_` |
| `predict(X)` | Features only | 1D array of predictions | Applies the learned parameters |
| `score(X, y)` | Features and true targets | One float | Predicts on `X`, then compares with `y` |
Two details cause most beginner mistakes.
Shapes. X must be 2D with shape (n_samples, n_features), even when there is one feature. y is 1D with shape (n_samples,). A single column of X taken as X[:, 0] is 1D and will be rejected. Use X[:, [0]] or X[:, 0].reshape(-1, 1) to keep it 2D.
Return value of fit. fit returns self. That is why LinearRegression().fit(X, y) gives you the fitted model in one line, and why chained calls like model.fit(X, y).predict(X_new) work.
A first complete run
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=100)
model = LinearRegression()
print("fitted before fit?", hasattr(model, "coef_"))
returned = model.fit(X, y)
print("fit returns self?", returned is model)
print("coef:", model.coef_, "intercept:", model.intercept_)
print("predictions:", model.predict([[4.0], [5.0]]))
print("R2 on training data:", model.score(X, y))Before fit, coef_ does not exist. After fit, coef_ holds one weight per feature, here an array of length 1 close to 3. The predictions for 4 and 5 should be close to 14 and 17. The last line scores on the training data only to show the call. The chapter on train_test_split explains why you should score on held-out data.
What score means
score is not the same for every estimator. Each estimator class defines its own default.
- For regressors, including
LinearRegression,scorereturns R-squared, the share of the target's variance that the model explains. A value of 1.0 is a perfect fit. A value of 0.0 is no better than always predicting the mean ofy. It can be negative on new data if the model is worse than that. - For classifiers,
scorereturns accuracy.
Because the meaning changes with the estimator type, do not compare score outputs across model families without checking. When you need a specific error measure such as RMSE or MAE, use the metrics functions covered in a later chapter. score is a convenient default, not a full evaluation.
Common errors and what they mean
Three failures account for most estimator API problems. This script triggers each one on purpose.
import numpy as np
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LinearRegression
from sklearn.utils.validation import check_is_fitted
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=100)
model = LinearRegression()
try:
model.predict(X[:3])
except NotFittedError:
print("NotFittedError: call fit before predict")
try:
model.fit(X[:, 0], y)
except ValueError:
print("ValueError: X was 1D, expected 2D")
model.fit(X, y)
check_is_fitted(model)
print("check_is_fitted passed")
try:
model.predict(np.zeros((2, 3)))
except ValueError:
print("ValueError: wrong number of features")NotFittedErrormeans you calledpredictorscoreon an estimator that has no learned attributes.check_is_fitted(model)raises the same error and is useful in your own helper functions.- A 1D
XraisesValueErrorwith a message that suggestsreshape(-1, 1)for one feature orreshape(1, -1)for one sample. - A feature count mismatch raises
ValueErrorbecause the model learned a fixed number of coefficients. The columns you pass at prediction time must be the same columns, in the same order, as at fit time.
A fourth problem raises no error at all. Calling fit a second time on a different dataset replaces the earlier learned state. If you fit on the test set by accident, the model will run without complaint and your evaluation will be wrong.
Parameters, copying and refitting
Every estimator exposes its hyperparameters through get_params and lets you change them with set_params. The helper clone builds a new, unfitted estimator with the same hyperparameters. Tools such as cross_val_score and GridSearchCV use clone internally, so each fold starts from a clean model.
import numpy as np
from sklearn.base import clone
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=100)
ridge = Ridge(alpha=1.0)
print("alpha:", ridge.get_params()["alpha"])
ridge.set_params(alpha=10.0)
ridge.fit(X, y)
print("fitted coef:", ridge.coef_)
fresh = clone(ridge)
print("clone keeps alpha:", fresh.alpha)
print("clone is unfitted:", not hasattr(fresh, "coef_"))clone keeps alpha=10.0 and drops coef_. Note that clone is not copy.deepcopy, which would copy the learned state too.
Transformers use the same pattern
Preprocessing steps such as StandardScaler follow the same idea with a different method. A transformer has fit(X) to learn from data, for example the column means and standard deviations. It then has transform(X) to apply what it learned. The shortcut fit_transform(X) does both in one call on the same data.
The rule that matters is that you call fit or fit_transform on training data only. For new data, call transform alone. If you fit a scaler on the full dataset before splitting, information from the test set leaks into training. Pipelines, covered later, enforce this rule for you. They expose the same fit, predict and score methods, so a whole pipeline is used like a single estimator.
Exercises
Exercise
You run LinearRegression().fit(X[:, 0], y) and get a ValueError. What is wrong, and give two ways to fix it?
Show answer
X[:, 0] is 1D, but estimators need X with shape (nsamples, nfeatures). Use X[:, [0]] or X[:, 0].reshape(-1, 1), which both keep a second dimension of size 1.
Exercise
A colleague calls scaler.fit_transform(X_test) on a StandardScaler that was already fitted on X_train. Why is that a problem, and what should they call instead?
Show answer
fit_transform refits the scaler on the test data, so the test set is scaled with its own mean and standard deviation instead of the training statistics. This breaks the held-out setup and can leak information. They should call scaler.transform(X_test).
Exercise
After fitting, model.score(X_test, y_test) returns -0.4. What does that tell you?
Show answer
For a regressor, score is R-squared. A negative value means the model predicts the test targets worse than a constant prediction equal to the mean of y_test.