Lesson 4 of 9 · 22m
The scikit-learn Fit/Predict Contract
Learn estimators, transformers, predictors, and why the consistent scikit-learn API is a discipline tool rather than mere convenience.
Scikit-learn's greatest contribution is not any particular algorithm. It is a contract: objects learn state with fit, transform data with transform, and make predictions with predict. That boring consistency is what allows preprocessing, model selection, pipelines, and cross-validation to compose without bespoke glue code. Treat violations of the contract as design smells.
Estimators are stateful objects
A model is not a pure function. It has learned parameters after fitting:
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
prob = model.predict_proba(X_test)[:, 1]Calling fit again replaces learned state. Passing different column order produces different meaning even if shape matches. The model does not know your feature names unless the object explicitly stores them.
Transformers learn too
Preprocessors are not static functions. They learn statistics:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)fit_transform on test data is leakage. It tells preprocessing what the evaluation distribution looks like before the evaluation. In production terms, it is equivalent to peeking at tomorrow's users when deciding how to normalize today's.
Choose the baseline before the fancy model
New teams reach for gradient boosting because it feels professional. Senior practitioners establish a baseline first:
from sklearn.dummy import DummyClassifier
from sklearn.metrics import average_precision_score
baseline = DummyClassifier(strategy='prior')
baseline.fit(X_train, y_train)
print(average_precision_score(y_test, baseline.predict_proba(X_test)[:, 1]))If your sophisticated model barely beats predicting the class prior, the problem is data, features, or evaluation — not the model family. Baselines are how you detect wasted complexity.
Know the estimator families
Scikit-learn objects follow broad roles:
Transformer scaler, encoder, imputer, feature selector
Predictor classifier, regressor
Clusterer fit/predict or fit_predict depending on algorithm
Pipeline composition object exposing the same outer contract
Meta-estimator GridSearchCV, CalibratedClassifierCV, ensembles of estimatorsThe important question is always the same: what state is learned during fit, and when exactly is that state allowed to see evaluation rows?
Inputs are matrices, not dataframes by magic
Scikit-learn accepts pandas dataframes, numpy arrays, sparse matrices, and sometimes mixed representations, but each estimator has expectations. Sparse input is essential for high-cardinality text or categorical features:
from scipy import sparse
X_sparse = sparse.csr_matrix(X_dense)
model.fit(X_sparse, y_train)Do not densify sparse matrices casually. I have watched a compact 300 MB sparse matrix become a machine-killing 40 GB dense array because someone wanted to print a row.
Field notes
fitis not free; refitting inside loops can dominate runtime.predictreturning hard labels hides ranking quality. Inspectpredict_probaordecision_functionwhen available.- Feature names matter when debugging, even though most algorithms consume positions numerically.
- Some estimators expect finite input and reject
NaN; others can handle missing values natively. - Keep preprocessing and model objects together or deployment will recreate training inconsistently.
Was this lesson helpful?