Intermediate: machine learning · The ML workflow, regression and classification · topic 26 of 62 · 35 min
Logistic regression and classification
Explanation
Why not use a straight line for yes/no?
Suppose we label "will default on the loan" as 1 and "will repay" as 0, and fit a straight line. The line happily predicts 1.4 or −0.3, which make no sense as chances. We want an output between 0 and 1 that we can read as a probability. Logistic regression does exactly that, and despite its name it is a classification method.
The sigmoid function
First compute a score z = w·x + b, just like linear regression. Then pass it through the sigmoid, σ(z) = 1 ÷ (1 + e^(−z)). The sigmoid is an S-shaped curve: very negative scores give values near 0, very positive scores give values near 1, and z = 0 gives exactly 0.5.
import math
def sigmoid(z):
return 1 / (1 + math.exp(-z))
for z in [-4, 0, 2]:
print(z, round(sigmoid(z), 4))From probability to decision: the threshold
The model outputs a probability, say 0.73 that an email is spam. To act, we need a yes/no. The usual rule is "predict 1 if the probability is at least 0.5". But 0.5 is not sacred. A bank worried about missing fraud may flag anything above 0.2, accepting more false alarms. A spam filter that must never hide important mail may only block above 0.9. Module 6 shows how to pick the threshold with metrics.
How it is trained: log loss
Logistic regression is trained by minimising log loss (also called binary cross-entropy). For one example with true label y (0 or 1) and predicted probability p, the loss is −(y·log p + (1 − y)·log(1 − p)). If y = 1 and the model says p = 0.9, the loss is small (about 0.105). If it says p = 0.01, the loss is large (about 4.6). Confident wrong answers are punished heavily. Training uses gradient descent on this loss.
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
proba = clf.predict_proba(X_test)[:, 1] # probability of class 1
pred = (proba >= 0.5).astype(int) # the same as clf.predict(X_test)More than two classes
For three or more classes (for example, routing a support ticket to billing, delivery or technical), logistic regression is extended with the softmax function, which turns a score for each class into probabilities that add up to 1. You will meet softmax again in neural networks (module 9).
Reading the weights
A positive weight pushes the probability up as its feature grows; a negative weight pushes it down. Each weight is the change in log-odds per unit of the feature, which is why analysts in banks and insurance like logistic regression: it is accurate enough for many tasks and easy to explain to a regulator.
Common mistakes
- Treating the 0.5 threshold as fixed. Fix: choose it from the costs of each kind of mistake.
- Calling it a regression method because of the name. It is used for classification.
- Taking log(0) when computing log loss by hand. Fix: clip probabilities to a tiny range like [1e-15, 1 − 1e-15].
- Reading the probability as certain truth. Probabilities from a model can be badly calibrated; check them on held-out data.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Logistic regression and classification · 1/7
Logistic regression predicts the probability of yes or no. Despite the name, it classifies.
Prefer a video by a teacher? Find free videos on “logistic regression sigmoid log loss explained” on YouTube ↗
In real life: Loan default scoring
A lender uses logistic regression to estimate each applicant's probability of default from repayment history, income stability and existing loans. Applicants below 5% are approved automatically, those above 30% are declined, and the middle band goes to a human underwriter. The thresholds come from business costs, not from the default 0.5, and the model's weights are documented so decisions can be explained to customers and auditors.
import math
def p_default(score):
return 1 / (1 + math.exp(-score))
for s in [-3.5, -1.0, 0.5]:
p = p_default(s)
action = "approve" if p < 0.05 else ("decline" if p > 0.30 else "review")
print(round(p, 3), action)Practice (0/3 done)
Write sigmoid(z) that returns 1 / (1 + e^(−z)) rounded to 4 decimal places (use math.exp).
Write classify(probs, threshold) that turns a list of probabilities into labels: 1 if the probability is greater than or equal to the threshold, else 0.
Write log_loss(y_true, probs): the mean of −(y·ln p + (1 − y)·ln(1 − p)) over all examples, rounded to 4 decimal places. First clip each p into [1e-15, 1 − 1e-15] so log(0) never happens.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- The ML workflow end to endThe ML workflow, regression and classification · same module
- Training: loss, backpropagation and optimisersNeural networks and deep learning
- Thresholds, ROC-AUC and imbalanced classesEvaluating models
- Bag of words, TF-IDF and text classificationNLP, embeddings and large language models
- Layers, activations and the forward passNeural networks and deep learning
- k-nearest neighboursk-NN, decision trees and ensembles
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does the sigmoid function do?
Answer: Squeezes any score into a value between 0 and 1
It maps scores to the range (0, 1) so they can be read as probabilities.
What is σ(0)?
Answer: 0.5
1 / (1 + e⁰) = 1 / 2.
A hospital wants to miss as few sick patients as possible. Compared with 0.5, the threshold should usually be…
Answer: Lower
A lower threshold flags more people, catching more true cases at the cost of more false alarms.
Which prediction gives the LARGEST log loss when the true label is 1?
Answer: p = 0.02
A confident wrong answer (p near 0 for a true 1) is punished most.
Is logistic regression used for regression or classification?
Answer: Classification
It predicts class probabilities; the name is historical.
Training loss keeps falling but validation loss starts rising. What is happening?Related
Answer: Overfitting
The network is memorising the training data; consider early stopping.
A model trained on flats of 400–1,500 sq ft predicts a 9,000 sq ft villa. What is the risk?Related
Answer: Extrapolation: the line may not hold far outside the training range
Patterns learned in one range may not continue outside it.
You lower the classification threshold from 0.5 to 0.2. What usually happens?Related
Answer: Recall goes up and precision goes down
More cases are flagged: more caught, but more false alarms.
In a class, P(plays cricket) = 0.6, P(plays football) = 0.3 and P(plays both) = 0.2. What is P(cricket or football)?Related
Answer: 0.7
0.6 + 0.3 − 0.2 = 0.7. Subtract the overlap so the students who play both are counted once.
From Probability basics
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “The ML workflow, regression and classification”. The module exam comes next.
- Module 5 exam: The ML workflow, regression and classification · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Evaluating models. 62 topics left in the course before the final exam.