Sub topic 6
Estimators and the fit method
This chapter assumes you can write basic Python classes, know what a NumPy array shape is, and have already split data into X_train, X_test, y_train, and y_test. It covers what scikit-learn calls an estimator, what fit does, and the errors people hit most often when calling it.
What an estimator is
An estimator is any object that learns something from data. In scikit-learn, every estimator has a fit method. A classifier, a regressor, a scaler, and a clustering model are all estimators.
The library separates two moments in an estimator's life:
- Construction. You choose settings and pass them to the constructor. No data is involved. Nothing is learned yet.
- Fitting. You call
fitwith data. The estimator computes values from that data and stores them on itself.
Keeping these steps apart is what lets you create many configured-but-unfitted copies of a model, compare them, and fit each on different data.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(C=0.5, max_iter=200) # construction: settings only
print(model.C) # 0.5
print(hasattr(model, "coef_")) # False, nothing is learned yetThe signature of fit
For supervised estimators the signature is fit(X, y). X is the feature matrix with shape (n_samples, n_features). y is the label vector with shape (n_samples,). Row i of X must correspond to element i of y.
Unsupervised estimators, such as KMeans or StandardScaler, learn from X alone. Their fit still accepts a y argument, which is ignored and defaults to None. This keeps one calling convention, so Pipeline can call fit(X, y) on every step without checking what kind of step it is.
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)
returned = model.fit(X_train, y_train)
print(returned is model) # True
print(model.coef_.shape) # (3, 4)
print(model.classes_) # [0 1 2]What fit does and returns
fit does three things.
- It validates the input. It checks that
Xis two-dimensional, thatXandyhave the same number of rows, and that values are numeric and finite unless the estimator supports otherwise. - It learns from the data and stores the results as attributes on the object.
- It returns
self.
Returning self enables method chaining, as in LogisticRegression().fit(X_train, y_train).predict(X_test). It also means fit does not return predictions or a new model. The object you called it on is the fitted model.
Fitted attributes end in an underscore
Anything the estimator learns from data is stored in an attribute whose name ends with a single underscore, such as coef_, classes_, mean_, or n_features_in_. Constructor settings never end in an underscore. This convention lets you tell at a glance whether a value is something you chose or something the model computed.
Some attributes are set by almost every estimator:
| Attribute | Meaning |
|---|---|
| `n_features_in_` | Number of columns seen during `fit` |
| `feature_names_in_` | Column names, set only when `X` is a DataFrame with string column names |
| `classes_` | Sorted class labels, for classifiers |
import pandas as pd
from sklearn.linear_model import LinearRegression
df = pd.DataFrame({"rooms": [2, 3, 4, 5], "age": [30, 20, 10, 5]})
price = [100, 150, 210, 260]
reg = LinearRegression().fit(df, price)
print(reg.n_features_in_) # 2
print(reg.feature_names_in_) # ['rooms' 'age']
print(reg.coef_.shape) # (2,)Checking whether an estimator is fitted
Calling predict before fit raises NotFittedError. You can trigger the same check yourself with check_is_fitted, which looks for attributes ending in an underscore.
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression
from sklearn.utils.validation import check_is_fitted
model = LogisticRegression()
try:
model.predict([[5.1, 3.5, 1.4, 0.2]])
except NotFittedError as err:
print("not fitted:", type(err).__name__)
check_is_fitted(LogisticRegression().fit([[0], [1], [2], [3]], [0, 0, 1, 1]))
print("fitted")Fitting again replaces what was learned
Each call to fit starts from scratch. The new call discards earlier learned attributes and computes them again from the data you pass. It does not add to the earlier fit.
import numpy as np
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(np.array([[1.0], [2.0], [3.0]]))
print(scaler.mean_) # [2.]
scaler.fit(np.array([[10.0], [20.0], [30.0]]))
print(scaler.mean_) # [20.]The first fit leaves no trace. If you want to learn from data in several chunks, you need an estimator that supports partial_fit, such as SGDClassifier or MiniBatchKMeans. Plain fit never accumulates.
A few estimators accept warm_start=True in the constructor. They then begin the next fit from the previous solution instead of from scratch. This is an optimization that you request explicitly. It is not the default.
Where learning happens in the life cycle
The diagram shows the states an estimator passes through and which methods are legal in each.
Methods like predict, score, and transform read the learned attributes. They do not change them.
Input handling details
Arrays and DataFrames
fit accepts NumPy arrays, pandas DataFrames, SciPy sparse matrices, and nested lists. Internally most estimators convert the input to a NumPy array. When you pass a DataFrame, scikit-learn records the column names in feature_names_in_. Later calls to predict then check that the columns match the names seen in fit. A mismatch raises an error or warning, which catches column-order mistakes.
A 1D `X` is an error
A common mistake is passing a single feature as a flat array. X must be 2D, even with one column.
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([1.0, 2.0, 3.0, 4.0])
y = np.array([2.0, 4.0, 6.0, 8.0])
try:
LinearRegression().fit(x, y)
except ValueError as err:
print("error:", str(err).splitlines()[0])
model = LinearRegression().fit(x.reshape(-1, 1), y)
print(model.coef_) # [2.]The error message suggests reshaping with reshape(-1, 1) for a single feature or reshape(1, -1) for a single sample.
Missing values and strings
Most estimators reject NaN and raise a ValueError during fit. Some, such as HistGradientBoostingClassifier, handle missing values natively. Strings in X also fail for most models, which is why encoding categorical columns comes before fitting. Labels in y can be strings for classifiers. The model stores them in classes_ and returns them from predict.
Mismatched lengths
If X has 100 rows and y has 99 elements, fit raises ValueError: Found input variables with inconsistent numbers of samples. Check X.shape[0] == y.shape[0] first when you see this.
A column vector for y
If y has shape (n, 1) instead of (n,), many classifiers emit a DataConversionWarning and ravel it for you. Pass y.ravel() to avoid the warning.
Common mistakes
- Fitting on test data. Calling
fitonX_testthrows away what was learned from training and tests the model on data it was just fitted to. Fit on training data only. - Ignoring that
fitreturnsself. Writingmodel = LogisticRegression().fit(X, y)is fine, since the result is the fitted model. Writingpreds = model.fit(X, y)gives you the model, not predictions. - Reading attributes before fitting.
model.coef_raisesAttributeErroron an unfitted model. - Assuming a second
fitbuilds on the first. It replaces it, unless you usepartial_fitorwarm_start. - Changing column order between
fitandpredict. With NumPy arrays nothing warns you, and the model silently misreads the features.
Exercise
You run m = LogisticRegression(); m.fit(X_a, y_a); m.fit(X_b, y_b). Then you read m.coef_. Which data do the coefficients come from, and what would you use if you wanted the model to learn from both batches incrementally?
Show answer
The coefficients come only from X_b and y_b, because each call to fit discards what was learned before. For incremental learning, use an estimator that supports partial_fit, such as SGDClassifier, and call partial_fit on each batch. Alternatively, concatenate both batches and call fit once.
Exercise
A colleague writes model = LinearRegression().fit(x, y) where x = np.array([1.0, 2.0, 3.0]). It raises a ValueError. What is wrong and how do you fix it?
Show answer
x is one-dimensional, but fit needs a 2D X with shape (n_samples, n_features). Reshape it with x.reshape(-1, 1) so it has 3 rows and 1 column.