ML Logistic Regression
Despite its name, logistic regression is a classification method. It predicts the probability that an example belongs to the positive class, then turns that probability into a yes/no answer (usually "yes" when the probability is above 0.5).
It is fast, easy to interpret and a strong baseline for almost any yes/no problem: will the customer churn, is the transaction fraudulent, will the student pass?
From a line to a probability
Linear regression produces any number from −∞ to +∞, but a probability must stay between 0 and 1. Logistic regression computes a linear score and squeezes it through the sigmoid (logistic) function:
score = b0 + b1*x
probability = 1 / (1 + e^(-score))import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
for z in [-6, -2, -0.5, 0, 0.5, 2, 6]:
print(f"score {z:5} -> probability {sigmoid(z):.3f}")score -6 -> probability 0.002
score -2 -> probability 0.119
score -0.5 -> probability 0.378
score 0 -> probability 0.500
score 0.5 -> probability 0.622
score 2 -> probability 0.881
score 6 -> probability 0.998
A score of 0 means 50/50; large positive scores approach 1, large negative scores approach 0.
A first model
Invented data: the number of driving lessons 16 learners took and whether they passed the driving test (1) or not (0).
import numpy as np
from sklearn.linear_model import LogisticRegression
lessons = np.array([3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18, 20, 22, 25, 28]).reshape(-1, 1)
passed = np.array([0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1])
model = LogisticRegression()
model.fit(lessons, passed)
print("coefficient:", model.coef_.round(3), " intercept:", model.intercept_.round(3))
print("predict 10 lessons:", model.predict([[10]]))
print("predict 20 lessons:", model.predict([[20]]))coefficient: [[0.256]] intercept: [-3.517]
predict 10 lessons: [0]
predict 20 lessons: [1]
Probabilities
predict_proba returns one column per class: the probability of 0 (fail) and of 1 (pass). The two always add up to 1.
import numpy as np
from sklearn.linear_model import LogisticRegression
lessons = np.array([3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18, 20, 22, 25, 28]).reshape(-1, 1)
passed = np.array([0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1])
model = LogisticRegression().fit(lessons, passed)
for n in [5, 10, 15, 20, 30]:
p_fail, p_pass = model.predict_proba([[n]])[0]
print(f"{n:2} lessons: P(pass) = {p_pass:.2f}")
# the lesson count where the probability crosses 50 %
b0, b1 = model.intercept_[0], model.coef_[0, 0]
print(f"50 % point: about {-b0 / b1:.1f} lessons") 5 lessons: P(pass) = 0.10
10 lessons: P(pass) = 0.28
15 lessons: P(pass) = 0.58
20 lessons: P(pass) = 0.83
30 lessons: P(pass) = 0.98
50 % point: about 13.7 lessons
The 50 % point is where the linear score b0 + b1*x equals zero, i.e. x = -b0 / b1.
Interpreting the coefficient: odds
The coefficient lives on the log-odds scale. Exponentiating it gives an odds ratio: how much the odds of passing are multiplied by each extra lesson.
import numpy as np
from sklearn.linear_model import LogisticRegression
lessons = np.array([3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 17, 18, 20, 22, 25, 28]).reshape(-1, 1)
passed = np.array([0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1])
model = LogisticRegression().fit(lessons, passed)
odds_ratio = np.exp(model.coef_[0, 0])
print(f"odds ratio per lesson: {odds_ratio:.3f}")
print(f"each lesson multiplies the odds of passing by {odds_ratio:.3f}")
print(f"five extra lessons multiply them by {odds_ratio ** 5:.2f}")odds ratio per lesson: 1.292
each lesson multiplies the odds of passing by 1.292
five extra lessons multiply them by 3.59
Many features
With more features, logistic regression works exactly the same — one coefficient per feature. On the breast-cancer data set (30 features) we standardize first: logistic regression is trained iteratively, and unscaled features slow it down or stop it from converging.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.25, random_state=0, stratify=data.target)
scaler = StandardScaler().fit(X_train)
model = LogisticRegression(max_iter=1000)
model.fit(scaler.transform(X_train), y_train)
print("train accuracy:", round(model.score(scaler.transform(X_train), y_train), 3))
print("test accuracy: ", round(model.score(scaler.transform(X_test), y_test), 3))
first = scaler.transform(X_test[:3])
print("P(benign) for 3 test tumours:", model.predict_proba(first)[:, 1].round(3))train accuracy: 0.991
test accuracy: 0.958
P(benign) for 3 test tumours: [0.996 0. 0. ]
model.score() returns accuracy for classifiers (the share of correct predictions).
Note: By default scikit-learn's
LogisticRegressionapplies a little regularization (parameterC=1.0; smaller C = stronger). It keeps coefficients small to reduce overfitting. The next lesson tunesCwith a grid search.
Go further: Logistic Regression in the Machine Learning track derives the loss from maximum likelihood and fits it from scratch with Newton's method.
Test yourself
What does logistic regression predict?
- A continuous number like a price
- The probability of a class
- A cluster number
- A decision tree
What is sigmoid(0)?
- 0
- 0.5
- 1
- Undefined
Which method returns class probabilities for a fitted classifier?
predict()predict_proba()score()decision_tree()