Lesson 9 of 228 min
Preparing features
A model reads only numbers, so each column is prepared in its own way (words become columns of 0 and 1, numbers go on one ruler, codes for a gap are filled and flagged) inside one pipeline that learns from the training rows only.
After this lesson you can scale numbers, encode categories and fill gaps inside a pipeline.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
See the prepared table
Put bank-additional-full.csv from UCI’s Bank Marketing dataset next to your notebook and run these cells in order. The prep hands the model a table with no names. Ask for pandas output to see it. A one-hot encoder makes a sparse table by default, which pandas can’t hold, so set sparse_output=False.
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScalercalls = pd.read_csv("bank-additional-full.csv", sep=";")
y = calls["y"].eq("yes")
nums = ["age", "campaign", "previous"]
words = ["job", "marital", "education", "default", "housing", "loan", "contact", "poutcome"]
X = calls[nums + ["pdays"] + words]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=1000, stratify=y, random_state=0)prep = make_column_transformer(
(StandardScaler(), nums),
(SimpleImputer(missing_values=999, add_indicator=True), ["pdays"]),
(OneHotEncoder(handle_unknown="ignore", sparse_output=False), words),
).set_output(transform="pandas")
table = prep.fit_transform(X_train)
print(table.shape)
print(list(table.columns[3:6]))(40188, 43) ['simpleimputer__pdays', 'simpleimputer__missingindicator_pdays', 'onehotencoder__job_admin.']
Why not get_dummies
pd.get_dummies makes a column for each word it finds in the table you give it, right now. Three new customers make three job columns, not twelve, and the model refuses them. A fitted OneHotEncoder keeps the training set’s words, so every new row gets the same columns.
print(pd.get_dummies(X_train["job"]).shape[1])
print(pd.get_dummies(X_test["job"].head(3)).shape[1])12 3
Words that have an order
Some words do have an order, like education’s levels. Then write the order out, and OrdinalEncoder numbers the words in it. The alphabet’s order is almost never the one you mean. A word outside your list stops it with an error, so deal with a gap like "unknown" first.
from sklearn.preprocessing import OrdinalEncoder
levels = ["illiterate", "basic.4y", "basic.6y", "basic.9y",
"high.school", "professional.course", "university.degree"]
order = OrdinalEncoder(categories=[levels])
rows = pd.DataFrame({"education": ["basic.6y", "university.degree"]})
print(order.fit_transform(rows))[[2.] [6.]]
A column with many words
A postcode or a product code can hold thousands of words, and a column for each is too many. TargetEncoder gives each word one number, its share of yes, learned on the training rows. Or keep the common words and join the rest in one column, with min_frequency.
from sklearn.preprocessing import TargetEncoder
enc = TargetEncoder(random_state=0).fit(X_train[["job"]], y_train)
print(enc.transform(pd.DataFrame({"job": ["student", "blue-collar"]})).round(3))
few = OneHotEncoder(min_frequency=1000, handle_unknown="infrequent_if_exist")
print(len(few.fit(X_train[["job"]]).get_feature_names_out()))[[0.314] [0.07 ]] 10
Save the pipeline
The pipeline is the one object to keep. Save it with joblib, and load it next month to score customers just as they come. Load only files you made yourself, since loading one runs its code, and load it with the same scikit-learn version.
import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
model = make_pipeline(prep, LogisticRegression()).fit(X_train, y_train)
joblib.dump(model, "bank_model.joblib")
loaded = joblib.load("bank_model.joblib")
print(loaded.predict_proba(X_test.head(3))[:, 1].round(3))[0.131 0.052 0.064]
The whole table in one line
skrub’s TableVectorizer looks at each column and picks a step for it by itself: words, numbers, dates. It’s a quick start on a new table. Read what it chose before you trust it: it can’t know that 999 means never called. Install it with pip install skrub.
from skrub import TableVectorizer
wide = TableVectorizer().fit_transform(X_train)
print(wide.shape)(40188, 41)
Run on Python 3.13, scikit-learn 1.9.1, pandas 3.1.1 and skrub 0.12.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Tables with pandas
A small table of four penguins, made from a dict. What does this print?
import pandas as pd
df = pd.DataFrame({"species": ["Adelie", "Gentoo", "Chinstrap", "Gentoo"],
"body_mass_g": [3700, 5400, 3800, 5000]})
heavy = df[df["body_mass_g"] > 4500]
print(heavy.shape)2 of 3
A table has a column color, with red, green or blue in each row. How should a model like logistic regression get it?
3 of 3
The days since a customer was last called hold 999 for "never called", in most of the rows. What do you do with the column before the model reads it?
The ideas in this lesson
- One-hot encoding
- A column of words becomes one column for each word, 1 where the row has it and 0 elsewhere, so each word gets its own weight.
- Scaling
- Put each number column on one ruler: subtract its average and divide by its spread, so most values land between −2 and 2.
- A pipeline
- One object that prepares each column its own way, then fits the model, learning every number from the training rows only.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Preparing features
Here's a challenge. A model can only read numbers. But this table has jobs, like student or retired. How would you turn a job into a number?
Keep your guess
Hold on to your guess.
A bank called its customers to offer a savings deposit, and each call ended in a yes or a no.
This is its table of calls, filled out like a form, forty-one thousand times.
It has twelve columns, all known before a call.
Four are numbers, like age.
Eight are columns of words.
The job column alone holds twelve different jobs.
A model reads numbers only
A model like logistic regression multiplies each column by a weight, and adds them all up. So give it the table as it is.
It stops.
"Could not convert string to float: blue-collar." You can't multiply a word.
Numbering the words breaks
The quick fix is to number the jobs, in alphabetical order, from zero to eleven. Now the model has one weight for the whole column. So it can only say one thing: the later a job comes in the alphabet, the more likely a yes. Or the less likely. Here's the share of yeses for each job, in that order. Spot the problem.
It jumps up and down. Retired is high, then services is low, then student is high again. No straight line follows that. Score it on five folds of the training set, using the area under the ROC curve.
The four number columns alone get zero point six three eight. With the jobs numbered, zero point six four one. The job column adds almost nothing.
One-hot
Instead, make a column for each job. Put a one where the customer has that job, and a zero in the others. In each row, one column is hot.
Now each job gets its own weight: student up, retired up, blue-collar down. This is called one-hot encoding. On the folds, zero point six eight three.
A gap is a word too
Some answers say "unknown": a gap, where the bank didn't know.
That's a word like the others, with its own column, so the model learns what a gap says.
All eight columns of words, one-hot encoded, make thirty-eight columns of zeros and ones.
On the folds, zero point seven three one.
One ruler
A model gets each column as numbers.
Age runs from seventeen to ninety-eight.
The calls before this campaign run from zero to seven. Does the size matter?
scikit-learn's logistic regression finds its weights in small steps, like walking downhill.
With the numbers as they are, it uses up all its hundred steps without finishing. And it warns you to scale the data.
So put each column on one ruler.
Subtract its average, and divide by its spread, the standard deviation.
Age forty becomes zero. Sixty-one becomes plus two. Nineteen becomes minus two.
That's called scaling.
Now it finishes in sixty-one steps.
Why one ruler
Why does one ruler help it finish? Those steps downhill are slow when one column's numbers are far bigger than another's. A model that measures distance counts the big numbers more, too.
A model that only asks questions, like "is the age over sixty?", doesn't care. And here the score stays at zero point seven three one.
A code that looks like a number
What about the days since an earlier call? Onto the ruler too? Spot what's wrong. Three days and twenty-seven days land almost on the same spot. And nine hundred and ninety-nine lands far away from both.
Nine hundred and ninety-nine means never called. Thirty-nine thousand of the calls have it. Read as days, they pull the average up to nine hundred and sixty-two. They stretch the spread, too. So the real days all land on one spot. Think of a paper form. A missing answer is just an empty box. Here, the missing answer was written as a number. So nine hundred and ninety-nine doesn't count days. It's a gap.
Fill and flag
So fill it, and flag it. Fill the nine hundred and ninety-nine with the middle of the real days: six.
Then add a column.
One means never called.
Zero means called.
An imputer does both: its fit learns the six, and transform fills the gaps.
The score stays at zero point seven three one.
This model mostly needed to know "called before, or not".
Now the flag says it plainly, and the days mean days.
One object
Before a model reads a table, three things happen. Its words become columns of zeros and ones. Its numbers go on one ruler. And its gaps are filled and flagged. Which column gets which step? A column transformer says that. And together with the model, it makes a pipeline.
When you fit the pipeline, it learns every number it needs from the training rows only.
Age's average, forty. The twelve job words. The six. Then the model's weights.
New rows, the same steps
A new customer goes through the same steps, with the same numbers. Now guess what happens to a job it never saw, like "influencer".
All twelve job columns get a zero. No error.
And cross-validation fits the whole pipeline again inside each fold.
So the preparation never sees the fold being scored.
On the folds, zero point seven three one. On the test set, opened once, zero point seven three nine.
In code
In real code, with scikit-learn, a column transformer holds the three steps. A scaler for age and the two counts of calls. An imputer for the days, with nine hundred and ninety-nine as the gap.
And a one-hot encoder that ignores new words.
Make a pipeline with the model, and cross-validate it. Will the five folds' scores be close together, or far apart?
Close together. All of them near zero point seven three.
This one object is saved with the model. Next month's customers go through it just as they come, with their words and their gaps.
Three ideas
So, each kind of column gets its own step. Words become a column for each word, numbers go on one ruler, and a gap is filled and flagged.
One pipeline learns all of it, from the training rows.
Each column its own way
A model reads only numbers, so prepare each column its own way. Now try it on this lesson's page, and take the quiz. Sort all twelve columns, and get every one right.
You use this lesson in Lab 3: A call list the bank can trust, after Data leakage.
Facts last checked on .
