Lesson 4 of 228 min
Logistic regression
Logistic regression puts a line's score through an S-curve, so every penguin gets a chance between 0 and 1, and it says yes where that chance passes one half.
After this lesson you can turn a score into a probability and draw a decision boundary.
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.
Turn a score into a chance
The sigmoid divides one by one plus the exponential of the negative score. At zero the exponential gives one, so the chance is one half.
import numpy as np
scores = np.array([-2, 0, 2])
print((1 / (1 + np.exp(-scores))).round(3))[0.119 0.5 0.881]
Set up the two kinds
Keep both bill measurements in the split. Fit the first curve on length alone, and keep the same penguins aside for the notebook task.
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
features = ["bill_length_mm", "bill_depth_mm"]
penguins = pd.read_csv(url).dropna(subset=features)
two = penguins[penguins["species"].isin(["Adelie", "Chinstrap"])]
X, y = two[features], two["species"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)Find the chance for one kind
predict_proba returns one column per species, in the order of classes_. Chinstrap is the second column here. Find the column by name so the same code still works if you change the labels.
length = ["bill_length_mm"]
model = LogisticRegression().fit(X_train[length], y_train)
new = pd.DataFrame({"bill_length_mm": [40, 43, 45, 48]})
chinstrap = model.classes_.tolist().index("Chinstrap")
print(model.classes_)
print(model.predict_proba(new)[:, chinstrap])['Adelie' 'Chinstrap'] [0.01299459 0.21717749 0.67912997 0.97807004]
Fit with and without a penalty
The default solver, lbfgs, searches for the weights in steps. The default C=1.0 adds a cost for large weights, so the fit balances that cost against the training set’s surprise. C=np.inf removes the penalty. Here it makes the curve slightly steeper.
plain = LogisticRegression(C=np.inf).fit(X_train[length], y_train)
for fit in (model, plain):
slope = fit.coef_.item()
middle = -fit.intercept_.item() / slope
print(f"C={fit.C}: {slope:.3f} per mm, halfway at {middle:.2f} mm")C=1.0: 1.016 per mm, halfway at 44.26 mm C=inf: 1.057 per mm, halfway at 44.24 mm
Read a weight as odds
Odds are the chance of Chinstrap divided by the chance of Adelie. Each extra millimeter adds one weight to the score. Taking the exponential of that weight tells you how much one millimeter multiplies the odds.
print(f"{np.exp(model.coef_.item()):.2f} times the odds per mm")2.76 times the odds per mm
Give the model a third kind
With Gentoos back in the data, the same call learns a model that gives all three species a chance. The solver fits them together. The model turns their scores into chances with softmax, so the three chances add up to one.
three = LogisticRegression().fit(penguins[features], penguins["species"])
print(three.classes_)['Adelie' 'Chinstrap' 'Gentoo']
Run on Python 3.13.3, NumPy 2.5.5, pandas 3.1.1, and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Linear regression
Two models guess the penguins' mass. On the test set, model A prints MAE 234 and RMSE 282. Model B prints MAE 230 and RMSE 400. What does B's gap between the two say?
2 of 3
Each Chinstrap is written as 1 and each Adelie as 0. Why not fit a straight line through them and read its guess as the chance of a Chinstrap?
3 of 3
For bills of 40, 43, 45 and 48 mm, model.predict_proba(new)[:, 1] prints [0.013 0.217 0.679 0.978]: each bill's chance of being a Chinstrap. What does model.predict(new) print?
The ideas in this lesson
- The S-curve (sigmoid)
- It turns any score into a number between 0 and 1: a score of 0 gives one half.
- Logistic regression
- A line's score through the S-curve gives the chance of a yes; training learns the weights from labeled examples.
- Decision boundary
- Where the chance is one half: the model says yes on one side and no on the other; with two inputs, a straight line.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Logistic regression
Here's a game. There are two kinds of penguin. One kind mostly has a shorter bill. The other kind has a longer bill. This penguin's bill is right in between. Which kind is it?
Keep your guess
Hold on to your guess.
Here are two hundred and nineteen penguins, Adelies and Chinstraps, by the length of their bills. Short bills are mostly Adelies. Long bills are mostly Chinstraps. In the middle, you find both. The penguin in the puzzle has a bill of forty-four millimeters. One hundred and sixty-four penguins are the training set. Fifty-five are kept aside as the test set.
A kind as zero or one
Here, a model has to pick one of two kinds. That's classification: the label is a kind. But how can a model guess a kind as a number?
Like this. Write each Chinstrap as one, and each Adelie as zero. Now the model's guess can be a number: the chance that a penguin is a Chinstrap. Zero means never.
One means for sure. Like a weather forecast that gives a seventy percent chance of rain.
A straight line breaks
Can a straight line guess that chance, the way a line guessed a penguin's mass?
Try it. Fit one through the zeros and ones, the same way as before.
At forty-five millimeters, it says zero point five two: about half.
Fine so far. Now look at the two ends. Spot the problem.
At fifty-five millimeters, the line says one point two four.
At thirty-five, it says minus zero point two.
A chance of a hundred and twenty-four percent? That can't be. A chance never goes below zero, or above one.
The S-curve
So how do you keep a guess between zero and one?
Take any number at all, and call it a score. The S-curve turns it into a number between zero and one. A score of zero gives exactly one half. A score of two gives eighty-eight percent. Minus two gives twelve percent. Farther out, the curve levels off, close to one and close to zero, but it never reaches them.
This S-shaped curve... is called the sigmoid.
A score through the S-curve
To pick one of two kinds, a model can give a chance between zero and one. The S-curve keeps any number in that range.
So what number goes into the S-curve?
A score: the number a line gives, the way a line gave a penguin's mass.
Here, the line's input is the bill's length. Its weight says how much each millimeter of bill adds to the score. Training put the score's zero at forty-four point three millimeters, the middle. From there, each millimeter adds about one.
So what chance does a bill of forty-five millimeters get?
Sixty-eight percent.
At forty millimeters, one percent. At forty-three, twenty-two percent. At forty-eight, ninety-eight percent.
Putting a line's score through the S-curve... is called logistic regression.
The puzzle's penguin
And the penguin in the puzzle, with its bill of forty-four millimeters?
Forty-three percent.
It leans Adelie, but just barely.
Nearly half and half, and the model says so.
Nobody could be sure about this penguin. So here, a chance is a better answer than a kind.
Surprise
But why this curve, and not another one? Each penguin pays a surprise for its real kind, measured in bits, as in the Probability course. The smaller the chance the model gave its real kind, the more it pays.
Here are two Chinstraps. The model gives one of them ninety-eight percent, and the other three percent. Which one pays more?
The one at three percent pays almost five bits. The one at ninety-eight percent pays almost nothing. A flat curve, one half for every penguin, pays one bit each.
The weights that make the answers likely
Training moves the weights to bring down the average surprise across the training penguins. Watch it fall. It goes from one bit to zero point one six bits a penguin. The model we fit also adds a small cost for large weights.
That average... is the cross-entropy you saw in the Probability course.
Less surprise means the model gave the real kinds higher chances overall. Take away the extra cost. Now finding the least surprise also makes the real answers as likely as possible. That's maximum likelihood.
The decision boundary
Logistic regression gives each penguin a chance of being a Chinstrap. A forecast can stop at a chance.
But a model that picks a kind has to say one.
So when does it say Chinstrap? Where the chance goes above... one half. That's where the score is zero, at forty-four point three millimeters. That point is the decision boundary. To the left of it, the model says Adelie. To the right of it, it says Chinstrap. On the training set, it's wrong on only six of the hundred and sixty-four.
On the test set
Now open the test set. How many of its fifty-five penguins will the model get right?
Fifty-two. Always saying Adelie, the most common kind, gets thirty-eight. The three it gets wrong sit close to the boundary, where both kinds have bills that long.
Two measurements
And with two measurements?
Add how deep the bill is. Each measurement gets its own weight, and together they make one score. The same S-curve turns that score into a chance.
Now the points where the chance is one half make a straight line across the picture. The chance fades from one side of the line to the other.
On the test set, it's right on fifty-four of fifty-five.
In code
In real code, take the Adelies and the Chinstraps, their bill lengths and their species. Then split off the test set. Make a logistic regression, and fit it on the training set. The next line asks for each bill's chance of being a Chinstrap. They're the same chances as before, as decimals. So what will predict say for the bill of forty-five millimeters?
Chinstrap, because its chance is over one half. And on the test set, it gets fifty-two of the fifty-five right. You'd use the same lines on any table with a yes or no to guess. Will a customer say yes? Is an email spam?
Three ideas
So: the S-curve turns any score into a chance between zero and one. Logistic regression puts a line's score through it and learns the weights from the training examples. Where the chance passes one half, the model switches its answer. That's the decision boundary.
A score through the S-curve
Logistic regression turns a score into a chance. Now try it on this lesson's page, and take the quiz. Match the fitted curve by hand.
You use this lesson in Lab 2: Tune a penguin model on folds, after Cross-validation and tuning.
Facts last checked on .
