Sub topic 6
Estimators and the fit method
This chapter assumes you can read basic Python classes and methods, know what a NumPy array shape is, and have seen the X (features) and y (labels) split from earlier chapters. Here you learn what an estimator is and what fit does.
What an estimator is
In scikit-learn, an estimator is any object that learns something from data. Every estimator follows the same pattern:
- Create the object and set its configuration in the constructor.
- Call
fitwith training data. The object learns from it. - Use the learned object, for example to predict.
Because every model shares this pattern, you can swap LogisticRegression for another classifier and change very little code.
Configure, then fit
The constructor only stores settings. It does not look at data. The fit method does the learning.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
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)
print(model.coef_.shape) # (3, 4), learned during fit
print(model.predict(X_test[:5]))
print(model.score(X_test, y_test))Line by line:
LogisticRegression(max_iter=200)creates an unfitted estimator.max_iteris a setting you choose.model.fit(X_train, y_train)takes the 2D feature array and the 1D label array. It finds the best coefficients for the training rows.model.coef_holds what was learned. It has shape(3, 4): one row per class and one column per feature.predictandscoreuse the learned values on rows the model has not seen.
What fit does and returns
fit has three properties worth remembering.
- It modifies the estimator in place. You do not need to assign a new object to keep the result.
- It returns
self. This allows chaining, such asLogisticRegression().fit(X_train, y_train).predict(X_test). - It stores results in attributes whose names end with an underscore, such as
coef_andclasses_.
The trailing underscore is a convention that tells you "this exists only after fitting". Settings from the constructor have no underscore.
Unfitted estimators raise errors
If you call predict before fit, scikit-learn raises a NotFittedError. This is a useful check. It means a missing fit call fails loudly instead of returning nonsense.
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
try:
model.predict([[5.1, 3.5, 1.4, 0.2]])
except NotFittedError as err:
print("Not fitted yet")Common mistakes
- Fitting on all the data. Fit on
X_trainandy_trainonly. If you fit on the test set, your score is no longer an honest estimate. - Wrong shapes.
Xmust be 2D, even with one feature. UseX.reshape(-1, 1)for a single column.yis 1D. - Mismatched row counts.
Xandymust have the same number of rows, orfitraises aValueError. - Reading attributes too early.
model.coef_does not exist untilfithas run.
Exercise
You run model = LogisticRegression(C=2.0) and then immediately print model.coef_. What happens, and what two steps fix it?
Show answer
It raises an AttributeError, because coef_ is an attribute learned during fit and does not exist on an unfitted estimator. Call model.fit(X_train, y_train) with a 2D feature array and a 1D label array, and then read model.coef_.
Exercise
A colleague writes model = LogisticRegression().fit(X_train, y_train). Does model hold the fitted estimator or something else? Why?
Show answer
It holds the fitted estimator. fit returns self, so the assignment stores the same object that was just trained.