🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Logistic Regression

Logistic regression sorts rows into two groups. It turns each row into a chance, then calls it one group or the other.

The sigmoid curve

The sigmoid turns a big negative number into a chance near 0. It turns a big positive number into a chance near 1.

import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

print(np.round(sigmoid(np.array([-2.0, 0.0, 2.0])), 3))

Chances for one tumour

predict_proba() gives two chances that add to 1. The first row is likely malignant, with a chance of 0.86.

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LogisticRegression(max_iter=5000)
model.fit(X_train, y_train)
print(model.predict_proba(X_test[:1]).round(3))

Move the threshold

A threshold of 0.9 calls fewer tumours malignant than a threshold of 0.5.

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LogisticRegression(max_iter=5000)
model.fit(X_train, y_train)
for threshold in [0.5, 0.9]:
    count = int((model.predict_proba(X_test)[:, 1] >= threshold).sum())
    print(threshold, count)

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

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = LogisticRegression(max_iter=5000)
model.fit(X_train, y_train)
print("Train accuracy:", round(model.score(X_train, y_train), 4))
print("Test accuracy:", round(model.score(X_test, y_test), 4))
print("First probabilities:", np.round(model.predict_proba(X_test[:3]), 3))
print("First predictions:", model.predict(X_test[:3]))
print("First actual labels:", y_test[:3])
for threshold in [0.5, 0.9]:
    count = int((model.predict_proba(X_test)[:, 1] >= threshold).sum())
    print("Threshold:", threshold, "predicted malignant:", count)

Key points

  • Classification: a model that sorts rows into groups, like benign or malignant
  • LogisticRegression: the sklearn model for two-group sorting
  • Sigmoid: the curve that turns any number into a chance between 0 and 1
  • Probability: a number between 0 and 1 that says how likely a group is
  • Use predict_proba() to see the chance for each group
  • Threshold: the chance cut-off that decides the group, usually 0.5
  • Move the threshold up to call fewer rows malignant

In this example, the Breast Cancer data is split with random_state 42. LogisticRegression learns from the training tumours and scores 0.965 on the test set. The first test tumour gets a malignant chance of 0.86, so it is called malignant. At a threshold of 0.5 the model calls 90 test tumours malignant. At a threshold of 0.9 it calls only 78 malignant. The threshold is a choice, and moving it trades one kind of mistake for the other.

Note

The Breast Cancer data holds 569 tumours, each with 30 measurements, labelled benign or malignant.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does the sigmoid do in logistic regression?