InferenceAIAll articles

Logistic Regression From Scratch in Python (NumPy Tutorial)

By InferenceAI Editorial · 10 min read · beginner · Updated

Build logistic regression with NumPy in about 30 lines (sigmoid, cross-entropy, gradients, training loop) and verify it matches scikit-learn exactly.

Logistic regression is often the first "real" classifier students meet, and it turns up in a lot of interviews too. It's simple enough to write from scratch in about 30 lines, yet it contains nearly every idea you'll meet later in deep learning: a linear model, an activation function, a loss, gradients, and an optimisation loop.

In this tutorial we'll build it from scratch with NumPy, train it, and then check it against scikit-learn. If our version is right, the two should agree to two decimal places. (Spoiler: they do.)

What logistic regression actually does

Despite the name, logistic regression is a classification algorithm. It predicts the probability that an example belongs to the positive class (spam, fraud, "will pass the exam").

It works in two steps:

  1. Compute a linear score: z = w · x + b, a weighted sum of the features plus a bias.
  2. Squash the score into a probability with the sigmoid function: p = σ(z) = 1 / (1 + e^(−z)).

If p ≥ 0.5, predict class 1; otherwise class 0. The model learns the weights w and bias b from data.

Why not plain linear regression? A straight line produces values like −3.2 or 7.5, which aren't probabilities. Sigmoid maps any number into (0, 1), and the loss we'll use penalises confident wrong answers heavily, which is what you want from a classifier.

The loss: binary cross-entropy

To learn, the model needs a number that says how wrong it is. For classification we use binary cross-entropy (also called log loss):

L = −mean[ y·log(p) + (1 − y)·log(1 − p) ]

Read it case by case:

  • When the true label is y = 1, the loss is −log(p). It's near zero if p is close to 1 and huge if p is close to 0.
  • When y = 0, the loss is −log(1 − p), the mirror image.

So confident mistakes are punished hard, and that's exactly what pushes the weights in the right direction.

The gradient, without the pain

You'll see a page of calculus in textbooks, but the result is beautifully short. For the combination of sigmoid and cross-entropy:

∂L/∂w = Xᵀ(p − y) / n ∂L/∂b = mean(p − y)

where n is the number of examples. The gradient is just the prediction error (p − y), weighted by the inputs. Intuitively: if we predicted too high for an example, move the weights away from that example's features; if too low, move towards them.

The code

First, a numerically stable sigmoid (the naive version overflows on large negative inputs; here's why) and the loss:

python
import numpy as np

def sigmoid(z):
    return np.where(z >= 0, 1 / (1 + np.exp(-np.abs(z))), np.exp(-np.abs(z)) / (1 + np.exp(-np.abs(z))))

def log_loss(y, p, eps=1e-12):
    p = np.clip(p, eps, 1 - eps)   # avoid log(0)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

Using np.abs(z) inside both branches keeps every exponent ≤ 0, so np.exp can never overflow, whichever branch np.where picks.

Now the model itself. We'll follow scikit-learn's familiar fit / predict interface:

python
class LogisticRegressionScratch:
    def __init__(self, lr=0.1, epochs=1000, l2=0.0):
        self.lr, self.epochs, self.l2 = lr, epochs, l2

    def fit(self, X, y):
        n_samples, n_features = X.shape
        self.w = np.zeros(n_features)
        self.b = 0.0
        self.history = []
        for _ in range(self.epochs):
            p = sigmoid(X @ self.w + self.b)          # forward pass
            error = p - y
            grad_w = X.T @ error / n_samples + self.l2 * self.w
            grad_b = error.mean()
            self.w -= self.lr * grad_w                # gradient descent step
            self.b -= self.lr * grad_b
            self.history.append(log_loss(y, p))
        return self

    def predict_proba(self, X):
        return sigmoid(X @ self.w + self.b)

    def predict(self, X, threshold=0.5):
        return (self.predict_proba(X) >= threshold).astype(int)

That's the whole algorithm: forward pass, error, gradient, update, repeated. The optional l2 term adds L2 regularisation, which keeps weights small to reduce overfitting.

Training it on real data

Let's generate a classification dataset and hold out 20% for testing:

python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=1000, n_features=5, n_informative=3,
                           n_redundant=0, random_state=7)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=7)

model = LogisticRegressionScratch(lr=0.1, epochs=1000).fit(X_train, y_train)

print(round(model.history[0], 4), round(model.history[-1], 4))   # 0.6931 0.3671
print((model.predict(X_test) == y_test).mean())                  # 0.87

Two things to notice:

  • The first loss is 0.6931, which is ln(2). With all weights at zero, every prediction is exactly 0.5, and −log(0.5) = ln 2. If your starting loss isn't close to this, something is wrong. It's a handy sanity check.
  • The loss falls to 0.367, and test accuracy is 87%.

Checking against scikit-learn

Now the moment of truth. scikit-learn's LogisticRegression regularises by default, so to compare like with like we switch that off with C=np.inf:

python
from sklearn.linear_model import LogisticRegression

sk = LogisticRegression(C=np.inf, max_iter=5000).fit(X_train, y_train)

print(sk.score(X_test, y_test))        # 0.87
print(np.round(model.w, 2))            # [ 0.1   0.59  1.69 -0.09  0.03]
print(np.round(sk.coef_[0], 2))        # [ 0.1   0.59  1.69 -0.09  0.03]

Same accuracy, same weights to two decimal places. Our 30 lines of NumPy reproduce the library.

The weights are also interpretable: feature 3 (weight 1.69) pushes predictions towards class 1 strongly, while features 1, 4 and 5 barely matter. That kind of explanation is one reason logistic regression is still widely used in places like finance and healthcare.

Practical tips that save hours

  1. Scale your features. Gradient descent converges much faster when features have similar ranges. Use StandardScaler (fit it on the training set only, to avoid data leakage).
  2. Watch the loss curve. If it goes up or bounces around, the learning rate is too high. If it barely moves, it's too low.
  3. Don't treat 0.5 as sacred. The threshold is a business decision. For fraud detection you might flag anything above 0.2. See our guide to precision, recall and thresholds.
  4. Check class balance first. With 99% negatives, a model that always predicts "no" gets 99% accuracy and is useless.

Where this leads

Here's the key insight: a neural network is a stack of these. Each neuron computes a weighted sum and applies an activation. The final layer of a binary classifier is often a logistic regression on learned features, and multi-class classifiers swap sigmoid for softmax. The training loop you just wrote (forward, loss, gradient, update) is the same loop that trains GPT-scale models, just with automatic differentiation and much bigger matrices.

Frequently asked questions

Is logistic regression a regression or a classification algorithm?

It's a classification algorithm. The name comes from the logistic (sigmoid) function it uses to turn a linear regression-style score into a probability, which is then thresholded to choose a class.

Why does logistic regression use cross-entropy instead of mean squared error?

With sigmoid outputs, mean squared error creates a non-convex loss with weak gradients for confident wrong predictions. Cross-entropy is convex for logistic regression and gives a simple gradient, the prediction error times the inputs, so training is faster and more reliable.

What learning rate should I use for logistic regression?

With standardised features, values between 0.01 and 0.5 usually work. Plot the loss: if it increases or oscillates, lower the learning rate; if it decreases very slowly, raise it.

Can logistic regression handle more than two classes?

Yes. Multinomial logistic regression replaces sigmoid with softmax and binary cross-entropy with categorical cross-entropy. scikit-learn's LogisticRegression handles multi-class problems automatically.

When should I use logistic regression instead of a neural network?

Use it as a strong baseline, when you have limited data, when you need interpretable coefficients, or when the relationship between features and the outcome is roughly linear. Always try it before reaching for something more complex.

#logistic-regression#machine-learning#numpy#python#classification

Sources and further reading

Practise what you just read

Solve hands-on AI and ML coding problems in your browser, with instant feedback on every test case.

Browse problems