Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 15 min · revision 2

The Estimator Contract: fit, predict, score

Learn the scikit-learn estimator contract (hyperparameters in the constructor, learning in fit, attributes ending in an underscore, predict and score), use transformers and pipelines without leaking validation data, and see what loss each common model minimises.

Contentsand lesson path

What you will learn

  • Train and compare a dummy baseline, linear regression, logistic regression and k-nearest neighbours with the scikit-learn estimator API on a train/validation/test split.

Prerequisites: Data Handling

01. Why it matters

scikit-learn offers dozens of models, from a baseline that ignores its inputs to support vector machines. They all follow one small set of rules, the estimator contract. Once you know it, you can swap one model for another in a single line, compare several models with the same loop, and spot the evaluation bugs that the contract was designed to prevent. The same pattern appears in many other libraries (XGBoost, LightGBM and others offer scikit-learn compatible classes), so it is worth learning precisely.

This lesson uses the breast cancer dataset that ships with scikit-learn: 569 tumours described by 30 measurements, labelled malignant (0) or benign (1). Every script imports the same split, so save this file first. Tested with Python 3.12 and scikit-learn 1.9.

Python · split.py
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)        # 569 tumours, 30 features
X_train, X_val, y_train, y_val = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=0
)

stratify=y keeps the share of each class the same in both parts, and random_state=0 makes the split repeatable. The validation set is for comparing models; a separate test set, used once at the end, comes in the lab.

02. The contract, step by step

An estimator is any object that learns from data. Its life has three stages.

  1. Construct it with its hyperparameters, the settings you choose rather than learn, such as the regularisation strength C. The constructor only stores them; get_params() reads them back.
  2. Fit it with fit(X, y). X has shape (n_samples, n_features) and y has shape (n_samples,). Fitting learns the parameters and stores them as attributes whose names end in an underscore, such as coef_ (the weights) and classes_. The trailing underscore is a promise: "this exists only after fit". fit returns the estimator itself, so calls can be chained.
  3. Use it. predict(X) returns one prediction per row. Classifiers usually add predict_proba(X), one column of probabilities per class. score(X, y) returns a default metric: accuracy (the share of correct predictions) for classifiers, and R² for regressors. R² is 1 for perfect predictions, 0 for a model that always predicts the mean, and negative for one that does worse than that.

Calling predict before fit raises NotFittedError instead of returning made-up numbers.

Python · contract.py
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import LogisticRegression

from split import X_train, X_val, y_train, y_val

model = LogisticRegression(C=1.0, max_iter=5000)   # hyperparameters only
print("params:", {k: model.get_params()[k] for k in ["C", "max_iter"]})
try:
    model.predict(X_val)
except NotFittedError:
    print("predict before fit: NotFittedError")

returned = model.fit(X_train, y_train)              # learns from the data
print("fit returns the model itself:", returned is model)
print("learned: coef_", model.coef_.shape, "intercept_", model.intercept_.shape,
      "classes_", model.classes_)
print("predict:", model.predict(X_val[:5]))
print("predict_proba:\n", model.predict_proba(X_val[:2]).round(3))
print("score (accuracy):", round(model.score(X_val, y_val), 3))
Expected output
params: {'C': 1.0, 'max_iter': 5000}
predict before fit: NotFittedError
fit returns the model itself: True
learned: coef_ (1, 30) intercept_ (1,) classes_ [0 1]
predict: [1 0 0 1 0]
predict_proba:
 [[0.013 0.987]
 [1.    0.   ]]
score (accuracy): 0.937

coef_ has shape (1, 30): one row of weights for this two-class problem, one weight per feature. Each row of predict_proba adds up to 1, and the column order follows classes_. Accuracy is a fine default for a first look, but it can hide a lot; the next sections show why you need a baseline to read it.

03. Transformers, fit on training data only

A transformer is an estimator that changes the features instead of predicting. StandardScaler learns the mean and standard deviation of each column in fit and applies them in transform; fit_transform does both on the same data. The rule that matters: learn the statistics on the training data only, then apply those same numbers to validation, test and production data. The small example shows why.

Python · scaler_leak.py
import numpy as np
from sklearn.preprocessing import StandardScaler

train = np.array([[10.0], [20.0], [30.0]])
new = np.array([[30.0], [40.0], [50.0]])           # new data arrives later

scaler = StandardScaler().fit(train)               # learns mean 20 from train
print("transform with train statistics:", scaler.transform(new).ravel().round(2))
print("refit on the new rows instead:  ",
      StandardScaler().fit_transform(new).ravel().round(2))
Expected output
transform with train statistics: [1.22 2.45 3.67]
refit on the new rows instead:   [-1.22  0.    1.22]

With the training statistics, a raw value of 30 becomes 1.22 in both datasets, so the model sees the same number for the same input. Refitting on the new rows maps 30 to −1.22 and 40 to 0: the meaning of the features has shifted, and the model is fed inputs it never learned. When you refit on a validation set, there is a second problem: statistics of the validation data now shape the features it is scored on, which makes the evaluation dishonest.

A Pipeline chains transformers and a final model into one estimator. make_pipeline(StandardScaler(), LogisticRegression()) behaves like a model: fit fits the scaler on the training data and passes the scaled data on; predict and score only call transform. Because the whole chain is one object, you cannot forget a step in production, and cross-validation refits the scaler inside each training fold.

04. One loop, four models, and a baseline

Because every model follows the contract, comparing them is one loop. The first entry is DummyClassifier, which ignores the features and always predicts the most frequent class. It shows the score you get without learning anything. A real model is only useful if it clearly beats that number. k-nearest neighbours (k-NN) predicts the majority label of the k training rows closest to the input, so it needs scaled features. A linear SVM is a linear model trained with a different loss, explained in the next section.

Python · compare.py
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

from split import X_train, X_val, y_train, y_val

models = {
    "dummy (most frequent)": DummyClassifier(strategy="most_frequent"),
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression()),
    "k-NN, k = 15": make_pipeline(StandardScaler(), KNeighborsClassifier(15)),
    "linear SVM": make_pipeline(StandardScaler(), LinearSVC(C=0.1)),
}
for name, model in models.items():                 # one contract, four models
    model.fit(X_train, y_train)
    print(f"{name:<22} validation accuracy {model.score(X_val, y_val):.3f}")

knn = models["k-NN, k = 15"][-1]
logreg = models["logistic regression"][-1]
print("k-NN keeps", knn.n_samples_fit_, "training rows to search at predict time")
print("logistic regression keeps", logreg.coef_.size + 1, "numbers")
Expected output
dummy (most frequent)  validation accuracy 0.629
logistic regression    validation accuracy 0.958
k-NN, k = 15           validation accuracy 0.951
linear SVM             validation accuracy 0.958
k-NN keeps 426 training rows to search at predict time
logistic regression keeps 31 numbers

The baseline already scores 0.629, because 63% of the tumours are benign. So "95% accuracy" means the models remove most of the remaining errors, not that they are 95% clever. The three real models are close; with only 143 validation rows, a difference of one or two rows is noise.

The last two lines show a cost that accuracy does not. Logistic regression compresses what it learned into 31 numbers, and a prediction is one dot product. k-NN "training" just stores the 426 training rows, and every prediction searches them for the nearest 15. With millions of rows that search makes each prediction slow and memory-hungry, so for similar scores, the cheaper model to serve usually wins. Tree indexes or approximate search can speed up the search, but the stored data does not go away.

05. What fit minimises: losses, hinge and kernels

Behind every fit is a loss function: a number that is large when predictions are bad, which the model makes as small as it can. Linear regression minimises squared error. Logistic regression minimises log-loss, which punishes confident wrong probabilities heavily. A linear support vector machine (SVM) minimises the hinge loss. Write the label as −1 or +1 and the margin as label × score: positive means the right side of the boundary. The hinge loss is max(0, 1 − margin): zero once a point is on the right side by a margin of at least 1, and growing linearly when it is not.

Python · losses.py
import numpy as np
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC

# margin m = y * score with y in {-1, +1}: positive means the right side
for m in [-1.0, 0.0, 0.5, 1.0, 2.0]:
    hinge = max(0.0, 1 - m)
    log_loss = np.log(1 + np.exp(-m))
    print(f"margin {m:4.1f}: hinge {hinge:.3f}  log-loss {log_loss:.3f}")

X, y = make_moons(n_samples=400, noise=0.2, random_state=0)  # two curved classes
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
print("linear SVM on moons:", round(LinearSVC().fit(X_tr, y_tr).score(X_te, y_te), 3))
print("RBF-kernel SVM on moons:",
      round(SVC(kernel="rbf").fit(X_tr, y_tr).score(X_te, y_te), 3))
Expected output
margin -1.0: hinge 2.000  log-loss 1.313
margin  0.0: hinge 1.000  log-loss 0.693
margin  0.5: hinge 0.500  log-loss 0.474
margin  1.0: hinge 0.000  log-loss 0.313
margin  2.0: hinge 0.000  log-loss 0.127
linear SVM on moons: 0.9
RBF-kernel SVM on moons: 0.93

The two losses agree on direction but not on detail. The hinge loss stops caring about a point once its margin reaches 1, so only points near the boundary (the support vectors) shape the model. Log-loss keeps rewarding larger margins a little, and its output can be read as a probability. That is why LinearSVC has no predict_proba. In scikit-learn 1.9 the old probability=True option of SVC is deprecated; wrap the model in CalibratedClassifierCV if you need probabilities.

A kernel lets an SVM draw curved boundaries. Instead of the plain dot product between two rows, it uses a similarity function such as the RBF (radial basis function) kernel, which is large for nearby points. On the two interleaving "moons" a straight line misclassifies points where the classes curl into each other, while the RBF kernel follows the curves. Kernels cost more as data grows, since they compare rows with each other, so they suit small and medium datasets.

06. Check your understanding

Practice check · 3 questions

Reading the contract

Predict what scikit-learn does in each case.

Q1. A learner runs `model = LogisticRegression()` and then `model.predict(X_val)` straight away. What happens?
Q2. What does `LinearRegression().fit(X_train, y_train).score(X_val, y_val)` return?
Q3. After `pipe = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y)`, where are the learned feature weights?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project, write a helper evaluate(models, X_train, y_train, X_val, y_val) that fits every estimator in a dictionary and returns a table of validation scores. Use it with a DummyRegressor, LinearRegression and a scaled KNeighborsRegressor on load_diabetes. Add one column with the number of values each model must keep to make predictions, and write one sentence on which model you would serve and why.

08. Review prompt

Without looking back, explain the three stages of an estimator and what the trailing underscore means; why a scaler must be fitted on training data only and how a Pipeline enforces it; what a dummy baseline tells you about an accuracy score; why k-NN is costly to serve on large data; and how the hinge loss differs from log-loss.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check