Python ML Logistic Regression from Scratch
Logistic regression from scratch is gradient descent on a new loss. The sigmoid turns the line into a chance, and the loss punishes confident mistakes.
The sigmoid of a straight line
One feature times a weight, plus a bias, goes through the sigmoid to give a chance.
import numpy as np
weight = -34.0
bias = 4.1
x = 0.1
prob = 1 / (1 + np.exp(-(weight * x + bias)))
print(round(float(prob), 3))Log loss punishes confident misses
A chance of 0.9 for the true group costs little. A chance of 0.1 for the true group costs a lot.
import numpy as np
print(round(float(-np.log(0.9)), 3))
print(round(float(-np.log(0.1)), 3))One gradient step
The error is the chance minus the true label. The weight moves against the average error times x.
import numpy as np
x = np.array([0.05, 0.1, 0.15])
y = np.array([1, 1, 0])
weight = 0.0
bias = 0.0
prob = 1 / (1 + np.exp(-(weight * x + bias)))
error = prob - y
weight = weight - 10.0 * np.mean(error * x)
bias = bias - 10.0 * np.mean(error)
print(round(float(weight), 4))
print(round(float(bias), 4))Example
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X = data.data[:, [5]]
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
weight = 0.0
bias = 0.0
rate = 10.0
for _ in range(5000):
z = weight * X_train[:, 0] + bias
prob = 1 / (1 + np.exp(-z))
error = prob - y_train
weight = weight - rate * np.mean(error * X_train[:, 0])
bias = bias - rate * np.mean(error)
z_test = weight * X_test[:, 0] + bias
prob_test = 1 / (1 + np.exp(-z_test))
scratch_pred = (prob_test >= 0.5).astype(int)
scratch_acc = np.mean(scratch_pred == y_test)
model = LogisticRegression(max_iter=5000, C=1000000)
model.fit(X_train, y_train)
print("From scratch weight:", round(float(weight), 3))
print("From scratch bias:", round(float(bias), 3))
print("From scratch accuracy:", round(float(scratch_acc), 4))
print("sklearn weight:", round(float(model.coef_[0][0]), 3))
print("sklearn bias:", round(float(model.intercept_[0]), 3))
print("sklearn accuracy:", round(model.score(X_test, y_test), 4))
print("Same predictions:", bool(np.array_equal(scratch_pred, model.predict(X_test))))Key points
- Log loss: the error measure for chances, short for logarithmic loss
- Use log loss because a plain squared error misleads on chances
- A confident wrong chance costs far more than a unsure wrong chance
- Gradient descent still works: the same loop, a new gradient
- Use one feature here so the maths stays visible
- sklearn adds a small shrink to its weights by default
- Set C very large in sklearn to switch that shrink almost off
In this example, one Breast Cancer feature, the mean compactness, sorts the tumours. Gradient descent runs 5000 steps at a rate of 10 on the log loss. The from-scratch weight is -34.068 and the bias is 4.123, while sklearn gives -34.095 and 4.126. Both versions score 0.8112 on the test set and make exactly the same predictions. One feature alone is a weak sorter, and that is the point: the two methods agree even when the answer is modest.
Note
The two versions must agree on the same data and split. The final lines of the example show the match.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why does logistic regression use log loss instead of squared error?