Module 3 · Beginner · Data preparation and EDA

Scikit-learn tutorial: fit, predict, transform

A scikit-learn tutorial for beginners: estimators, fit, predict and score, transformers and fit_transform, train_test_split, and the errors you'll meet first.

By theprogrammers team · · 15 min read

Every UPI app looks different, but they all work the same way: scan, enter the amount, enter the PIN. Learn it once and you can pay with any of them. Scikit-learn is like that for machine learning. A straight line, a decision tree and a random forest are very different inside, but you use all of them with the same few method calls.

Scikit-learn (imported as sklearn) is the most used Python library for classic machine learning. A scikit-learn tutorial for beginners only needs those few calls: fit to learn from data, predict to make predictions, transform to change data, and score to check the result. You'll also meet the error messages beginners hit first, and what each one means.

What you need first: data, features and labels, the NumPy array tutorial, and a working setup from set up a machine learning environment.

Key terms

  • Estimator: any scikit-learn object that learns from data. Every model is an estimator.
  • fit: the method that learns from training data. Before fit, the object knows nothing.
  • predict: the method that uses what was learned to give answers for new rows.
  • Transformer: an estimator that changes data instead of predicting, such as a scaler. It has fit and transform.
  • Hyperparameter: a setting you choose before training, such as the number of neighbours. You pass it when you create the object.
  • Learned parameter: a number the estimator works out during fit. Its name ends in an underscore, such as coef_.

The pattern: create, fit, predict

Here are five second-hand phones: their age in months, their storage in GB, and the price they sold for. (The numbers are made up.)

import numpy as np

X = np.array([[12, 128], [30, 64], [18, 128], [6, 128], [40, 64]])   # age, storage
y = np.array([14500, 4200, 11800, 16900, 3100])                    # price in ₹
print(X.shape, y.shape)
(5, 2) (5,)

X has 5 rows and 2 columns, one row per phone. y has one price per phone. Every model in scikit-learn takes data in exactly this shape: X is 2D (rows × features), y is 1D.

Now the three steps. LinearRegression fits a weighted sum of the features plus a constant; you'll learn how it works in the linear regression module. Here, focus on how it's used:

from sklearn.linear_model import LinearRegression

model = LinearRegression()     # 1. create: choose the model (and its settings)
model.fit(X, y)                # 2. fit: learn from the examples
print(model.predict([[24, 128]]))   # 3. predict: a 24-month-old, 128 GB phone
[10849.18032787]

That's the whole pattern. fit changes the model object itself: before it, the model has no idea about phones; after it, it has learned numbers that turn age and storage into a price.

Notice the double brackets in predict([[24, 128]]). The model expects a table, even for one phone, so you give it a list containing one row.

What did it learn?

Learned numbers live in attributes ending with an underscore. The underscore is scikit-learn's signal for "this only exists after fit":

print("weights:", np.round(model.coef_, 1))
print("intercept:", round(float(model.intercept_), 1))
weights: [-295.9   61.6]
intercept: 10062.3

Read the weights as: each extra month of age changes the price by the first number (in ₹), and each extra GB of storage by the second. Predict: using these, roughly what would a brand-new (0 months) 128 GB phone sell for? Work it out from the intercept and weights, then check:

print(round(float(model.predict([[0, 128]])[0])))
print(round(float(model.intercept_ + model.coef_[0] * 0 + model.coef_[1] * 128)))
17951
17951

Both lines give the same number, because predict is just that weighted sum. There's no magic in predict: it's the formula the model learned in fit.

Hyperparameters go in the brackets

Settings you choose come in when you create the estimator. For example, fit_intercept=False forces the line through zero:

no_intercept = LinearRegression(fit_intercept=False).fit(X, y)
print(no_intercept.intercept_, np.round(no_intercept.coef_, 1))
0.0 [-135.9  126.1]

Two things to notice. First, fit returns the model itself, so LinearRegression(...).fit(X, y) in one line is common. Second, the learned weights changed completely, because you changed a setting. Choosing good hyperparameters is a big part of machine learning, and later lessons show how to choose them with data instead of guessing.

Score: how good is it?

Every model has score(X, y). For regression models it gives R² (read "R squared"): 1 means perfect, 0 means no better than always predicting the average. For classifiers it gives accuracy, the share of correct answers.

print(round(model.score(X, y), 3))
0.981

Very high, but don't celebrate: the model is being scored on the same five phones it learned from. That's like marking a student on the exact questions they practised. To know how a model does on new data, you score it on rows it never saw during fit.

Train and test sets with train_test_split

train_test_split shuffles the rows and cuts them into a training part and a test part. Here's a bigger made-up dataset of 200 phones, so the split has room to work:

from sklearn.model_selection import train_test_split

rng = np.random.default_rng(0)
age = rng.integers(1, 48, size=200)
storage = rng.choice([64, 128, 256], size=200)
price = 20000 - 300 * age + 40 * storage + rng.normal(0, 1500, size=200)
X_phones = np.column_stack([age, storage])

X_train, X_test, y_train, y_test = train_test_split(
    X_phones, price, test_size=0.25, random_state=42)
print(X_train.shape, X_test.shape)

model = LinearRegression().fit(X_train, y_train)
print("train R²:", round(model.score(X_train, y_train), 3))
print("test R²: ", round(model.score(X_test, y_test), 3))
(150, 2) (50, 2)
train R²: 0.905
test R²:  0.935

What the arguments mean:

  • test_size=0.25 keeps 25% of the rows (50 phones) for testing.
  • random_state=42 fixes the shuffle, so you get the same split every time you run the code. Any whole number works; 42 is only a habit. Without it, your scores change slightly on every run, which makes comparing two ideas confusing.
  • It returns four things, in this order: training features, test features, training labels, test labels. Mixing up the order is a common bug.

The test score is the one to believe. Here train and test R² are close, which is a good sign. The next lesson, train, validation and test sets, covers splitting properly.

Transformers: fit, then transform

Some estimators don't predict anything. They change data. The most common is StandardScaler, which rescales each column so it has a mean of 0 and a standard deviation of 1. You'll see why that matters in feature scaling; here it shows how transformers work.

Do it by hand first. For one column, subtract its mean, then divide by its standard deviation:

ages = np.array([[12.0], [30.0], [18.0], [6.0], [40.0]])
mean, std = ages.mean(), ages.std()
print("mean", mean, " std", round(float(std), 2))
print(np.round((ages - mean) / std, 2).ravel())
mean 21.2  std 12.3
[-0.75  0.72 -0.26 -1.24  1.53]

(ravel() flattens the column into one row, only to print it compactly.) Now the scikit-learn way:

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
scaler.fit(ages)                 # learns the mean and standard deviation
print(scaler.mean_, np.round(scaler.scale_, 2))
print(np.round(scaler.transform(ages), 2).ravel())   # applies them
[21.2] [12.3]
[-0.75  0.72 -0.26 -1.24  1.53]

Same numbers. Split into two steps:

  • fit learns the numbers it needs (here, the mean and standard deviation) and stores them in mean_ and scale_.
  • transform applies those stored numbers to whatever data you pass in.
  • fit_transform(data) does both in one call, on the same data.

Models and transformers share the same shape: fit learns and stores, and the second method reuses what was stored.

Two side-by-side flowcharts. A model such as LinearRegression: fit on the training data stores what it learned in coef_ and intercept_, and predict uses those to turn new data into predictions. A transformer such as StandardScaler: fit on the training data stores mean_ and scale_, and transform uses them to turn new data into rescaled data. Fit only ever sees training data.

Why keep them separate? Because of this rule, which you'll use in every project:

Fit on the training data only. Transform both the training and the test data with what was learned from training.

The test set stands in for data from the future. In real use, you won't know the mean of next month's data when you scale it, so your test must not know it either:

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)   # learn from training rows, then scale them
X_test_scaled = scaler.transform(X_test)         # scale test rows with the training mean and std
print(np.round(X_train_scaled.mean(axis=0), 2), np.round(X_test_scaled.mean(axis=0), 2))
[ 0. -0.] [0.29 0.21]

The training columns have mean 0, because the scaler learned from them. (The -0. is zero too: rounding a tiny negative number such as −0.0000000001 keeps its minus sign.) The test columns aren't exactly 0, and that's correct: they were scaled with the training numbers, and these 50 test phones happen to be a little older, with a little more storage, than the training phones on average. If you called fit_transform on the test set, you'd be letting test data influence the preprocessing, a mistake called data leakage.

A full example: classify penguins

Now a real dataset and a classifier. The goal: predict a penguin's species from four body measurements.

Download the data: penguins.csv (14 KB), or from the original source, the palmerpenguins project. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("penguins.csv").

import seaborn as sns

penguins = sns.load_dataset("penguins").dropna()
features = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
X = penguins[features]
y = penguins["species"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=0, stratify=y)
print(X_train.shape, X_test.shape)
print(y_train.value_counts(normalize=True).round(2).to_dict())
print(y_test.value_counts(normalize=True).round(2).to_dict())
(249, 4) (84, 4)
{'Adelie': 0.44, 'Gentoo': 0.36, 'Chinstrap': 0.2}
{'Adelie': 0.44, 'Gentoo': 0.36, 'Chinstrap': 0.2}

stratify=y makes the split keep the same share of each species in both parts. Without it, a small class like Chinstrap could end up mostly in one part by chance. Use it for every classification split.

The classifier is k-nearest neighbours (KNN): to classify a new penguin, it finds the k most similar penguins in the training data and lets them vote. You'll build it yourself in the KNN module. For now, it's one more estimator with fit and predict:

from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
predictions = knn.predict(X_test)
print(predictions[:5])
print("accuracy:", round(accuracy_score(y_test, predictions), 3))
['Adelie' 'Adelie' 'Adelie' 'Gentoo' 'Gentoo']
accuracy: 0.786

Decent, but not great. Predict: KNN judges "similar" by distance between measurements. Body mass is in grams (around 4,000) while bill depth is in millimetres (around 17). Which feature do you think dominates the distance? Now scale first, using the fit-on-train rule:

scaler = StandardScaler().fit(X_train)
knn_scaled = KNeighborsClassifier(n_neighbors=5).fit(scaler.transform(X_train), y_train)
predictions = knn_scaled.predict(scaler.transform(X_test))
print("accuracy with scaling:", round(accuracy_score(y_test, predictions), 3))
accuracy with scaling: 0.988

A big jump. Unscaled, a difference of 100 g in body mass counted as much as a difference of 100 mm in bill depth, which is absurd. Body mass drowned out the other three features. After scaling, all four count on the same footing. This is a model failing because of preprocessing, not because of the algorithm, and it happens all the time.

Classifiers can also give probabilities with predict_proba. Each row adds up to 1, with one column per class in the order of classes_:

print(knn_scaled.classes_)
print(knn_scaled.predict_proba(scaler.transform(X_test[:3])))
['Adelie' 'Chinstrap' 'Gentoo']
[[0.  1.  0. ]
 [0.4 0.6 0. ]
 [1.  0.  0. ]]

With n_neighbors=5, the probabilities are vote shares: 1.0 means all five neighbours agreed, 0.6 would mean three out of five.

Swap the model in one line

Because every estimator uses the same methods, trying another model is a one-line change. A decision tree learns a flowchart of yes/no questions about the features (you'll build one in the decision trees module):

from sklearn.tree import DecisionTreeClassifier

tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print("tree accuracy:", round(tree.score(X_test, y_test), 3))
tree accuracy: 0.952

The tree didn't need scaling: it asks questions like "is flipper length above 206 mm?" about one feature at a time, so units don't matter. Different algorithms need different preprocessing, and the algorithm lessons say which.

Experiment: change n_neighbors=5 to n_neighbors=1 and then to n_neighbors=100 in the scaled KNN, and run it again. With 1, accuracy is 0.976: the species are well separated once scaled, so copying the single nearest penguin mostly works. With 100, it falls to 0.893, and most of the new mistakes are Chinstraps. Only about 51 Chinstraps are in the training set, so 100 neighbours always include plenty of Adelies, and the small group gets outvoted. The number of neighbours is a hyperparameter, and both extremes are worse than a middle value.

The errors you'll meet first

You'll see these three errors in your first week. Here's each one, on purpose, so you recognise it:

from sklearn.exceptions import NotFittedError

ages_1d = np.array([12, 30, 18, 6, 40])
try:
    LinearRegression().fit(ages_1d, [14500, 4200, 11800, 16900, 3100])
except ValueError as error:
    print("1)", str(error).splitlines()[0])

try:
    StandardScaler().transform(ages)
except NotFittedError as error:
    print("2)", error)

try:
    knn_scaled.predict([[45.0, 15.0, 210.0]])
except ValueError as error:
    print("3)", error)
1) Expected 2D array, got 1D array instead:
2) This StandardScaler instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
3) X has 3 features, but KNeighborsClassifier is expecting 4 features as input.

What each means and the fix:

  1. "Expected 2D array, got 1D array instead": you passed a single column as a flat 1D array. Make it a table with one column: ages_1d.reshape(-1, 1). The -1 means "work out the number of rows yourself", and the 1 means one column. With pandas, use df[["age"]] (double brackets) instead of df["age"].
  2. "This StandardScaler instance is not fitted yet": you called transform or predict before fit. Fit first.
  3. "X has 3 features, but ... is expecting 4 features": new data must have exactly the same columns, in the same order, as the training data.

Common mistakes

  • Fitting a scaler on the test set, or on all the data before splitting. Fit on training data, transform both.
  • Scoring on the training data and trusting the number. Always report the test score.
  • Mixing up the order of train_test_split's outputs: it's X_train, X_test, y_train, y_test.
  • Forgetting stratify=y for classification, especially with a small class.
  • Forgetting random_state, then wondering why results change on every run.

Practice

  1. What's the difference between fit, transform and fit_transform?
Show the answer

fit learns numbers from data (such as a column's mean) and stores them. transform applies the stored numbers to some data. fit_transform does both on the same data. Use fit_transform on the training set and only transform on the test set, so the test set never influences what's learned.

  1. Spot the bug:
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.fit_transform(X_test)
Show the answer

The second line fits the scaler again, on the test set. Now the test data is scaled with its own mean and standard deviation instead of the training ones, so the model sees test rows on a different scale from what it learned, and the test set has influenced the preprocessing. It should be X_test_s = scaler.transform(X_test).

  1. Which attributes would you expect to exist after StandardScaler().fit(data), and which before? How can you tell from the names?
Show the answer

After fitting, mean_ and scale_ (among others) exist. Before fitting, they don't. Attributes ending in an underscore are learned during fit. Settings you passed in, such as with_mean=True, exist from the start and have no underscore.

  1. Train a KNeighborsClassifier(n_neighbors=5) on the scaled penguin data using only the two features bill_length_mm and flipper_length_mm. What's the test accuracy? Is it better or worse than with all four?
Show the answer
two = ["bill_length_mm", "flipper_length_mm"]
scaler_two = StandardScaler().fit(X_train[two])
knn_two = KNeighborsClassifier(n_neighbors=5).fit(scaler_two.transform(X_train[two]), y_train)
print(round(knn_two.score(scaler_two.transform(X_test[two]), y_test), 3))
0.94

0.94, a little below the 0.988 from all four features. Bill length separates Adelie from Chinstrap and flipper length separates Gentoo, so these two carry most of the information; bill depth and body mass fix the last few mistakes.

  1. You write model.predict(5) for a model trained on one feature. What error will you get, and how do you fix it?
Show the answer

A ValueError saying it expected a 2D array but got a scalar (a single number). The model wants a table: one row, one column. Write model.predict([[5]]), or np.array([5]).reshape(-1, 1).

  1. Why didn't the decision tree need scaled features, when KNN did?
Show the answer

KNN compares penguins by distance across all features at once, so a feature with big numbers (grams) dominates. A decision tree looks at one feature at a time and asks "is it above this value?", so the units of each feature don't affect the others.

Interview questions

Explain the difference between fit, predict and transform in scikit-learn.

fit(X, y) learns parameters from training data and stores them on the object. predict(X) uses a fitted model to produce outputs for new rows. transform(X) uses a fitted transformer (scaler, encoder) to change data. fit_transform combines fit and transform for efficiency on the training set.

Why should you never call fit on the test set?

The test set represents unseen future data. Fitting a scaler, encoder or model on it lets information from the test set into training, so the test score becomes optimistic and no longer measures real performance. Fit only on training data and apply the fitted object to the test set.

Key takeaways

  • Every scikit-learn model follows the same pattern: create (with settings), fit, then predict and score.
  • X must be 2D (rows × features); y is 1D. One column needs reshape(-1, 1) or double brackets.
  • Attributes ending in _ are learned during fit; hyperparameters go in the brackets when you create the object.
  • Transformers fit to learn and transform to apply. Fit on training data only.
  • train_test_split with random_state (and stratify=y for classification) gives a fair, repeatable test set.
  • Preprocessing can matter more than the algorithm: scaling took KNN on penguins from mediocre to excellent.

Frequently asked questions

Is scikit-learn enough to get a job in machine learning?

It covers the classic algorithms used in most real tabular-data work, and almost every data science interview expects you to know it. For deep learning (images, text, LLMs) you'll add PyTorch or TensorFlow later.

Can scikit-learn use pandas DataFrames directly?

Yes. You can pass DataFrames as X and Series as y. The model remembers the column names from fit and warns you if new data has different ones. Predictions come back as NumPy arrays.

What does random_state actually do?

It fixes the random number generator used for shuffling or random choices inside the function, so the result is the same every time you run the code. The particular number doesn't matter; using the same one makes results repeatable.

What to learn next

  1. Train, validation and test sets: split data properly, and why you need three parts.
  2. Feature scaling: when and why to scale, and which scaler to use.
  3. Scikit-learn pipelines: chain the scaler and the model so the fit-on-train rule happens automatically.