Sub topic 1
The estimator API: fit, predict, transform
Every object in scikit-learn follows a small set of conventions. Once you know them, pipelines, cross-validation, and grid search all follow from the same few ideas. This chapter covers those conventions.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including classes and methods, plus NumPy arrays and pandas DataFrames.
- Supervised learning basics: features, labels, and a train/test split.
- Some experience fitting a scikit-learn model with
fitandpredict.
Three kinds of estimator objects
Scikit-learn calls any object that learns from data an estimator. Estimators come in three common kinds, and each kind has its own methods.
| Kind | Purpose | Key methods | Example |
|---|---|---|---|
| Estimator | Learns from data | `fit` | any of the below |
| Predictor | Makes predictions for new rows | `fit`, `predict`, `score` | `LogisticRegression` |
| Transformer | Rewrites features | `fit`, `transform`, `fit_transform` | `StandardScaler` |
A single class can be more than one kind. A pipeline, for example, is a predictor when its last step is a predictor.
fit: learning from data
fit(X, y) learns from the data and stores the result on the object. X is a 2-D array of features with shape (n_samples, n_features). y holds the labels. Unsupervised estimators and most transformers ignore y, but they still accept it so that all estimators share one signature.
Learned values are stored as attributes that end with an underscore, such as mean_ or coef_. Constructor arguments, called hyperparameters, have no trailing underscore. This lets you see at a glance whether an object has been fitted.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
scaler = StandardScaler() # hyperparameters are set here
scaler.fit(X_train) # statistics are learned here
print(scaler.mean_) # learned attribute: [ 2. 200.]
print(scaler.scale_) # learned attribute: standard deviationsfit returns self. That is why you can write StandardScaler().fit(X_train) in one line, and why a pipeline can chain calls.
predict and transform: using what was learned
After fitting, you apply the learned state to rows. A predictor uses predict. A transformer uses transform, which returns a new feature matrix and does not change the input.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
X_new = np.array([[4.0, 400.0]])
scaler = StandardScaler().fit(X_train)
print(scaler.transform(X_train)) # training rows, now centered and scaled
print(scaler.transform(X_new)) # new row, scaled with the TRAINING mean and scaleThe new row is scaled with the mean and standard deviation of X_train, not its own. This matters a great deal in the next chapters. The transformer must never learn from the rows it later transforms in validation or test data.
fit_transform(X, y) runs fit and then transform on the same data. Use it only on training data.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0, 100.0], [2.0, 200.0], [3.0, 300.0]])
X_train_scaled = StandardScaler().fit_transform(X_train)
print(X_train_scaled.mean(axis=0)) # approximately [0. 0.]The same pattern for models
Predictors follow the same two-step flow. You fit on training data, then call predict on rows you want labels for. score evaluates the predictions against known labels.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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)
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X_train, y_train)
print(clf.predict(X_test[:5]))
print(clf.score(X_test, y_test))Common errors
- Calling
transformbeforefit. Scikit-learn raisesNotFittedErrorbecause the learned attributes do not exist yet. - Refitting on test data. Calling
fitorfit_transformon test rows makes the transformer learn from data it should not see. The test rows then get different scaling than the training rows. - Wrong input shape.
Xmust be 2-D. For a single feature, useX.reshape(-1, 1). For a single row, useX.reshape(1, -1). - Changed columns at predict time. The number of features must match what was seen during
fit.
Exercises
Exercise
You fit a StandardScaler on Xtrain and then call scaler.transform(Xtest). Which mean is used to center X_test, and why?
Show answer
The mean of Xtrain, stored in scaler.mean. The scaler learned its statistics during fit and transform only applies them. Using the test mean would let test data influence preprocessing and would make train and test rows scaled differently.
Exercise
How can you tell from its attributes whether an estimator has been fitted, and what does fit return?
Show answer
Fitted estimators have attributes that end in an underscore, such as mean or coef. Unfitted ones do not. fit returns self, which allows chaining like StandardScaler().fit(X).