Homework · Runs in your browser

Logistic regression from scratch in pure Python

Build logistic regression with nothing but the standard library: a stable sigmoid, the log loss, the gradient (p - y) x, and a full-batch gradient descent loop with an optional L2 penalty. Edit starter.py, then run the tests. In the browser runner, press Run tests. In Colab or on your own machine, put starter.py and test_starter.py in one folder and run pytest. Nothing needs installing except pytest.

Hints:

  • Stable sigmoid: for z >= 0 use 1 / (1 + exp(-z)). For z < 0 use exp(z) / (1 + exp(z)). Both never overflow.
  • Log loss: clip p to [eps, 1 - eps] first, so a confident mistake gives a large number and not a crash.
  • Gradient: for each row, err = sigmoid(w . x + b) - y. The weight gradient is the mean of err * x_j and the bias gradient is the mean of err.
  • Fit: start at zero, repeat gradient steps. Add l2 * w_j to each weight gradient, but not to the bias.
  • Lesson check: x = [1, 2], y = 1, lr = 0.1, one step gives w = [0.05, 0.10], b = 0.05 and p = 0.574.
  • Try it: on x = [-2, -1, 1, 2], y = [0, 0, 1, 1] the weight keeps growing without L2 and settles near 1.458 with l2 = 0.1.

Running the tests needs JavaScript. You can still read the starter code below and run it on your own machine with pytest.

Tab inserts 4 spaces. To move on with the keyboard, press Esc, then Tab. Shift+Tab always moves back.

Show a solution

Try it yourself first. This site is static, so the solution is sent to your browser with the page; it is hidden here, not secret.

import math


def sigmoid(z):
    """Numerically stable logistic function."""
    if z >= 0:
        return 1.0 / (1.0 + math.exp(-z))
    e = math.exp(z)
    return e / (1.0 + e)


def log_loss(y_true, p_pred, eps=1e-12):
    """Mean binary cross-entropy. Probabilities are clipped to [eps, 1 - eps]."""
    total = 0.0
    for y, p in zip(y_true, p_pred):
        p = min(max(p, eps), 1.0 - eps)
        total += -(y * math.log(p) + (1 - y) * math.log(1 - p))
    return total / len(y_true)


def gradient(X, y, w, b):
    """Mean gradient of the log loss: (1/n) * sum (p - y) * x, and (1/n) * sum (p - y)."""
    n = len(X)
    gw = [0.0] * len(w)
    gb = 0.0
    for xi, yi in zip(X, y):
        p = sigmoid(sum(a * c for a, c in zip(w, xi)) + b)
        err = p - yi
        for j, c in enumerate(xi):
            gw[j] += err * c
        gb += err
    return [g / n for g in gw], gb / n


def fit_logreg(X, y, lr=0.5, epochs=1000, l2=0.0):
    """Full-batch gradient descent. The L2 penalty is not applied to the bias."""
    w = [0.0] * len(X[0])
    b = 0.0
    for _ in range(epochs):
        gw, gb = gradient(X, y, w, b)
        w = [wj - lr * (g + l2 * wj) for wj, g in zip(w, gw)]
        b -= lr * gb
    return w, b


def predict_proba(X, w, b):
    return [sigmoid(sum(a * c for a, c in zip(w, xi)) + b) for xi in X]
Show the tests (test_starter.py)

Python

import math

from starter import fit_logreg, gradient, log_loss, predict_proba, sigmoid

SEPARABLE_X = [[-2], [-1], [1], [2]]
SEPARABLE_Y = [0, 0, 1, 1]


def test_sigmoid_basic_values():
    assert sigmoid(0) == 0.5, "sigmoid(0) is exactly 0.5"
    assert math.isclose(sigmoid(2), 1 / (1 + math.exp(-2)))


def test_sigmoid_does_not_overflow():
    assert sigmoid(-1000) == 0.0, "exp(1000) overflows; use the exp(z)/(1+exp(z)) form for negative z"
    assert sigmoid(1000) == 1.0


def test_log_loss_at_one_half():
    assert math.isclose(log_loss([1, 0], [0.5, 0.5]), math.log(2)), "-log(0.5) = 0.693 for either label"


def test_log_loss_survives_a_confident_mistake():
    value = log_loss([1], [0.0])
    assert math.isfinite(value) and value > 20, "clip p to [eps, 1-eps]: the loss is large but finite"


def test_gradient_is_p_minus_y_times_x():
    gw, gb = gradient([[1, 2]], [1], [0.0, 0.0], 0.0)
    assert math.isclose(gw[0], -0.5) and math.isclose(gw[1], -1.0), "p = 0.5, so (p - y) x = -0.5 * [1, 2]"
    assert math.isclose(gb, -0.5)


def test_gradient_is_a_mean_over_rows():
    gw, gb = gradient([[1, 2], [1, 2]], [1, 1], [0.0, 0.0], 0.0)
    assert math.isclose(gw[0], -0.5) and math.isclose(gb, -0.5), "two identical rows give the same mean"


def test_one_step_matches_the_lesson():
    w, b = fit_logreg([[1, 2]], [1], lr=0.1, epochs=1)
    assert math.isclose(w[0], 0.05) and math.isclose(w[1], 0.10) and math.isclose(b, 0.05)
    p = predict_proba([[1, 2]], w, b)[0]
    assert math.isclose(p, 0.5744425168, abs_tol=1e-6), "z = 0.30, so p = 0.574"


def test_one_step_lowers_the_loss():
    before = log_loss([1], predict_proba([[1, 2]], [0.0, 0.0], 0.0))
    w, b = fit_logreg([[1, 2]], [1], lr=0.1, epochs=1)
    after = log_loss([1], predict_proba([[1, 2]], w, b))
    assert math.isclose(before, 0.6931471806, abs_tol=1e-6)
    assert math.isclose(after, 0.5543552445, abs_tol=1e-6)


def test_separable_weight_keeps_growing_without_l2():
    w100, _ = fit_logreg(SEPARABLE_X, SEPARABLE_Y, lr=0.5, epochs=100)
    w1000, _ = fit_logreg(SEPARABLE_X, SEPARABLE_Y, lr=0.5, epochs=1000)
    assert math.isclose(w100[0], 3.376, abs_tol=2e-3), "the lesson reports 3.376 after 100 steps"
    assert math.isclose(w1000[0], 5.548, abs_tol=2e-3), "the lesson reports 5.548 after 1,000 steps"


def test_l2_keeps_the_weight_finite():
    w, _ = fit_logreg(SEPARABLE_X, SEPARABLE_Y, lr=0.5, epochs=1000, l2=0.1)
    assert math.isclose(w[0], 1.458, abs_tol=2e-3), "with l2 = 0.1 the weight settles at 1.458"


def test_bias_is_not_penalised():
    X = [[0.0], [0.0], [0.0], [0.0]]
    y = [1, 1, 1, 0]
    _, b_plain = fit_logreg(X, y, lr=0.5, epochs=500, l2=0.0)
    _, b_l2 = fit_logreg(X, y, lr=0.5, epochs=500, l2=5.0)
    assert math.isclose(b_plain, b_l2, abs_tol=1e-9), "the penalty must touch weights, not the bias"
    assert math.isclose(b_plain, math.log(3), abs_tol=1e-3), "with no features the odds are 3 to 1"