Sub topic 1
The Estimator API: fit, predict, transform
Every object in scikit-learn follows a small set of conventions. Once you know them, a Pipeline is only a way to chain objects that already agree on how to talk to each other. This chapter covers those conventions: what fit, predict, and transform do, where fitted state is stored, and which mistakes beginners make most often.
Prerequisites
This chapter assumes you can:
- Write basic Python, including classes and method calls.
- Use NumPy arrays and pandas DataFrames (shapes, indexing).
- Explain what features (
X), labels (y), and a train/test split are. - Fit a scikit-learn model with
fitandpredictat least once.
You do not need to know about pipelines yet. They come later in this tutorial.
Three roles, one interface
scikit-learn describes its objects by the methods they provide:
| Role | Key methods | Examples |
|---|---|---|
| Estimator | `fit` | Anything that learns from data |
| Predictor | `fit`, `predict`, often `predict_proba`, `score` | `LogisticRegression`, `RandomForestClassifier` |
| Transformer | `fit`, `transform`, `fit_transform` | `StandardScaler`, `SimpleImputer`, `OneHotEncoder` |
An estimator is any object that learns something from data by calling fit. A predictor is an estimator that produces outputs for new samples. A transformer is an estimator that produces a modified version of X. These roles are not exclusive, but most objects fit one of the last two.
The data layout is always the same. X has shape (n_samples, n_features): one row per sample, one column per feature. y has shape (n_samples,). Even a single feature must be passed as a 2D array. A 1D array raises an error that asks you to reshape it.
fit: learning from data
fit is where learning happens. For a predictor, it is fit(X, y). For an unsupervised transformer, it is fit(X). Transformers still accept a y argument, which is usually ignored. They accept it so that a pipeline can call every step the same way.
Three conventions apply to every fit:
fitreturnsself. This allows chaining such asmodel.fit(X, y).predict(X_new).- Learned values are stored as attributes whose names end with an underscore, such as
coef_,mean_, orclasses_. - Calling
fitagain discards the previous state and learns from scratch. It does not update the model.
Here is a scaler, the simplest useful transformer:
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 10.0], [2.0, 20.0], [3.0, 30.0]])
X_test = np.array([[4.0, 40.0]])
scaler = StandardScaler()
print(hasattr(scaler, "mean_")) # False: nothing learned yet
scaler.fit(X_train)
print(scaler.mean_) # [ 2. 20.]
print(scaler.scale_) # [0.81649658 8.16496581]
print(scaler.n_features_in_) # 2
print(scaler.transform(X_test)) # [[2.44948974 2.44948974]]The trailing underscore is how you tell a fitted attribute from a constructor parameter. with_mean is a setting you chose. mean_ is something the object computed.
predict, predict_proba, and score
Once a predictor is fitted, predict(X) returns one output per row. For classifiers, it returns class labels. For regressors, it returns numbers.
Many classifiers also provide predict_proba(X), which returns an array of shape (n_samples, n_classes). Each row sums to 1. The column order follows the classes_ attribute, so always check it before you interpret a column.
score(X, y) computes a default metric: accuracy for classifiers and R² for regressors. It predicts and compares in one call.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
clf = LogisticRegression(max_iter=1000).fit(scaler.transform(X_train), y_train)
X_test_scaled = scaler.transform(X_test)
print(clf.classes_) # [0 1]
print(clf.predict(X_test_scaled[:3])) # three labels
print(clf.predict_proba(X_test_scaled[:3])) # shape (3, 2)
print(clf.score(X_test_scaled, y_test)) # accuracy on the test setNotice what the code does with the test set. It calls scaler.transform(X_test), not fit. The scaler's statistics come from the training data only, and the test data is modified with those numbers. The next section explains why.
transform and fit_transform
transform(X) applies what fit learned. It does not learn anything. The output has the same number of rows as the input. It may have a different number of columns. OneHotEncoder expands one column into many, and some selectors drop columns.
fit_transform(X, y=None) is a shortcut for fit(X, y).transform(X). Some classes implement it more efficiently than two separate calls. Use it on training data only.
The following snippet shows the mistake that makes this distinction matter:
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0], [2.0], [3.0]])
X_test = np.array([[100.0]])
# Correct: statistics come from the training data only.
scaler = StandardScaler().fit(X_train)
print(scaler.transform(X_test)) # [[120.17...]]
# Wrong: the test data changes the statistics it is scaled with.
wrong = StandardScaler().fit_transform(X_test)
print(wrong) # [[0.]]The wrong version always gives every test column a mean of zero, whatever values the column holds. The model sees a different scale at prediction time than it saw in training, and the evaluation no longer measures how it will behave on new data.
A subtler version of the same error is calling fit_transform on the full dataset before splitting. Test-set information then flows into the training statistics. This is called data leakage, and the next chapters cover it in detail. The estimator API is built so that leakage-free code is easy to write, as long as you keep fit for training data and transform for everything else.
Parameters, clones, and constructors
Estimators separate hyperparameters, which you set, from fitted attributes, which are learned.
- Hyperparameters are passed to
__init__and stored unchanged under the same name. get_params()returns them as a dictionary.set_params(**kwargs)changes them.clone(estimator)returns a new, unfitted estimator with the same hyperparameters.
from sklearn.base import clone
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
clf = LogisticRegression(C=0.5, max_iter=1000).fit(X, y)
print(clf.get_params()["C"]) # 0.5
print(hasattr(clf, "coef_")) # True
fresh = clone(clf)
print(fresh.C) # 0.5
print(hasattr(fresh, "coef_")) # False: the clone is unfitted
fresh.set_params(C=2.0)
print(fresh.C) # 2.0Cloning matters more than it first seems. Cross-validation and grid search fit the same estimator many times on different data. They clone it before each fit, so no fold can see state from another fold. Pipelines use the same mechanism: get_params and set_params are what make step-prefixed names like clf__C work in a later chapter.
The constructor rule has a practical consequence for code you write. __init__ must only store arguments, and every argument must be stored under an attribute with the same name. Validation and computation belong in fit. If you break this rule, clone and get_params give wrong results.
Common errors
Calling predict or transform before fit. scikit-learn raises NotFittedError. You can run the same check yourself with check_is_fitted:
from sklearn.exceptions import NotFittedError
from sklearn.preprocessing import StandardScaler
from sklearn.utils.validation import check_is_fitted
scaler = StandardScaler()
try:
scaler.transform([[1.0, 2.0]])
except NotFittedError as err:
print("Not fitted:", type(err).__name__)
scaler.fit([[1.0, 2.0], [3.0, 4.0]])
check_is_fitted(scaler) # returns None when the estimator is fitted
print("Now fitted")Wrong number of features. The fitted estimator remembers n_features_in_. Passing data with a different number of columns at predict time raises a ValueError. When you fit on a DataFrame, the estimator also records feature_names_in_. If you later pass a DataFrame whose column names or order differ, scikit-learn raises an error or warns, depending on the version.
Passing a 1D array as X. A single feature must have shape (n, 1). Use X.reshape(-1, 1) or df[["col"]] with double brackets.
Refitting on test data. Calling fit or fit_transform on validation or test data replaces what the transformer learned. No error appears, so the bug is silent. A good rule is that fit and fit_transform appear only on training data.
Expecting fit to return something useful. fit returns self, not predictions or transformed data. Code like X_scaled = scaler.fit(X) assigns the scaler itself to X_scaled.
Assuming the output type. Transformers usually return NumPy arrays, even when given a DataFrame. This drops column names. In scikit-learn 1.2 and later, calling set_output(transform="pandas") on a transformer makes it return a DataFrame. The later chapter on inspecting pipelines returns to feature names.
Why a pipeline can exist
A Pipeline works because every step obeys this contract. It calls fit_transform on each intermediate step, passes the output to the next step, and calls fit on the final one. At prediction time it calls transform on each intermediate step and predict on the last. Since the pipeline itself provides fit and predict, it is an estimator too. You can hand it to cross_val_score or GridSearchCV as if it were one model.
The contract places two requirements on any step you write yourself. Every step except the last must have transform. Every step must accept fit(X, y), even if it ignores y.
Exercises
Exercise
You fit a StandardScaler on Xtrain and then call scaler.transform(Xtest). Your colleague says it would be "more consistent" to call scaler.fittransform(Xtest) so each set is scaled with its own mean and standard deviation. Give two reasons this is wrong.
Show answer
First, the model was trained on features scaled with the training statistics. Scaling the test data with its own statistics puts the features on a different scale than the model expects, so predictions are distorted. For example, a single test sample would always be scaled to zero. Second, in real use you often predict one sample or a small batch at a time, where batch statistics are meaningless or undefined. The saved training statistics (mean and scale) are the only stable reference, so test data must go through transform only.
Exercise
After running clf = LogisticRegression(C=0.5).fit(X, y), you run other = clone(clf). Does other have a coef_ attribute? Does other.C equal 0.5? Why does cross-validation clone estimators?
Show answer
other has no coef, because clone returns an unfitted copy. other.C equals 0.5, because clone copies the hyperparameters from getparams. Cross-validation clones the estimator before each fold so that every fold starts with no learned state, and so that no fold can use information from another fold.