Concepts / The fit Method in scikit-learn

The fit Method in scikit-learn

The learned result is then available to the methods that come later.

  • Programming

Fitting Is Only the First Step

Every scikit-learn estimator goes through a two-part life. First you fit it on data, then you put it to work. Fitting is the step where the estimator learns from data, and it is easy to think of it as the finish line. It is not. Fitting only learns from data. By itself it does not tell you anything about new data.

What do you think happens?

You have a fitted model and a new batch of inputs X_new. Does calling transform on X_new give you predicted labels y?

  • Yes, transform returns predicted labels y

  • No, transform returns a new representation of X

Reveal answer
Answer:

No, transform returns a new representation of X

Transform does not produce an output such as y. It produces a new representation of the input data X, such as reshaped or reduced inputs. Predicted labels come from predict.

The question that follows fitting is what you want back from the model. The answer splits into two broad families. One family returns a new output for each input. The other returns a reshaped version of the inputs. A third method, score, serves a separate purpose: evaluating a supervised model. The methods in this article are predict, transform, and score.

What Fitting Leaves Behind

Fitting is the step that gives the other methods something to work with. During fit, the estimator takes in training data and learns from it. The learned result is then available to the methods that come later. Those later calls do not relearn anything from scratch. They reuse what fit learned, applied to whatever inputs you pass in.

Your codecalls the methodsEstimatorholds learned state1. fit(X_train, y_train) learns state2. predict(X_test) reuses learned state3. transform(X_test) reuses learned state4. score(X_test, y_test) reuses learned state
What happens in order when I call fit, then predict or transform, and where does the learned state come in?

The diagram shows the order of calls. Fit comes first and does the learning. The later calls can happen in any order you need, and each one applies the learned state to inputs you provide. Once you see fit as the setup step, the other methods read as different ways of using the same fitted object.

Predict: A New Output for Each Input

Definition

The predict method creates a prediction in the form of a new output, which is usually called y. You call it on a fitted estimator and pass in the inputs you want predictions for.

python
Notes on the code
  • fit learns from the training inputs and labels
  • predict is called on the fitted model with the inputs to predict for
  • y_pred is the new output produced for each row of X_test

Here X_test is the set of inputs you want to predict for, and y_pred is the output the estimator produces for them. The method is used for classification, regression, and clustering. In each case the output is a new value or label attached to each input. That is why predict is the method you reach for when the question is what the model thinks each input corresponds to.

Transform: A New Representation of X

The transform method answers a different question. Instead of producing an output such as y, it creates a new representation of the input data X. The call has the same shape as predict, but the result is a different kind of object.

python
Notes on the code
  • fit learns the state the scaler needs from the training inputs
  • transform returns a re-described version of X_test
  • X_new is still a representation of the same inputs, not a set of predicted labels

The result X_new is still a representation of the same inputs, but it is no longer the original data. The typical uses of this method are preprocessing, dimensionality reduction, feature extraction, and feature selection. Each of these changes how the inputs are described, not what the model guesses about them. This is the key contrast with predict. A transform call hands back reshaped inputs, while a predict call hands back a prediction.

X_test inputspredict(X_test)a new output, usually ytransform(X_test)a new representation of Xone output per input rowone re-described row per input row
If I pass the same X to a fitted estimator, how do the outputs of predict and transform differ in kind and shape?
Aspectpredicttransform
What it returnsA new output, usually yA new representation of X
Typical usesClassification, regression, clusteringPreprocessing, dimensionality reduction, feature extraction, feature selection
Question it answersWhat does the model think each input corresponds to?How should the inputs be described for the next step?
Where the result usually goesConsumed as an answerPassed onward to a pipeline step or a model

Predict and transform both take inputs X, but they serve different goals.

Choosing a Method for Your Goal

A helpful way to pick a method is to ask what the result is for. Predict results are typically consumed as answers. Transform results are typically passed onward, either to another step in a pipeline or to a model that will consume the new representation. Score sits apart from both, because its purpose is evaluation rather than output or representation.

What do you needback?A new output for eachinputpredictA new representationof XtransformAn evaluation withtrue labelsscoreanswer or labelreshaped inputsmeasure quality
Given my goal, which method do I call, and what is the decision path from the goal to predict, transform, or score?

Read the flowchart from the top. If the goal is a prediction such as what class or value each input belongs to, call predict. If the goal is to change how the inputs are described before a later step, call transform. If the goal is to judge how well a supervised model is doing, call score.

Score: Evaluating Against True Labels

The third method is score. Its purpose is evaluation rather than output or representation. All supervised models have a score method that allows an evaluation of the model. It takes two inputs: the test data and the test labels.

python
Notes on the code
  • X_test supplies the inputs the model is evaluated on
  • y_test supplies the true labels those predictions are compared against
  • the call returns a single evaluation number

Because score needs y_test, it can only be used when you have labels for the inputs you are evaluating. This is why the method is tied specifically to supervised models. The data flows in two directions at once: the inputs go through the fitted model, and the model's results are compared against the true labels to produce one number that summarizes how well it did.

Definition

Naming convention: X_train and y_train refer to the training data and training labels. X_test and y_test refer to the test data and test labels, which are used only if applicable. Keeping this convention in mind helps you read which data each method call should receive.

Mistakes With Choosing and Calling Methods

The three methods share a similar call pattern, which makes them easy to confuse. The following mistakes come up often when a learner first applies them.

  • Common mistake

    Expecting transform to return predicted labels

    What it looks like
    labels = model.transform(X_test)
    Why it fails

    Transform creates a new representation of the input data X. It does not produce an output such as y.

    Do this instead

    Use predict when you want the model's output for each input, and transform when you want reshaped inputs.

  • Common mistake

    Calling predict when the goal is preprocessing

    What it looks like
    X_scaled = model.predict(X_test) when preparing inputs for a later step
    Why it fails

    Predict returns a prediction, not a re-described version of X that a later step can consume.

    Do this instead

    Call transform to get a new representation of X that is passed onward.

  • Common mistake

    Calling score without true labels

    What it looks like
    model.score(X_test)
    Why it fails

    Score needs y_test to compare predictions against. Without labels there is nothing to evaluate against.

    Do this instead

    Pass both the test data and the test labels: model.score(X_test, y_test).

  • Common mistake

    Evaluating on training data and calling it test performance

    What it looks like
    model.score(X_train, y_train) reported as the model's test result
    Why it fails

    The naming convention reserves X_test and y_test for evaluation. Training data does not show how the model handles inputs it was not fitted on.

    Do this instead

    Evaluate with X_test and y_test, keeping the test data separate from the data used in fit.

Worked Example: Three Calls, Three Different Results

Worked example

One fitted model, three different goals

A model has been fitted on training data. You now have a batch of 3 new test rows and their true labels. Work out which method to call for each goal and what each call returns.

  1. 1
    Goal 1: a label for each new row

    The goal is a new output for each input, so the method is predict. The call model.predict(X_test) returns one output per row, 3 values in total.

  2. 2
    Goal 2: reshaped inputs for a later step

    The goal is a new representation of X, so the method is transform. The call returns one re-described row per input row, still 3 rows, but no predicted labels.

  3. 3
    Goal 3: how well the model does on these rows

    The goal is evaluation against true labels, so the method is score. The call model.score(X_test, y_test) takes both inputs and returns a single evaluation number for the whole batch.

Result

predict gives 3 outputs, transform gives 3 re-described rows, and score gives 1 evaluation number. The method is chosen by what you need back, not by which data you have.

Practice Choosing the Right Method

EASY

You have a fitted scikit-learn estimator and a new batch of inputs X_new. For each goal below, name the method you would call and say what it returns: (a) the model's guess for each row, (b) a re-described version of the rows to feed into a later step, (c) a single number measuring how well the model matches the true labels for these rows.

Hints
  • Ask what the result is for: an answer, a passed-on representation, or an evaluation.
  • Score is the only one of the three that takes true labels as a second input.
  • The method that returns predicted labels is the one tied to classification, regression, and clustering.

Summary of the Three Methods

  1. 1
    Fitting learns from data but does not by itself say anything about new data; predict, transform, and score put the fitted model to work.
  2. 2
    predict produces a new output, usually y, for each input, and is used for classification, regression, and clustering.
  3. 3
    transform produces a new representation of the input data X, typically for preprocessing, dimensionality reduction, feature extraction, or feature selection.
  4. 4
    score takes the test data and test labels and returns an evaluation of a supervised model, so it needs y_test.

At a glance

  • Fitting learns from data, and the other methods reuse that learned state on inputs you pass in.
  • predict returns a new output, usually y, for each input.
  • transform returns a new representation of X, not a prediction.
  • Choose the method by the goal: output, reshaped inputs, or evaluation.
  • score needs test data and test labels, and it is used to evaluate supervised models.

Related concepts

More concepts starting with T