Lesson 10 of 146 min
The scikit-learn pattern
Every scikit-learn model is an object that learns from a table with fit, then answers with predict; a tool that changes the table learns with fit too, then answers with transform.
After this lesson you can use fit, predict and transform on any model.
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.
One column still needs two brackets
X is always a table, even with one column in it. With one bracket, df["bill_length_mm"] is a single column, a Series, and fit stops. Two brackets keep it a table of one column, and the model learns from it.
model = tree.DecisionTreeClassifier()
model.fit(df["bill_length_mm"], df["species"])ValueError: Expected a 2-dimensional container but got <class 'pandas.Series'> instead. …
model.fit(df[["bill_length_mm"]], df["species"])Fit comes before predict
A model just made has learned nothing, so it has nothing to answer with. Ask it before fit and scikit-learn says so, by the model's name. You will meet this when a notebook's cells run out of order: run the cell with fit again, then ask.
model = svm.SVC()
model.predict([[39.1, 18.7]])sklearn.exceptions.NotFittedError: This SVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.
Test it on penguins it has not seen
The video asked the model about the same penguins it learned from. Real code holds some rows back: train_test_split puts a quarter aside, the model learns from the rest, and score gives the share of the held-back rows it got right. The Machine Learning course starts here.
from sklearn import impute, model_selection, svm
X = impute.SimpleImputer().fit_transform(df[["bill_length_mm", "bill_depth_mm"]])
X_train, X_test, y_train, y_test = model_selection.train_test_split(
X, df["species"], test_size=0.25, random_state=0)
model = svm.SVC()
model.fit(X_train, y_train)
print(model.score(X_test, y_test))0.9767441860465116
A scaler is one more transformer
You will often see StandardScaler before a model. It is used just like the imputer: its fit learns each column's average and spread, and transform moves every value so each column is centred on 0. The averages are the imputer's, 43.92 and 17.15.
from sklearn import preprocessing
scaler = preprocessing.StandardScaler()
scaler.fit(X)
print(scaler.mean_.round(2), scaler.scale_.round(2))
X = scaler.transform(X)[43.92 17.15] [5.44 1.97]
Run on Python 3.13.3, scikit-learn 1.9.1 and pandas 3.1.1. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
Your code makes a tree.DecisionTreeClassifier(), then calls fit and predict. You want svm.SVC() instead. Which lines do you change?
2 of 2
Four penguins, two measurements each, and their species. What does this print?
from sklearn import tree
X = [[39, 18], [46, 13], [50, 19], [38, 17]]
y = ["Adelie", "Gentoo", "Chinstrap", "Adelie"]
model = tree.DecisionTreeClassifier()
model.fit(X, y)
kinds = model.predict(X)
print(kinds.shape)The ideas in this lesson
- Fit, then predict
- fit teaches a model from a table and its answers; predict then gives one answer for each row.
- Estimator
- An estimator is any scikit-learn object that learns with fit. Every model also has the same predict.
- Transform
- A transformer learns from the table with fit, then changes it with transform, like an imputer filling gaps.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Three lines
Here's a question.
These are real penguins, of three kinds. For each one, we have two measurements of its bill, its beak.
A model is a program that learns from examples.
With scikit-learn, three lines make one that tells the kinds apart. One line makes the model. One teaches it. One asks it. Now we put in a very different model. How many of the three lines change?
Examples and their answers
Hold on to your guess.
First, the three lines.
How does a model learn which kind a penguin is? From examples, each with its answer. Like cards with a question on the front, and the answer on the back.
Line one brings in pandas.
Line two brings in two kinds of model from scikit-learn, the Python library of classic models. Line three reads the penguins into a table. Lines four and five pick two of its columns by name: the bill's length, and its depth. That's X. Each row is one card. And the species column, on line seven, is the answer on the back.
A model is an object
Line six makes the model. It calls a class from scikit-learn, with brackets, and that makes a new object. This one is a decision tree: a model that learns questions about the measurements.
Just made, it has learned nothing.
Fit learns
So how does it learn?
Line seven: fit. It gets the measurements and the species, and it reads every row with its answer.
Does fit give anything back?
There's no name on the left, so nothing comes back. Fit works on the model itself, the object before the dot. Watch the model.
It fills. The first name is classes. Here, that word means the kinds of answer: the three species. Not a Python class.
The second is the tree: the questions it learned about the bills.
Each name ends in an underscore. That mark means: learned from the data.
Predict answers
Line eight asks the model about X. Will it give one species, or one for each penguin?
One for each row, in a NumPy array. The first eight say Adelie... and they are.
But the model learned from these very penguins, so this doesn't show that it's good. Testing it on penguins it has never seen is where the Machine Learning course starts.
So, fit teaches the model. Predict asks it, and gives one answer for each row.
One line
Line six makes a model, line seven teaches it with fit, and line eight asks it with predict. Now, back to the question.
Line six becomes SVC, a support vector machine. It learns in a very different way.
And lines seven and eight... stay the same. One line changed.
If you said all three: inside, every model is different. But from the outside, every scikit-learn model has the same fit, and the same predict.
Estimators
scikit-learn has a word for anything that learns with fit: an estimator. It has more than two hundred of them, and every one learns with the same fit. Every model among them also answers with the same predict.
So another model is one line.
The gaps
X holds two bill measurements for every penguin, and a model learns from it with fit. Now run the same three lines, with SVC. Will it run?
It stops, on line seven. Input X contains NaN. SVC does not accept missing values.
NaN means not a number. Two rows were never measured, like row three. The tree could learn with these gaps. SVC can't learn from a missing number.
The message names two fixes. Remove those rows... or fill the gaps, with what it calls an imputer transformer.
A transformer learns too
So how do we fill the gaps?
On a second board, before the model: bring in scikit-learn's impute, and make an imputer. An imputer is a transformer: a tool that changes a table. Then fit it on X.
Its fit learns each column's average: about forty-four millimetres, and about seventeen. The same fit... and the same underscore.
Transform
Then, transform. It gives the table back, with each gap filled by its column's average. Row three was NaN and NaN. Now it holds the two averages. The same shape as before, with no gaps.
And now SVC learns, and answers.
An average is a guess, not a measurement. Removing the two rows is the other fix.
Most code writes the two steps as one line: fit transform. Fit learned the two averages. Transform used them, on every gap.
Make it, fit it
So here's what you saw. One pattern, for every tool in scikit-learn. Make it. Fit it. Then predict, or transform.
And another model is one line.
The lab
That's the end of this unit. In its lab, you use these three lessons on a new table, of real cars. You teach two models to tell where a car was made.
One pattern
So every model in scikit-learn is used the same way. Now try it on this lesson's page, and take the quiz. Ask the model about three rows from the middle of the table.
You use this lesson in Lab 4: From a table to a first prediction, which comes next.
Facts last checked on .
