Reading history

Logistic Regression in Python: Classification Explained

5 min read 5 views

Learn logistic regression for classification in Python: the sigmoid function, predict_proba, decision thresholds, scaling pipelines and key settings.

Despite its name, logistic regression is a classification model: it predicts which group something belongs to, such as pass or fail, spam or not spam, malignant or benign. It works out a probability between 0 and 1 and then turns that probability into a decision. It is fast, easy to explain and a strong first model for almost any yes/no problem.

In this lesson you will learn

  • How the sigmoid function turns a score into a probability
  • Using predict_proba and predict
  • The decision threshold
  • Training on a real dataset with scaling in a pipeline
  • Handling more than two classes

From a Line to a Probability

Logistic regression first computes a linear score, just like linear regression: z = w·x + b. It then squashes that score into the range 0 to 1 with the sigmoid function, σ(z) = 1 / (1 + e−z). Large positive scores give probabilities close to 1, large negative scores give probabilities close to 0, and a score of 0 gives exactly 0.5.

import numpy as np
from sklearn.linear_model import LogisticRegression

# Hours studied -> passed (1) or failed (0)
hours = np.array([0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6]).reshape(-1, 1)
passed = np.array([0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1])

model = LogisticRegression()
model.fit(hours, passed)

for h in [1, 3, 5]:
    prob = model.predict_proba([[h]])[0, 1]
    label = model.predict([[h]])[0]
    print(f"{h} hours -> P(pass) = {prob:.2f}, prediction = {label}")

Output

1 hours -> P(pass) = 0.05, prediction = 0
3 hours -> P(pass) = 0.42, prediction = 0
5 hours -> P(pass) = 0.90, prediction = 1
  • predict_proba() returns one probability per class; column 1 holds the probability of class 1, “pass”.
  • predict() applies a threshold of 0.5: 3 hours gives 0.42, so the prediction is “fail”, even though it is close.
  • The training data contains one student who passed after 3 hours and one who failed after 3.5. Real data is noisy, which is exactly why a probability is more useful than a hard yes or no.

A Real Classification Problem

The breast cancer dataset bundled with scikit-learn has 30 measurements of cell nuclei from 569 tissue samples, each labelled malignant or benign. It is a standard teaching dataset; the model below is a learning exercise, not a medical tool.

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

data = load_breast_cancer()
X, y = data.data, data.target
print("Samples:", X.shape[0], "| features:", X.shape[1])
print("Classes:", [str(n) for n in data.target_names])

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print(f"Test accuracy: {model.score(X_test, y_test):.3f}")

probs = model.predict_proba(X_test[:3])[:, 1]
for p in probs:
    print(f"P(benign) = {p:.3f}")

Output

Samples: 569 | features: 30
Classes: ['malignant', 'benign']
Test accuracy: 0.982
P(benign) = 0.000
P(benign) = 1.000
P(benign) = 0.006
  • make_pipeline(StandardScaler(), LogisticRegression()) scales every feature to a similar range and then fits the model. Scaling helps the solver converge and makes the coefficients comparable. See feature scaling.
  • max_iter=1000 gives the optimiser enough steps to finish; the default of 100 sometimes raises a “failed to converge” warning.
  • 98.2% accuracy is high, but accuracy alone hides which mistakes were made. A missed malignant case is far worse than a false alarm; the metrics lesson shows how to measure that.
  • The probabilities show how confident the model is for each sample. Two samples are near-certain; the third is almost certainly malignant (0.6% chance of benign).

Changing the Threshold

probs = model.predict_proba(X_test)[:, 1]   # P(benign)
cautious = (probs > 0.9).astype(int)       # call benign only when very sure

Raising the threshold makes the model say “benign” less often, so fewer malignant cases slip through, at the cost of more false alarms. Choose the threshold from the real cost of each kind of mistake, not by habit.

Useful Settings

ParameterEffect
CInverse of regularisation strength. Smaller values give a simpler model that is less likely to overfit; the default is 1.0.
class_weight="balanced"Gives the rare class more weight when classes are imbalanced
max_iterMaximum optimiser steps

For three or more classes, such as the three Iris species, the same LogisticRegression class works without changes. It produces one probability per class, and the probabilities add up to 1.

Common Mistakes

  1. Using it for numeric targets. It predicts classes; use linear regression for numbers.
  2. Skipping feature scaling, leading to slow training and convergence warnings.
  3. Treating 0.5 as a law when mistakes have very different costs.
  4. Judging only by accuracy on imbalanced data.

Practice Exercises

Exercise 1. Calculate the sigmoid of 0, 2 and −2 with NumPy.

Show answer
import numpy as np
z = np.array([0, 2, -2])
print(1 / (1 + np.exp(-z)))  # [0.5  0.881  0.119]

Exercise 2. Train logistic regression on the Iris dataset and print the probabilities for the first test flower.

Show answer
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, stratify=y)
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
print(clf.predict_proba(X_test[:1]).round(3))  # three probabilities that sum to 1

Frequently Asked Questions

Why is it called regression if it classifies?

It regresses (fits) the log-odds of the outcome as a linear function of the features. The classification step only happens when a threshold is applied to the resulting probability.

Is logistic regression still used in industry?

Yes. It is common in credit scoring, medicine and marketing because it is fast, needs little data and its coefficients can be explained to regulators and customers.

Summary

  • Logistic regression turns a linear score into a probability with the sigmoid function.
  • predict_proba gives probabilities; predict applies a threshold, 0.5 by default.
  • Scale features in a pipeline and raise max_iter if needed.
  • Pick the threshold based on the cost of each type of mistake.

Next: Classification Metrics.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *