Learning path: Classify and Evaluate: Logistic Regression to Cross-Validation · Step 1 of 7
Logistic Regression and the Sigmoid: Score, Squash, Decide
How logistic regression turns a price into the probability of a car: why a straight line fails, Euler's number e, the sigmoid, the 0.5 threshold, the decision boundary and log loss, on eight vehicles.
What you will learn
- Explain why a straight line fails on yes/no data
- Turn any score into a probability with the sigmoid
- Find the decision boundary where the score is zero
- Compare two models with log loss
Before you start
- Basic Python and NumPy
- Linear Regression and the Cost Function
A vehicle costs $16k. Is it a bike or a car? A yes/no question like this is called classification, and logistic regression is the first model most people use for it. It answers "car" or "bike" and also says how sure it is, as a probability between 0 and 1.
We'll build it by hand on eight vehicles, in three steps: score, squash, decide.
The data: eight vehicles
import numpy as np
import pandas as pd
df = pd.read_csv("vehicles.csv")
df
price_k type is_car
0 2 bike 0
1 5 bike 0
2 8 bike 0
3 12 bike 0
4 18 car 1
5 24 car 1
6 30 car 1
7 60 car 1
Prices are in thousands of dollars. Up to $12k it's a bike (0); from $18k up it's a car (1).
Why a straight line fails
Let's try the regression line first. np.polyfit fits the best straight line through these zeros and ones.
x = df["price_k"]
y = df["is_car"]
w_line, b_line = np.polyfit(x, y, 1)
print("line: w", round(w_line, 4), "b", round(b_line, 3))
print("guess at $18k:", round(w_line * 18 + b_line, 2))
print("guess at $60k:", round(w_line * 60 + b_line, 2))
line: w 0.0212 b 0.079
guess at $18k: 0.46
guess at $60k: 1.35
Two problems. The $60k car gets 1.35, which would mean 135% sure. That makes no sense. And the $18k car gets 0.46, below one half, so the line calls it a bike. Wrong.
A probability has to stay between 0 and 1. A straight line keeps climbing past 1 as the price grows.
A dimmer, not a switch
Think of a normal light switch: on or off. Off is bike, on is car, and it can't tell you how sure it is. A dimmer can sit at any level from 0 to 1. At 0.9 the light is bright and the model is very sure it's a car. At 0.5 the light is half on and the model can't tell. Logistic regression is the dimmer.
Meet e, just the part we use
To build the dimmer we need one fixed number, e (Euler's number), about 2.718. Like pi, it never changes. We only use e to the power minus z:
print("e =", round(np.e, 3))
for z in [-2, 0, 2, 5]:
print("z =", z, " e**-z =", round(np.exp(-z), 3))
e = 2.718
z = -2 e**-z = 7.389
z = 0 e**-z = 1.0
z = 2 e**-z = 0.135
z = 5 e**-z = 0.007
A negative score makes it big. A big score shrinks it towards zero. That's all we need from e.
The sigmoid squashes any score
The sigmoid is:
sigmoid(z) = 1 / (1 + e-z)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
for z in [-4, 0, 4]:
print("z =", z, " sigmoid =", round(sigmoid(z), 3))
z = -4 sigmoid = 0.018
z = 0 sigmoid = 0.5
z = 4 sigmoid = 0.982
When z is big, e-z is almost zero, so you get almost 1/1. When z is very negative, e-z is huge, so you get almost 0. At z = 0 you get exactly 0.5. Any score goes in, a probability comes out.
Score, squash, decide
Take the $18k car, with two knobs set to w = 0.5 and b = -7.5:
w, b = 0.5, -7.5
z = w * 18 + b
p = sigmoid(z)
guess = "car" if p >= 0.5 else "bike"
print(z, round(p, 3), guess)
1.5 0.818 car
- Score: 0.5 × 18 − 7.5 = 1.5. This is the same
w * x + bas a regression line. - Squash: sigmoid(1.5) = 0.818.
- Decide: 0.818 is at least 0.5, the threshold, so the guess is car.
w and b are the knobs. Here we set them by hand; training is what turns them. The sigmoid and the 0.5 cut never change.
For every row at once
df["score"] = w * x + b
prob = sigmoid(df["score"])
df["prob_car"] = prob.round(3)
df["guess"] = np.where(prob >= 0.5,
"car", "bike")
df
price_k type is_car score prob_car guess
0 2 bike 0 -6.5 0.002 bike
1 5 bike 0 -5.0 0.007 bike
2 8 bike 0 -3.5 0.029 bike
3 12 bike 0 -1.5 0.182 bike
4 18 car 1 1.5 0.818 car
5 24 car 1 4.5 0.989 car
6 30 car 1 7.5 0.999 car
7 60 car 1 22.5 1.000 car
Bikes stay low, cars go high, and all eight guesses are right. The $12k bike gets 0.182; the $18k car gets 0.818.
The decision boundary
The probability is exactly 0.5 where the score is zero. Solve w * x + b = 0 and you get x = -b / w:
print("boundary: $", -b / w, "k")
p16 = sigmoid(w * 16 + b)
print("a $16k vehicle:", round(p16, 2))
boundary: $ 15.0 k
a $16k vehicle: 0.62
Left of $15k, bike. Right of it, car. Our mystery $16k vehicle gets 0.62, just past the line, so the model says car.
Log loss: how good is the curve?
For a regression line we used the MSE (see Linear Regression and the Cost Function). For the S curve we use log loss. It punishes a model that is confident and wrong. Lower is better.
from sklearn.metrics import log_loss
good = log_loss(y, sigmoid(0.5 * x - 7.5))
worse = log_loss(y, sigmoid(0.2 * x - 3))
print("w 0.5, b -7.5:", round(good, 3))
print("w 0.2, b -3 :", round(worse, 3))
w 0.5, b -7.5: 0.057
w 0.2, b -3 : 0.187
Our knobs score 0.057. A worse pair scores 0.187. Training is a search for the w and b with the lowest log loss.
Common mistakes
- Using a straight line for yes/no answers. It gives values above 1 and puts the cut in the wrong place.
- Reading the score as a probability. The score
zcan be any number (22.5 for the $60k car). Only the sigmoid output is a probability. - Thinking the boundary is a fixed price. It's
-b / w, so it moves whenever training changes the knobs.
Quick recap
| Step | What it does | $18k car |
|---|---|---|
| Score | z = w * x + b | 1.5 |
| Squash | 1 / (1 + e-z) | 0.818 |
| Decide | 0.5 or more means yes | car |
| Boundary | where z = 0, -b / w | $15k |
| Log loss | scores the curve, lower is better | 0.057 |
Try it yourself
With w = 0.5 and b = -7.5, what probability does a $14k vehicle get? Is it a bike or a car? Next, the same model in scikit-learn: Logistic Regression in scikit-learn.
The notebook and vehicles.csv are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.