Live build, 12–13 Dec: turn an app agentic, no fee. Register →

Courses / Data Science & ML with AI

Session 4 of 8

Feature Engineering and Train/Test Splits in scikit-learn

Notes

Feature Engineering and Train/Test Splits in scikit-learn Without Data Leakage

Course: Data Science & ML with AI

Before you start

You need Python 3 with pandas, numpy and scikit-learn installed (pip install pandas numpy scikit-learn). Every example uses the breast cancer dataset that ships inside scikit-learn, plus two small category columns the chapter invents in code, so nothing is downloaded and no account is needed. You should know what a DataFrame is and have met the words feature, target and train/test split. All three are explained again below, so a quick read of the key concepts table is enough preparation.

Keep one question in mind while you read: how do I prepare my columns for a model, and test the model, without the test rows quietly influencing the preparation? By the end you will have a rule that answers it, and a check you can run on any preprocessing code, including code written by an AI assistant.

Summary

Feature engineering is the work of turning raw columns into inputs a model can use well: creating new columns from old ones, putting numbers on a comparable scale and turning categories into numbers. Before any of that is learned from the data, the rows are split once into a training set and a held-back test set, so the model is scored on rows it never saw. Every preparation step that learns something from the data, such as an average or a list of categories, must learn it from the training rows alone, because a step that also looks at the test rows leaks information into the score. This is called data leakage, and a scikit-learn Pipeline helps prevent it by keeping each preparation step and the model together so they are fitted on the training rows only. This chapter builds such a pipeline step by step and ends by teaching you to check an AI assistant’s preprocessing code for leakage.

Key concepts

Term Definition
Feature engineering Creating, transforming or selecting the input columns of a model so that they carry the useful signal in a form the model can use, such as a ratio of two columns or a scaled number.
Scaling (standardisation) Rewriting a numeric column so it has an average of 0 and a spread of 1: each value becomes (value minus the training average) divided by the training standard deviation.
Categorical column A column whose values are names from a short list, such as a clinic called north, south or east, rather than numbers on a scale.
One-hot encoding Replacing one categorical column with one 0/1 column per category, so a row has a 1 in the column of its own category and 0 in the others.
Train/test split Dividing the rows once at random into a training set the model learns from and a test set kept aside to score it on unseen rows.
Stratified split A split that keeps the share of each target class about the same in the training and test sets as in the full table.
random_state A whole number that fixes the shuffle in a split, so everyone who runs the code gets the same rows in the same sets.
Fit and transform fit learns numbers from data (an average, a list of categories); transform applies the learned numbers to rows. A fitted step can transform any rows, but it must learn only from training rows.
Data leakage Using information in preparation or training that would not be available when the model predicts for a new row, which gives an overly optimistic score.
ColumnTransformer A scikit-learn object that applies one preparation to some columns and a different one to others, then joins the results into one table.
Pipeline A scikit-learn object that chains preparation steps and a final model, so one fit call fits every step on the same rows and one predict call applies them all.
Unknown category A category that shows up in new rows but was not in the training rows, such as a clinic added after the model was built.

Explanations

The failure, before the explanation

A team prepares a table for a model. First they standardise every numeric column, using the average and spread of all 569 rows. Then they split the rows into a training set and a test set, train, and report the test score. Nothing raises an error and the code reads naturally, top to bottom. But the test rows already helped decide what “average” means for the model’s inputs. The test set was meant to stand in for rows the model has never seen, and it was not quite that.

The scikit-learn documentation names this problem data leakage and says it results in overly optimistic performance estimates. The effect in this particular example is small, as you will measure below, and that is exactly what makes it dangerous: the code looks right, the score looks fine and the damage, when there is any, is hidden. The rest of the chapter gives you the habit that prevents it.

Start with the data: a dataset that ships inside scikit-learn

Run this first block. It loads the breast cancer dataset, which scikit-learn’s documentation describes as a binary classification dataset with 569 samples, 30 numeric features and two classes, 212 malignant and 357 benign. The target is a 0/1 label, where 0 means malignant and 1 means benign.

import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer(as_frame=True)
X = data.data
y = data.target

print(X.shape, y.shape)
print(data.target_names.tolist())
print(y.value_counts().sort_index().to_dict())
print(X.isna().sum().sum())
print(X[["mean radius", "mean area"]].describe().loc[["mean", "min", "max"]].round(1))

It prints:

(569, 30) (569,)
['malignant', 'benign']
{0: 212, 1: 357}
0
      mean radius  mean area
mean         14.1      654.9
min           7.0      143.5
max          28.1     2501.0

There are 569 rows and 30 feature columns, no missing values, and the two classes are not equal in size: 357 of the 569 rows are benign. Look at the two columns printed. mean radius runs from 7 to 28, while mean area runs from about 144 to 2501. Those two numbers describe the same cells on very different scales, which matters in the next sections.

The train/test split: a practice exam and a real exam

Think of a student who prepares with a practice paper and then sits a different real paper. If the real paper were the practice paper, a high mark would show only that the student remembered the answers. A train/test split is the same idea for a model: the rows are divided once at random, and the model learns from the training set only. The test set stays aside and is used once, at the end, to measure how the model does on rows it has not seen. The previous chapter showed the cost of skipping this: a model that scored an error of 0.0 on its own training rows.

A second way to see it: a split is a rehearsal for the future. The model will be used on rows that do not exist yet, and the test set is the closest available stand-in for them. That only works if nothing about the test rows reaches the model before the final score.

In scikit-learn the split is one call. The documentation describes train_test_split as splitting arrays into random train and test subsets. A float test_size is the share of rows put in the test set, and when it is left out the test share is 0.25 by default. random_state given as a whole number makes the shuffle reproducible. The stratify option takes the labels and splits so the two sets have about the same percentage of each class as the full set.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
print(X_train.shape, X_test.shape)
print(round(y.mean(), 3), round(y_train.mean(), 3), round(y_test.mean(), 3))

_, _, y_a, y_b = train_test_split(X, y, test_size=0.25, random_state=42)
print(round(y_a.mean(), 3), round(y_b.mean(), 3))
(426, 30) (143, 30)
0.627 0.627 0.629
0.629 0.622

The first line shows 426 training rows and 143 test rows, a split of 0.25. Because the target is 0 or 1, its average is the share of benign rows: 0.627 in the full table, 0.627 in the training set and 0.629 in the stratified test set. The last line is the same split without stratify: the shares are 0.629 and 0.622, a little further apart. With 569 rows the difference is small. With a rare class, for example 1 positive in 100 rows, an unstratified split can leave the test set with almost none, so stratifying is the safer habit for a classification target.

Scaling numbers: why one column should not shout

Imagine comparing two people with a measuring tape in miles and a second one in millimetres. A difference of 1 means something completely different on each. Many models treat all columns as if their units were comparable, so a column measured in the thousands can drown one measured in tens. In the breast cancer table, mean area has values up to 2501 while mean smoothness is around 0.1.

Scaling, here standardisation, puts every numeric column on the same footing. The scikit-learn documentation gives the standard score of a value x as z = (x - u) / s, where u is the mean and s is the standard deviation of the training samples. Try it on three numbers by hand: 10, 20 and 30 have a mean of 20 and a standard deviation of about 8.16, so they become about -1.22, 0 and 1.22. Check it with the library:

from sklearn.preprocessing import StandardScaler

demo = np.array([[10.0], [20.0], [30.0]])
print(StandardScaler().fit_transform(demo).round(2).ravel().tolist())
[-1.22, 0.0, 1.22]

The word training in that definition carries the whole chapter, and it is the next section.

Fit and transform: where leakage comes from

A school sets a grading curve from the class average. If the average is worked out from this year’s class, it is fine to apply it to this year’s marks. Now suppose the school also folded in the marks of next year’s class, which has not sat the test yet. The curve now depends on people who were supposed to be unknown. That is leakage.

A scikit-learn preparation step has two stages. fit learns numbers from data: a scaler learns each column’s mean and standard deviation. transform applies those learned numbers to rows. The documentation says fit computes the mean and standard deviation from the training data to be used for later scaling. The rule that prevents leakage, in the documentation’s own words, is that transformations are only learnt from the training data: if the test subset is included in the average calculation, information from the test subset is influencing the model.

The code below compares a scaler fitted on all 569 rows with one fitted on the training rows only, for the mean area column:

from sklearn.preprocessing import StandardScaler

leaky = StandardScaler().fit(X)
clean = StandardScaler().fit(X_train)
col = list(X.columns).index("mean area")
print(round(leaky.mean_[col], 2), round(clean.mean_[col], 2))
print(round(X_train["mean area"].mean(), 2), round(X_test["mean area"].mean(), 2))

scaled_train = clean.transform(X_train)
scaled_test = clean.transform(X_test)
print(round(scaled_train[:, col].mean(), 3), round(scaled_train[:, col].std(), 3))
print(round(scaled_test[:, col].mean(), 3), round(scaled_test[:, col].std(), 3))
654.89 649.63
649.63 670.56
0.0 1.0
0.061 1.067

The first line is the leak made visible: the scaler that saw every row has a mean of 654.89 for mean area, while the scaler that saw only the training rows has 649.63, exactly the training average on the second line. The 654.89 is partly built from the 143 test rows, whose average is 670.56. The last two lines show what correct scaling looks like. The training column comes out with a mean of 0.0 and a standard deviation of 1.0, because the scaler learned from it. The test column comes out with a mean of 0.061 and a standard deviation of 1.067. That is not a bug. It is the honest picture: the test rows are slightly different from the training rows, and the model should meet them that way. If you had fitted the scaler on everything, the test column would look more like the training column than it truly does.

A rule of thumb to follow: split first, then fit every learned step on the training rows only, then transform both sets. The same rule applies to filling missing values with an average, choosing categories to encode, and picking the most useful columns, which are further steps that learn from data.

Feature engineering: new columns from old ones

A flat-hunting site holds each flat’s floor area and its number of rooms. Neither column alone says whether the flat is spacious, but area divided by rooms does. A second example from the table in this chapter: mean area and mean radius are both size measures, and dividing one by the other makes a new column about shape rather than size. Feature engineering is the practice of building such columns, and also of choosing which to keep and putting them in a form the model can use. It rests on a simple idea: a model only sees the columns you give it, so a useful relationship that is not in a column is a relationship the model may not find.

Not every engineered column helps, and one built from the target would leak it. Build a column only from the other columns of the same row, so that you could compute it for a new row at prediction time. The ratio above passes that test, since both inputs are known for any new row.

Categorical columns: one-hot encoding

A clinic column holds the words north, south and east. A model needs numbers, and the quick fix is to write north as 0, south as 1 and east as 2. That quietly says east is twice south and that south sits between the other two, an order that does not exist. One-hot encoding avoids it by giving each category its own 0/1 column: a row from the south clinic has a 1 in clinic_south and 0 in the other two. A second picture is a form with three tick boxes of which exactly one is ticked.

The scikit-learn documentation describes OneHotEncoder as creating a binary column for each category. It also has a setting for categories met only at prediction time: with handle_unknown="error", the default, an unknown category raises an error, while "ignore" encodes it as all zeros.

To practise, the next block builds a table that is the breast cancer data plus two category columns with invented values (clinic and referral route, drawn at random) and one engineered ratio column. The invented columns have no real link to the target. They exist so there is something to encode.

rng = np.random.default_rng(42)
table = X[["mean radius", "mean texture", "mean area", "mean smoothness"]].copy()
table["clinic"] = rng.choice(["north", "south", "east"], size=len(table))
table["referral"] = rng.choice(["walk-in", "doctor", "screening"], size=len(table))
table["area_per_radius"] = table["mean area"] / table["mean radius"]

print(table.head(3).round(2).to_string())
print(table["clinic"].value_counts().to_dict())
   mean radius  mean texture  mean area  mean smoothness clinic   referral  area_per_radius
0        17.99         10.38     1001.0             0.12  north     doctor            55.64
1        20.57         17.77     1326.0             0.08   east  screening            64.46
2        19.69         21.25     1203.0             0.11  south     doctor            61.10
{'north': 197, 'east': 190, 'south': 182}

The table now has five numeric columns and two text columns. The clinic counts are 197 north, 190 east and 182 south, which add up to 569 rows.

Putting it together: ColumnTransformer and Pipeline

A bakery follows one fixed order: weigh, mix, bake. Doing the steps in the wrong order, or baking before weighing, spoils the batch. A Pipeline is that fixed order for data. Its documentation says its main purpose is to assemble several steps that can be cross-validated together, and that the intermediate steps must provide fit and transform. The scikit-learn guide to common pitfalls adds that a pipeline is a great way to prevent leakage, since it ensures the appropriate method is performed on the correct data subset.

The numeric and the text columns need different treatment, so a ColumnTransformer applies the scaler to the numeric columns and the encoder to the text columns, then joins the results. Its remainder setting says what happens to columns not listed; by default they are dropped.

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

T_train, T_test, t_train, t_test = train_test_split(
    table, y, test_size=0.25, random_state=42, stratify=y
)
num_cols = ["mean radius", "mean texture", "mean area", "mean smoothness", "area_per_radius"]
cat_cols = ["clinic", "referral"]
prep = ColumnTransformer(
    [
        ("num", StandardScaler(), num_cols),
        ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
    ]
)
prep.fit(T_train)
print(prep.transform(T_train).shape)
print(prep.get_feature_names_out().tolist())
print(prep.named_transformers_["num"].mean_.round(2).tolist())
(426, 11)
['num__mean radius', 'num__mean texture', 'num__mean area', 'num__mean smoothness', 'num__area_per_radius', 'cat__clinic_east', 'cat__clinic_north', 'cat__clinic_south', 'cat__referral_doctor', 'cat__referral_screening', 'cat__referral_walk-in']
[14.08, 19.3, 649.63, 0.1, 43.41]

Seven input columns became eleven: five scaled numbers, three clinic columns and three referral columns, 5 + 3 + 3. The scaler’s means come from the 426 training rows: its mean area is 649.63, the same number as before. Now chain the preparation and a classifier into a pipeline:

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
model.fit(T_train, t_train)
print("train accuracy", round(model.score(T_train, t_train), 3))
print("test accuracy", round(model.score(T_test, t_test), 3))
train accuracy 0.939
test accuracy 0.902

model.fit(T_train, t_train) fits the scaler and the encoder on the training rows, transforms them and trains the classifier. model.score(T_test, t_test) then applies the same fitted steps to the test rows and reports accuracy, the share of rows predicted correctly. Here that is 0.939 on rows the model trained on and 0.902 on rows it never saw. The test figure is the one to report. A later chapter explains logistic regression and why accuracy alone can mislead; for now the classifier is a black box that fits the prepared table.

This setup keeps the leak out for a plain reason: the scaler’s fit runs inside model.fit, and model.fit was handed the training rows, so the test rows have no route into the scaler.

One more behaviour to know about. A new row arrives from a clinic called west, which the training data never contained:

new = T_test.iloc[[0]].copy()
new["clinic"] = "west"
print(model.predict(new))

strict = Pipeline(
    [
        (
            "prep",
            ColumnTransformer(
                [("num", StandardScaler(), num_cols), ("cat", OneHotEncoder(), cat_cols)]
            ),
        ),
        ("clf", LogisticRegression(max_iter=1000)),
    ]
).fit(T_train, t_train)
try:
    strict.predict(new)
except ValueError as error:
    print("ValueError:", str(error)[:70])
[1]
ValueError: Found unknown categories ['west'] in column 0 during transform

The pipeline built with handle_unknown="ignore" predicts as usual, treating the clinic as all zeros. The one built with the default encoder raises an error and stops. Neither is automatically right: an error is the safer choice when an unexpected category means something is broken, and ignoring is the safer choice when new categories are expected and a prediction is still wanted. The point is to choose on purpose.

With AI: check an assistant’s preprocessing code for leakage

An assistant writes preprocessing code quickly, and the most common draft looks tidy and is wrong. For the prompt “Scale the four size columns of the breast cancer data, split it and train a classifier” it returns:

import numpy as np
from sklearn.linear_model import LogisticRegression

cols = ["mean radius", "mean texture", "mean area", "mean smoothness"]
X_small = X[cols]

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_small)
Xs_train, Xs_test, ys_train, ys_test = train_test_split(
    X_scaled, y, test_size=0.25, random_state=42, stratify=y
)
clf = LogisticRegression(max_iter=1000).fit(Xs_train, ys_train)
print("draft test accuracy:", round(clf.score(Xs_test, ys_test), 3))
draft test accuracy: 0.895

Assistant’s note: “The data is standardised and split with a fixed random_state and stratification, so the 0.895 test accuracy is a trustworthy estimate. I also scaled before splitting so both sets share the same scale.”

The code runs, the score looks respectable and the note sounds sure. The last sentence is the flaw. Use the rule from this chapter as the check: a scaler’s learned mean must equal the mean of the training rows alone. Split the unscaled table the same way and compare:

S_train, S_test, s_train, s_test = train_test_split(
    X_small, y, test_size=0.25, random_state=42, stratify=y
)
print(np.allclose(scaler.mean_, S_train.mean().to_numpy()))
print(scaler.mean_.round(2).tolist())
print(S_train.mean().round(2).tolist())
False
[14.13, 19.29, 654.89, 0.1]
[14.08, 19.3, 649.63, 0.1]

False: the scaler’s means differ from the training means, so the scaler saw the test rows. The draft leaks. Fix it by putting the scaler and the classifier in one pipeline and fitting only on the training rows, then run the same check on the fitted scaler:

pipe = Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression(max_iter=1000))])
pipe.fit(S_train, s_train)
print(np.allclose(pipe.named_steps["scale"].mean_, S_train.mean().to_numpy()))
print("fixed test accuracy:", round(pipe.score(S_test, s_test), 3))
True
fixed test accuracy: 0.895

The check now passes, and notice that the accuracy is the same 0.895. This is the important lesson. The leak did not change the score on this table, so a reviewer who only compared scores would have approved the flawed draft. A check on the process (do the learned numbers come from training rows only?) catches what a check on the score cannot. The assistant’s claim that scaling before splitting is harmless is wrong as a rule, even though it did no visible harm here.

A second thing to ask of any draft: does it encode categories sensibly? Had the assistant written the clinic as 0, 1 and 2, the model would read a ranking into names. Look for one-hot encoding or an explicit reason for another choice.

Check on an assistant’s draft What a pass looks like What a fail looks like
Where does the split happen? Before any step that learns from data After scaling, encoding or filling values on all rows
Where are scalers and encoders fitted? Inside a Pipeline, on training rows only A bare fit_transform on the whole table
Does a fitted mean equal the training mean? np.allclose returns True False, so the test rows contributed
How are categories turned into numbers? One-hot columns Plain 0, 1, 2 codes for unordered names

Three situations you will meet, and what they mean for your work

Before the table, three situations:

  1. A notebook calls scaler.fit_transform(df) on the whole table in its first cell and splits later.
  2. A model is trained and tested in a notebook, and it fails in production on the first row with a category the notebook never saw.
  3. Two colleagues run the same split code and get different test scores because one forgot to fix the shuffle.
What you see What it means What to do
Scaling or encoding before the split (situation 1) The test rows influenced the preparation, so the score is optimistic by an unknown amount Split first and move the steps into a Pipeline fitted on the training rows
A production error on a new category (situation 2) The encoder’s unknown-category setting was never chosen on purpose Decide between "error" and "ignore" and test a made-up unseen category
Different scores from the same code (situation 3) The shuffle is not fixed, so each run tests different rows Set random_state to a whole number and keep it

Flashcards

Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.

What is data leakage?

Using information in preparation or training that would not be available when predicting for a new row, for instance an average computed with the test rows in it. It makes the score overly optimistic.

What do `fit` and `transform` do on a scaler?

fit learns the mean and standard deviation of each column from the rows it is given. transform applies those stored numbers to any rows. To avoid leakage, fit sees training rows only.

What is the rule of thumb for the order of work?

Split first, fit every learned step on the training rows only, then transform both the training and the test sets. A Pipeline follows this order for you.

What does a standard score `z = (x - u) / s` mean?

It says how many standard deviations a value sits from the training mean. The mean of the column becomes 0 and a typical spread becomes 1, so columns in different units become comparable.

Why one-hot encode a clinic column instead of writing 0, 1, 2?

Plain codes tell the model that the clinics have an order and distances between them. One-hot gives each clinic its own 0/1 column, so none is ranked above another.

What does `stratify=y` do in `train_test_split`?

It splits so the training and test sets each hold about the same percentage of every target class as the full table. It matters most when one class is rare.

Why set `random_state` to a whole number?

It fixes the shuffle, so every run produces the same training and test rows. Without it, two runs test different rows and report different scores for identical code.

What is the job of a `ColumnTransformer`?

It applies one preparation to some columns and another to the rest, such as scaling the numbers and one-hot encoding the text columns, then joins the results into one table.

How does a `Pipeline` prevent leakage?

It keeps the preparation steps and the model in one object, so fit fits every step on the rows you give it, and score or predict only applies the fitted steps to new rows.

What does `handle_unknown="ignore"` do on a one-hot encoder?

A category not seen in training becomes a row of all zeros and prediction goes ahead. With the default, "error", an unseen category raises an error instead.

How can you check that a fitted scaler did not see the test rows?

Compare its mean_ with the mean of the training rows using np.allclose. If they match, the scaler learned from training rows only. If they differ, the test rows leaked in.

Model answer

The question: “How do you prepare data and evaluate a model without leaking test information?” A strong answer hits five beats, in this order:

  1. Split — divide the rows first, stratifying a classification target and fixing the shuffle.
  2. Engineer — build new columns only from other columns of the same row.
  3. Fit on train — every scaler, encoder or filler learns from the training rows alone.
  4. Pipeline — keep preparation and model in one object so that rule holds automatically.
  5. Verify — test the model once on the held-back rows, and check the fitted numbers.

“I split the rows first, with a fixed random_state and stratification when the target is a class, so the test set is a stand-in for future rows. I engineer new columns only from the other columns of the same row, so I could compute them for a new row, and never from the target. Every step that learns from data, such as a scaler’s average or an encoder’s category list, is fitted on the training rows only. I put those steps and the model into a pipeline, with a column transformer for mixed numeric and text columns, so the rule holds without my having to remember it. Finally I score once on the test rows, and I check the fitted numbers, for instance that a scaler’s mean equals the training mean, because a score cannot show a leak.”

Missing a beat is a failure state. Without the split there is nothing unseen to score on. Without engineer the model may never see a relationship, or may see the target. Without fit on train the score is optimistic. Without the pipeline the rule depends on memory. Without verify a leak that leaves the score unchanged, like the one in this chapter, goes unnoticed.

Why this matters

  • Trustworthy scores. A test score is only worth reporting if the test rows had no part in preparing the model. This is the first question a reviewer asks about any result.
  • Models that survive production. The preparation steps must run identically on new rows. A pipeline saves them with the model, so nothing is rebuilt by hand and a new category is handled on purpose.
  • Reviewing AI-written code. Assistants write the leaky version because it is shorter and it runs. A checking habit based on the fitted numbers, not the score, catches it.
  • Cross-validation later. The tuning methods of a later chapter refit your steps many times; a pipeline makes sure each refit leaves its held-back rows alone.

After this unit

You can now split rows, build and scale columns, encode categories and keep it all leak-free with a pipeline. The next chapter puts a first model on prepared data: linear regression on the diabetes dataset, where you learn to read a model’s coefficients and to measure its error with MAE, RMSE and R².

Quiz

Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.

Quiz — Feature Engineering and Train/Test Splits in scikit-learn Without Data Leakage

Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.


1. [recall] What does calling fit on a StandardScaler do?

a) It rewrites every value in the table so the column averages become exactly zero everywhere b) It splits the rows into a training set and a test set using the shuffle it was given c) It learns each column’s mean and standard deviation from the rows it receives and stores them d) It converts text columns into 0/1 columns, one for each category that appears in the rows


2. [application] A learner has a table, a scaler and a classifier, and wants a test score that is honest about unseen rows. Which order of work achieves that?

a) Split the rows, fit the scaler on the training rows only, then transform both sets of rows b) Scale every row with a scaler fitted on all the rows, then split and train on the scaled rows c) Split the rows, then fit one scaler on the training rows and another on the test rows d) Fit the scaler on the test rows, then use it to transform the training rows before training


3. [scenario] A teammate’s pipeline reports good accuracy, but a check shows the fitted scaler’s mean_ for one column differs from the mean of the training rows. The test accuracy looks healthy anyway. What should you do?

a) Treat the gap as rounding, since the accuracy already looks healthy and nothing has failed b) Enlarge the test set until the two means move closer together and the check passes c) Remove that column from the table so the two averages can no longer disagree d) Find where the scaler was fitted and refit it inside a pipeline on the training rows only


4. [recall] Why is a clinic column with the words north, south and east one-hot encoded rather than written as 0, 1 and 2?

a) Words cannot be stored in a DataFrame once the table is split into two parts for testing b) Plain codes suggest an order and distances between clinics that the names do not have c) A one-hot column always makes the model more accurate than any other encoding would d) Plain codes would take up more memory than three separate columns of zeros and ones


5. [application] A table has 1,000 rows, of which only 20 belong to the positive class. Which call keeps the share of positives about the same in the training and test sets?

a) train_test_split(X, y, test_size=0.25) alone, because shuffling spreads the classes evenly b) train_test_split(X, y, random_state=42) alone, because a fixed seed balances the classes c) train_test_split(X, y, test_size=0.5) alone, because a larger test set holds more positives d) train_test_split(X, y, test_size=0.25, stratify=y), which keeps each class’s share in both sets


6. [scenario] A pipeline with a default OneHotEncoder stops with a ValueError on a row from a clinic that was not in the training data. The business wants a prediction anyway. What should you change?

a) Set handle_unknown="ignore" on the encoder so an unseen category becomes a row of zeros b) Refit the scaler on the new row so that the pipeline learns the name of the unseen clinic c) Replace the one-hot encoding with 0, 1, 2 codes so every possible clinic has a number d) Drop every text column from the table so that no new category can cause a failure again


7. [recall] What does random_state=42 do in a call to train_test_split?

a) It sets the share of rows that are placed in the test set to the number given b) It makes the training and the test set hold equal shares of every target class c) It fixes the shuffle so the same rows land in the same sets on every run d) It chooses which column of the table the model will be asked to predict


8. [application] A ColumnTransformer scales 3 numeric columns and one-hot encodes 1 text column that has 4 categories in the training rows. A fifth column, row_id, is listed in neither step. With default settings, how many columns come out?

a) 8, because the unlisted row_id column is passed through to the output unchanged b) 7, because the unlisted row_id column is dropped when the transformer runs c) 5, because the text column is kept as a single encoded column in the output d) 6, because the encoder leaves out one category to avoid repeating information

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.