Sub topic 3
The estimator API: fit, predict, score
This chapter assumes you know basic Python, NumPy array shapes, and what a linear model is from the previous chapter. It covers the three methods that nearly every scikit-learn model shares. Once you know them, you can use any regressor in the library the same way.
The three core methods
Every scikit-learn model is an estimator, an object that learns from data. Regressors share this interface:
fit(X, y)learns parameters from training data and returns the estimator itself.predict(X)returns predicted targets for new rows.score(X, y)returns a default quality number. For regressors this is R-squared.
X is a 2D array of shape (n_samples, n_features). y is a 1D array of shape (n_samples,). Features are the input columns. The target is the value you want to predict.
A minimal example
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([5.0, 7.0, 9.0, 11.0])
model = LinearRegression()
model.fit(X, y)
print(model.predict(np.array([[5.0], [6.0]])))
print(model.score(X, y))The data follow y = 2x + 3 exactly. The model predicts about 13 and 15 for the new rows. The score is 1.0 because the fit is perfect.
Parameters you set versus parameters learned
You choose settings when you create the object, such as LinearRegression(fit_intercept=True). These are hyperparameters. They control how learning happens.
The values learned by fit are stored as attributes that end with an underscore, such as coef_ and intercept_. The trailing underscore is a convention. It tells you the attribute exists only after fitting.
print(model.coef_, model.intercept_)This prints roughly [2.] and 3.0.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `NotFittedError` | Called `predict` or read `coef_` before `fit` | Call `fit` first |
| `Expected 2D array, got 1D array` | Passed a flat array as `X` | Use `X.reshape(-1, 1)` for one feature |
| `X has 2 features, but ... expecting 1` | Predicted with a different number of columns than in training | Keep the same columns in the same order |
Why the shared interface matters
Swapping LinearRegression for Ridge changes one line. The calls to fit, predict and score stay the same. Later chapters rely on this. Pipelines and cross-validation work because they only need these methods.
Exercise
You run LinearRegression().fit(X, y) with X of shape (100,). scikit-learn raises an error. What is wrong, and how do you fix it?
Show answer
X is 1D, but the estimator expects shape (n_samples, n_features). Reshape it with X.reshape(-1, 1) if it holds a single feature.