Machine Learning from Scratch · Classifying
Logistic Regression: From Score to Chance
Turn a straight line into a probability with the sigmoid curve, predict each student's chance of passing, then take one learning step.
logistic.py
import math
# Hours studied, and whether each student passed (1) or not (0).
hours = [1, 2, 3, 4, 5]
passed = [0, 0, 1, 1, 1]
w, b = 1.0, -3.0 # the model's knobs
# The chance of passing: squash w·x + b into 0 to 1 with the sigmoid.
probs = []
for x in hours:
z = w * x + b
p = 1 / (1 + math.exp(-z))
probs.append(round(p, 2))
print("chances:", probs)
# One step of learning: move w and b against the gradient of the log loss.
errors = [p - y for p, y in zip(probs, passed)]
w = w - 0.5 * sum([e * x for e, x in zip(errors, hours)]) / len(hours)
b = b - 0.5 * sum(errors) / len(hours)
print("new w and b:", round(w, 2), round(b, 2))
Step by step
- The
math module gives us exp, needed for the sigmoid. - Five students' study hours.
- Who passed: the students with 1 and 2 hours failed (0), the rest passed (1). On the chart, each student is a dot at 0 or at 1.
- The model has two knobs, like linear regression:
w and b. But instead of predicting a score, it will predict a chance of passing. The S-shaped curve on the chart is that chance for every number of hours. - A list to collect each student's chance of passing.
- The first student: 1 hour.
- 1 × 1 + (−3) = −2: the same straight line as before.
- The sigmoid squashes −2 into 0.12: a 12% chance of passing.
- The chance is stored, rounded. A hollow dot appears on the curve above 1 hour.
- Next: 2 hours.
- 2 − 3 = −1.
- Sigmoid of −1: 0.27.
- 0.27 is added to the end of the list that
probs points to. - Next: 3 hours.
- 3 − 3 = 0.
- Sigmoid of 0 is exactly 0.5: the model is completely unsure about this student, who actually passed.
- 0.5 is added to the end of the list that
probs points to. - Next: 4 hours.
- 4 − 3 = 1.
- Sigmoid of 1: 0.73.
- 0.73 is added to the end of the list that
probs points to. - The last student: 5 hours.
- 5 − 3 = 2.
- Sigmoid of 2: 0.88.
- 0.88 is added to the end of the list that
probs points to. - All five students have a chance.
- Chances 0.12, 0.27, 0.5, 0.73, 0.88: they rise with study time, as they should. The red lines on the chart are the gaps between each chance and what really happened.
- Each error is chance − answer: 0.12, 0.27, −0.5, −0.27, −0.12. Positive means "too hopeful", negative "too doubtful".
w grows from 1 to 1.25: the curve gets steeper, more confident.b moves from −3 to −2.95, shifting the curve slightly left.- After one step, the 3-hour student's chance would be about 0.69 instead of 0.5. More steps would keep sharpening the curve. Logistic regression is linear regression plus a sigmoid, and it is the classic way to predict a yes/no chance.