In scikit-learn, fit learns from data, transform applies what was learned to change data, and predict uses a fitted model to produce outputs. fit_transform is fit followed by transform on the same data, and you call it on the training set only. For validation, test and new data, call transform or predict, never anything that fits again.
That one rule prevents a common form of data leakage. A mean imputer and a standard scaler learn numerical quantities from the training set. Calculating them from the full dataset leaks information from the evaluation population into the fitted workflow.
fit vs transform vs fit_transform vs predict at a glance
| Method | What it does | Returns | Found on | Call it on |
|---|---|---|---|---|
fit(X, y) |
Learns from the data and stores it in attributes ending in _ |
The estimator itself, so calls can chain | Every estimator | Training data only |
transform(X) |
Applies the learned state to change the data | The transformed data | Transformers: scalers, imputers, encoders, PCA | Training, test and new data |
fit_transform(X, y) |
Fits, then transforms the same data, sometimes more efficiently | The transformed training data | Transformers | Training data only |
predict(X) |
Uses the fitted model to output a label or a number for each row | One prediction per row | Classifiers, regressors, some clusterers | Any data, once fitted |
predict_proba(X) |
Outputs a probability for each class | One row of probabilities per sample | Classifiers that support it | Any data, once fitted |
fit_predict(X) |
Fits, then returns a label for each training row | Cluster or outlier labels | Clusterers and outlier detectors | The data you are grouping |
score(X, y) |
Predicts, then compares with y |
Accuracy for classifiers, R² for regressors | Classifiers and regressors | Validation or test data |
The scikit-learn glossary defines each of these methods. Calling transform or predict before fit raises a NotFittedError.
Why test data gets transform, not fit_transform
A scaler learns a mean and a scale from the training rows. Calling transform on the test rows reuses them. Calling fit_transform on the test rows learns new ones, so the same raw value lands somewhere different:
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[1.0], [2.0], [3.0], [6.0]])
X_test = np.array([[4.0], [10.0]])
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train) # learn mean and scale, then apply them
X_test_scaled = scaler.transform(X_test) # reuse the training mean and scale
print("learned mean and scale:", scaler.mean_, scaler.scale_.round(3))
print("test with transform:", X_test_scaled.ravel().round(3))
wrong = StandardScaler().fit_transform(X_test) # refits on the test rows
print("test with fit_transform:", wrong.ravel().round(3))
learned mean and scale: [3.] [1.871]
test with transform: [0.535 3.742]
test with fit_transform: [-1. 1.]
With transform, the value 10 is 3.7 training standard deviations above the training mean: an unusual input the model should treat as unusual. Refitting on the test rows turns it into a modest 1.0, and 4 into -1.0, a coordinate system the model never trained in. With more test rows the damage is quieter but the same: the test set has helped define its own preprocessing.
A pipeline removes the need to remember this. During training it calls fit_transform on each preprocessing step and fit on the final model; afterwards, predict runs only transform on each step before the model predicts.
A pipeline that keeps learned state inside training
Our training table has one feature, four records and one missing value. The held-out table contains a very large value and a missing value. The unusual test value makes leakage visible: a full-data mean would differ from the training-only mean.
This is a fixed teaching split chosen to inspect API behavior, not an estimate of model quality. A real experiment needs an evaluation design matching the prediction population, time boundaries and class frequencies.
The pipeline explicitly names its steps. After fitting, inspect named_steps to confirm which statistics were learned. A pipeline does not automatically fix target leakage or a bad split, but it keeps these fitted preprocessing operations together with the estimator during training and evaluation.
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
X_train = np.array([[0.], [2.], [np.nan], [4.]])
y_train = np.array([0, 0, 1, 1])
X_test = np.array([[100.], [np.nan]])
model = make_pipeline(SimpleImputer(), StandardScaler(),
LogisticRegression(C=1., solver='lbfgs'))
model.fit(X_train, y_train)
imputer = model.named_steps['simpleimputer']
scaler = model.named_steps['standardscaler']
before = scaler.mean_.copy()
print('training imputer mean:', imputer.statistics_.tolist())
print('training scaler mean:', scaler.mean_.tolist())
print('held-out transformed:', np.round(scaler.transform(imputer.transform(X_test)), 3).ravel().tolist())
print('predictions:', model.predict(X_test).tolist())
print('state unchanged:', np.array_equal(before, scaler.mean_))
print('leaky full-data mean:', float(np.nanmean(np.vstack([X_train, X_test]))))
assert imputer.statistics_[0] == 2
assert np.array_equal(before, scaler.mean_)
Checked output:
training imputer mean: [2.0]
training scaler mean: [2.0]
held-out transformed: [69.296, 0.0]
predictions: [1, 1]
state unchanged: True
leaky full-data mean: 26.5
Know which methods a step supports
A scaler has fit and transform, but it does not classify observations. A classifier has fit and predict; it need not expose transform. The final estimator determines which methods the pipeline can provide. predict_proba is available only when the final estimator supports it.
Calling predict on the fitted pipeline transforms the held-out rows with the stored imputer and scaler, then passes them to the classifier. Nothing is refitted, which is what the state unchanged: True line confirms.
The large transformed held-out value is expected. Standardization uses training statistics; it does not promise that all future values fall into a small interval. Treat such a value as a possible distribution or data-quality issue rather than refitting until the number looks comfortable.
When fit_transform is not the same as fit then transform
For most transformers, fit_transform(X) gives the same result as fit(X).transform(X), sometimes computed more efficiently. There are deliberate exceptions. scikit-learn's TargetEncoder uses cross fitting inside fit_transform, so each training row is encoded without its own target value, and its documentation states that fit(X, y).transform(X) does not equal fit_transform(X, y). Use fit_transform on the training data and transform on everything else, and these differences are handled for you.
Put cross-validation around the whole workflow
Pass the complete pipeline into cross-validation. Each fold then learns its preprocessing state from that fold's training partition. Fitting a scaler once before splitting folds shares information across the fold boundary.
Hyperparameter search uses the same pattern. Keep model selection separate from a final untouched test set, and use group-aware or chronological splits when records are dependent. Cross-validation for groups and time demonstrates why the splitter is part of the experiment.
Test the input contract too
A valid pipeline still needs the expected feature order, units and missing-value conventions. A one-column model cannot infer that a newly supplied column means something different. At a service boundary, check the schema and use the same feature construction as training.
Extend this example with a second feature and verify that both fitted means come only from the training rows. Then compare a fold-specific imputer against the invalid full-data alternative. The Data Tools track connects these APIs to end-to-end modeling in its scikit-learn API module, and the glossary defines estimator, fit and predict in a line each. Scaling versus normalization explains which transformation suits a particular geometry, and data leakage in machine learning shows how much a single refit in the wrong place can inflate a score.
Common questions
What is the difference between fit and fit_transform?
fit only learns: it stores the learned values on the object and returns the object. fit_transform learns and then returns the transformed training data in one call. Use fit when you only need the learned state, for example on a model, and fit_transform on a preprocessing step's training data.
Do I call fit on the test set?
No. Fitting is learning, and the test set must not teach the model or its preprocessing anything. Fit on the training data, then call transform, predict or score on the test data.
Does a model have a transform method?
Usually not. Classifiers and regressors provide predict; transformers such as scalers provide transform. A pipeline offers the methods of its final step, so a pipeline that ends in a classifier has predict but not transform.
Why does fit return self?
So calls can chain: StandardScaler().fit(X_train).transform(X_test) and model = LogisticRegression().fit(X, y) both work because fit returns the fitted object.
References
scikit-learn common pitfalls — Consistent preprocessing, data leakage and pipeline use.
Pipeline API — Which methods are supported and how steps are fitted and applied.