Logistic Regression in Python From Scratch: Math, Code and a Real Dataset

Build logistic regression two ways in NumPy, match scikit-learn, pick a decision threshold properly and see why separable data needs regularization.

Tumours plotted as malignant or benign against one cell measurement, with a fitted logistic S-curve rising from 0 to 1.

A logistic regression model trained on 455 breast tumours missed 3 of the 42 malignant tumours in the test set at the usual 0.5 threshold. Moved to a threshold of 0.10, chosen beforehand from the training data alone, the same model missed 1, at the cost of 4 extra false alarms. Nothing about the model changed. Only the rule for turning its probabilities into decisions did, and that rule is the part most tutorials leave at its default.

This tutorial explains logistic regression from the sigmoid and the log loss to Newton’s method and gradient descent, implements both from scratch in NumPy, checks the result against scikit-learn and tests it on the Wisconsin breast cancer data with a baseline, a threshold chosen by cross-validation and an experiment on what happens without regularization. Every program was run for this article with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04. The printed output was identical on Python 3.13 and on Windows 11 with Python 3.14; all 20 unit tests pass on both systems, and every output block on this page is captured from the companion repository.

What Is Logistic Regression?

Logistic regression is a supervised learning algorithm for classification. It computes a weighted sum of the input features, like linear regression, and passes it through the sigmoid function to get a probability between 0 and 1 that an example belongs to the positive class. Training picks the weights that minimize the log loss, and a threshold on the probability turns it into a yes or no decision.

Despite the name, it is a classification model, not a regression model: “regression” refers to the weighted sum it fits on the log-odds scale. It is the standard first model for binary questions such as spam or not spam, churn or stay and malignant or benign, because it is fast, gives calibrated probabilities on many problems and has weights that can be read as odds ratios. If you have not met the weighted sum and gradient descent yet, linear regression from scratch builds both step by step; this article reuses that structure. In Python, the standard implementation is scikit-learn’s LogisticRegression, which this article rebuilds by hand and then uses as a reference.

When to Use Logistic Regression (and When Not To)

SituationGood fit?Why
A yes or no outcome from numeric or encoded featuresYesThis is the task the model was made for
You need a probability, not only a labelYesThe output is a probability you can threshold, rank or average
You need to explain the decisionYesEach weight is a change in log-odds, or an odds ratio per unit of its feature
A baseline before trying trees or neural networksYesFits in milliseconds; anything more complex has to beat it
The classes are separated by a curve, not a planeNot as isAdd interaction or polynomial features, or use a tree-based model
More than two classesWith an extensionMultinomial (softmax) logistic regression; scikit-learn handles it automatically
The training classes can be separated perfectlyWith a penaltyWithout regularization the weights grow without limit (measured below)

How Logistic Regression Works

  1. Compute a score. For each example, take the weighted sum of its features plus an intercept, exactly as linear regression does.
  2. Turn the score into a probability. Pass the score through the sigmoid, which squeezes any number into the range 0 to 1.
  3. Measure the error with the log loss. Confident wrong answers cost far more than hesitant ones.
  4. Fit the weights. There is no closed-form solution, so use an iterative method: Newton’s method or gradient descent.
  5. Choose a threshold. Predict the positive class when the probability is at or above a threshold. 0.5 is the default, not a law.
  6. Evaluate per class. Report precision and recall, not just accuracy, and compare with a baseline.

In pseudocode:

Xb    = [1 | X]                          # prepend a column of ones
theta = 0
repeat until the gradient is tiny:
    p        = sigmoid(Xb theta)          # one probability per row
    gradient = Xb^T (p - y) / n  (+ penalty on the weights)
    theta    = theta - step * gradient    # or a Newton step

predict(x) = 1 if sigmoid(theta[0] + x . theta[1:]) >= threshold else 0

The Math Behind Logistic Regression

The sigmoid and the model

The sigmoid maps a score z of any size to a probability: σ(0) = 0.5, large positive scores approach 1 and large negative scores approach 0. The model applies it to the weighted sum of the k features:

where x1 to xk are the features of one example, θ0 is the intercept and θ1 to θk are the weights.

Log-odds: what the weights mean

Inverting the sigmoid shows what the weighted sum actually models:

The left side is the log of the odds p / (1 − p). So a weight is the change in log-odds per unit of its feature, and eθj is the factor by which the odds are multiplied. The effect on the probability itself is not constant: it depends on where on the S-curve the example starts, as the worked example shows.

The loss: log loss (binary cross-entropy)

where pi is the model’s probability for example i and yi is 0 or 1. For a positive example the loss is −log p: 0.69 at p = 0.5, 0.01 at p = 0.99 and 4.6 at p = 0.01, so a confident mistake costs far more than an unsure one. The second term is an optional L2 penalty with strength λ on the weights (not the intercept). The log loss is convex, so there are no local minima, but unlike the squared error of linear regression it has no closed-form minimizer.

Gradient descent and Newton’s method

The gradient has the same shape as in linear regression, with probabilities in place of predictions:

where p − y is the vector of errors and the penalty term applies to the weights only. Gradient descent steps against it with a fixed step 1/L, where L is an upper bound on the curvature (each p(1 − p) is at most 1/4). Newton’s method also uses the curvature itself, the Hessian H, and jumps to the minimum of a local quadratic approximation:

Newton’s method needs a k × k solve per step but converges in a handful of iterations; this method, applied to logistic regression, is also known as iteratively reweighted least squares (Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, section 4.4.1).

Measuring a classifier

At a threshold, every prediction is a true positive (TP), false positive (FP), true negative or false negative (FN):

Precision is the share of positive calls that were right; recall is the share of actual positives that were found. Accuracy hides both when one class is rare, which is why the experiment below reports all of them, plus the ROC AUC (how well the probabilities rank positives above negatives, independent of any threshold) and the log loss on the test set.

A Worked Example by Hand

Ten students report hours studied and whether they passed (1) or failed (0); a small, made-up dataset chosen so the first step can be checked by hand:

Hours0.51.01.52.02.53.03.54.04.55.0
Passed0001010111

At the start, all weights are 0, so every score is 0 and every probability is σ(0) = 0.5. Each example’s loss is −log 0.5 = ln 2, so the mean loss is 0.6931. The gradient is the mean of (p − y) for the intercept and of (p − y) × hours for the weight. Five students passed and five failed, so the first is (5 × 0.5 − 5 × 0.5) / 10 = 0. For the second, the hours sum to 27.5 and the hours of the students who passed sum to 18.5, so it is (0.5 × 27.5 − 18.5) / 10 = −0.475. The negative sign says: increase the weight on hours.

The program below repeats that calculation, then fits the model with both methods of the from-scratch class:

"""The article's worked example: hours studied vs pass (1) or fail (0)."""

import numpy as np

from logistic_regression import (
    LogisticRegressionScratch,
    add_intercept,
    gradient,
    log_loss,
    sigmoid,
)

hours = np.array([0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0])
passed = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0])
X = hours.reshape(-1, 1)
Xb = add_intercept(X)

# By hand at theta = 0: every probability is 0.5, the loss is ln 2.
theta0 = np.zeros(2)
print(
    f"at theta = 0: loss = {log_loss(Xb, passed, theta0):.4f} (ln 2 = {np.log(2):.4f})"
)
g = gradient(Xb, passed, theta0)
print(f"gradient: d/d(intercept) = {g[0]:.4f}, d/d(weight) = {g[1]:.4f}")

newton = LogisticRegressionScratch(method="newton").fit(X, passed)
descent = LogisticRegressionScratch(method="gd").fit(X, passed)
print(
    f"\nnewton: intercept = {newton.intercept_:.4f}, weight = {newton.coef_[0]:.4f}"
    f"  ({newton.n_iter_} iterations)"
)
print(
    f"gd:     intercept = {descent.intercept_:.4f}, weight = {descent.coef_[0]:.4f}"
    f"  ({descent.n_iter_} iterations)"
)
print(f"final loss = {newton.loss_history_[-1]:.4f}")

boundary = -newton.intercept_ / newton.coef_[0]
print(f"\nP(pass) = 0.5 at {boundary:.2f} hours")
print(
    f"each extra hour multiplies the odds of passing by {np.exp(newton.coef_[0]):.2f}"
)
print("\nhours  P(pass)")
for h in (1.0, 2.0, 3.0, 4.0, 5.0):
    p = sigmoid(np.array([newton.intercept_ + newton.coef_[0] * h]))[0]
    print(f"{h:5.1f}  {p:7.3f}")

Output:

at theta = 0: loss = 0.6931 (ln 2 = 0.6931)
gradient: d/d(intercept) = 0.0000, d/d(weight) = -0.4750

newton: intercept = -3.7219, weight = 1.3534  (5 iterations)
gd:     intercept = -3.7219, weight = 1.3534  (2487 iterations)
final loss = 0.4335

P(pass) = 0.5 at 2.75 hours
each extra hour multiplies the odds of passing by 3.87

hours  P(pass)
  1.0    0.086
  2.0    0.266
  3.0    0.584
  4.0    0.844
  5.0    0.955

Newton’s method reaches the answer in 5 iterations; gradient descent needs 2,487 steps for the same four decimals. The fitted model says the probability of passing crosses 0.5 at 2.75 hours, and each extra hour multiplies the odds of passing by 3.87. The probability column shows why a weight is not a probability change: one more hour adds 0.18 going from 1 to 2 hours, 0.32 going from 2 to 3 and 0.11 going from 4 to 5, while the odds ratio stays at 3.87 throughout.

0 1 2 3 4 5 hours studied 0.0 0.2 0.4 0.6 0.8 1.0 probability of passing P(pass) = 0.5 at 2.75 hours The fitted S-curve turns a weighted sum into a probability P(pass) = σ(-3.72 + 1.35 × hours) passed (1) failed (0)
Figure 1: The ten-student example. The fitted curve crosses 0.5 at 2.75 hours, the decision boundary for the default threshold.

Logistic Regression in Python From Scratch

The model lives in logistic_regression.py and needs only NumPy. The sigmoid splits positive and negative scores so that np.exp never overflows, even for scores like ±1000:

def sigmoid(z: FloatArray) -> FloatArray:
    """1 / (1 + e^-z), computed without overflow for large |z|."""
    out = np.empty_like(z, dtype=np.float64)
    pos = z >= 0
    out[pos] = 1.0 / (1.0 + np.exp(-z[pos]))
    ez = np.exp(z[~pos])
    out[~pos] = ez / (1.0 + ez)
    return out

The loss, gradient and Hessian follow the equations above. The loss uses np.logaddexp(0, z) − y z, which equals the cross-entropy but never takes the log of 0:

def log_loss(
    Xb: FloatArray, y: FloatArray, theta: FloatArray, l2: float = 0.0
) -> float:
    """Mean binary cross-entropy, plus (l2 / 2) * ||w||^2 (intercept not penalized)."""
    z = Xb @ theta
    # log(1 + e^z) - y * z equals -[y log p + (1 - y) log(1 - p)], without log(0)
    data = float(np.mean(np.logaddexp(0.0, z) - y * z))
    return data + 0.5 * l2 * float(theta[1:] @ theta[1:])


def gradient(
    Xb: FloatArray, y: FloatArray, theta: FloatArray, l2: float = 0.0
) -> FloatArray:
    """Gradient of log_loss with respect to theta."""
    g = Xb.T @ (sigmoid(Xb @ theta) - y) / len(y)
    g[1:] += l2 * theta[1:]
    return g


def hessian(Xb: FloatArray, theta: FloatArray, l2: float = 0.0) -> FloatArray:
    """Second derivatives of log_loss: Xb^T S Xb / n + l2 (S = p (1 - p) on the diagonal)."""
    p = sigmoid(Xb @ theta)
    h: FloatArray = (Xb * (p * (1.0 - p))[:, None]).T @ Xb / float(Xb.shape[0])
    h[1:, 1:] += l2 * np.eye(Xb.shape[1] - 1)
    return h

fit starts from zero and runs either Newton steps or gradient descent until the gradient has shrunk by a factor of 10⁸, and warns if it runs out of iterations, which is what happens on separable data without a penalty:

    def fit(self, X: ArrayLike, y: ArrayLike) -> LogisticRegressionScratch:
        X_arr, y_arr = _validate(X, y)
        Xb = add_intercept(X_arr)
        theta = np.zeros(Xb.shape[1])
        grad = gradient(Xb, y_arr, theta, self.l2)
        stop_at = self.tol * float(np.linalg.norm(grad))
        lr = self.learning_rate
        if self.method == "gd" and lr is None:
            lr = 1.0 / lipschitz_constant(Xb, self.l2)
        history = [log_loss(Xb, y_arr, theta, self.l2)]
        norms = [0.0]
        converged = float(np.linalg.norm(grad)) <= stop_at
        iteration = 0
        while not converged and iteration < self.max_iter:
            iteration += 1
            if self.method == "newton":
                step = np.linalg.lstsq(hessian(Xb, theta, self.l2), grad)[0]
                theta = theta - step
            else:
                assert lr is not None
                theta = theta - lr * grad
            grad = gradient(Xb, y_arr, theta, self.l2)
            history.append(log_loss(Xb, y_arr, theta, self.l2))
            norms.append(float(np.linalg.norm(theta[1:])))
            converged = float(np.linalg.norm(grad)) <= stop_at
        if not converged:
            warnings.warn(
                f"{self.method} stopped after {self.max_iter} iterations without "
                "converging; the classes may be separable (try l2 > 0)",
                RuntimeWarning,
                stacklevel=2,
            )
        self.learning_rate_ = lr
        self.n_iter_ = iteration
        self.converged_ = converged
        self.loss_history_ = history
        self.weight_norm_history_ = norms
        self.intercept_ = float(theta[0])
        self.coef_ = theta[1:]
        return self

The repository’s tests check what is most likely to go wrong: the sigmoid at extreme inputs, the loss and gradient at zero against the hand calculation, the gradient and Hessian against finite differences, agreement with scikit-learn with and without a penalty, Newton and gradient descent agreeing, iteration counts, separable data failing to converge without a penalty and converging with one and input validation such as labels other than 0 and 1. A separate script re-applies 11 plausible bugs to a copy of the code, from a flipped sigmoid sign to a penalized intercept; every one makes a test fail.

Logistic Regression on a Real Dataset

The Breast Cancer Wisconsin (Diagnostic) dataset has 569 tumours, each described by 30 measurements of cell nuclei computed from a digitized image of a fine-needle aspirate (UCI Machine Learning Repository). It ships with scikit-learn as load_breast_cancer.

PropertyValue
SourceWolberg, Mangasarian, Street and Street (1993), UCI Machine Learning Repository, doi:10.24432/C5DW2B; bundled with scikit-learn
LicenseCC BY 4.0
Rows and features569 tumours, 30 numeric features (mean, standard error and worst value of 10 nucleus measurements)
Classes212 malignant, 357 benign
Labels used here1 = malignant, 0 = benign (scikit-learn codes malignant as 0; the labels are flipped so that the class a screening must not miss is the positive class)
PreprocessingStandardized with a scaler fitted on the training rows only
Split80/20, stratified, random_state=42: 455 training rows (170 malignant), 114 test rows (42 malignant)

The experiment fits four models on the same training rows: a baseline that always predicts the class frequencies, the from-scratch model with Newton’s method and with gradient descent, and scikit-learn. All three logistic models use the same L2 strength. scikit-learn’s default is C=1.0, and its penalty (1/2)‖w‖² on a summed loss is the same as λ = 1 / (C n) on the mean loss used here:

C = 1.0
l2 = 1.0 / (C * n)
models = {
    "baseline (class prior)": DummyClassifier(strategy="prior"),
    "scratch, newton": LogisticRegressionScratch(method="newton", l2=l2),
    "scratch, gradient descent": LogisticRegressionScratch(method="gd", l2=l2),
    "scikit-learn (C=1.0)": LogisticRegression(C=C, tol=1e-10, max_iter=10_000),
}
print(
    f"{'model':27} {'acc':>6} {'prec':>6} {'recall':>6} {'F1':>6} {'AUC':>6} {'logloss':>8}"
)
results = {}
proba = {}
for label, model in models.items():
    model.fit(X_train, y_train)
    p = model.predict_proba(X_test)
    p = p[:, 1] if p.ndim == 2 else p
    pred = (p >= 0.5).astype(int)
    proba[label] = p
    row = {
        "accuracy": accuracy_score(y_test, pred),
        "precision": precision_score(y_test, pred, zero_division=0.0),
        "recall": recall_score(y_test, pred),
        "f1": f1_score(y_test, pred),
        "roc_auc": roc_auc_score(y_test, p),
        "log_loss": log_loss(y_test, np.clip(p, 1e-15, 1 - 1e-15)),
    }
    results[label] = row
    print(
        f"{label:27} {row['accuracy']:6.3f} {row['precision']:6.3f} {row['recall']:6.3f}"
        f" {row['f1']:6.3f} {row['roc_auc']:6.3f} {row['log_loss']:8.4f}"
    )

Output:

train rows: 455 (170 malignant), test rows: 114 (42 malignant)

model                          acc   prec recall     F1    AUC  logloss
baseline (class prior)       0.632  0.000  0.000  0.000  0.500   0.6582
scratch, newton              0.965  0.975  0.929  0.951  0.996   0.0772
scratch, gradient descent    0.965  0.975  0.929  0.951  0.996   0.0772
scikit-learn (C=1.0)         0.965  0.975  0.929  0.951  0.996   0.0772

newton: 9 iterations; gradient descent: 15980 iterations
largest weight gap, newton vs scikit-learn:  1.2e-06
largest weight gap, gd vs newton:            2.8e-06

confusion matrix, scratch newton at threshold 0.5 (rows: actual, cols: predicted)
              benign  malignant
benign            71          1
malignant          3         39

largest weights (log-odds per standard deviation) and odds ratios:
  worst texture            1.43   x 4.17
  radius error             1.24   x 3.45
  worst symmetry           1.06   x 2.89
  mean concave points      0.95   x 2.58
  area error               0.91   x 2.49

Reading the results:

  • The baseline looks respectable on accuracy and fails on everything else. Always guessing benign scores 63.2% accuracy, because 72 of the 114 test tumours are benign, but its recall is 0: it finds no malignant tumour. The log loss and AUC expose it immediately.
  • The model is strong but not perfect. Logistic regression reaches 96.5% accuracy and an ROC AUC of 0.996: the probabilities rank almost every malignant tumour above almost every benign one. At the 0.5 threshold it still misses 3 of the 42 malignant tumours, with 1 false alarm.
  • All three fits agree. The from-scratch Newton weights match scikit-learn to 1.2 × 10⁻⁶, a difference that comes from where the iterative solvers stop rather than from the model, and gradient descent matches Newton to 2.8 × 10⁻⁶. Newton took 9 iterations; gradient descent took 15,980.
  • Odds ratios are per standard deviation. Because the features are standardized, a weight of 1.43 on “worst texture” means one standard deviation more multiplies the odds of malignancy by 4.17, holding the other features fixed. Many of the 30 features are strongly correlated (radius, perimeter and area measure the same size three ways), so individual weights should be read with the same caution as in linear regression.

Choosing the Decision Threshold

The 0.5 threshold assumes that a missed malignant tumour and a false alarm cost the same. In screening they do not: a false alarm means another test, a miss can mean a delayed diagnosis. The threshold should come from the costs, and it must be chosen without looking at the test set, or the test score stops being an honest estimate.

The threshold experiment gets an out-of-fold probability for every training row from 5-fold cross-validation, with the scaler refitted inside each fold:

X_train, X_test, y_train, y_test, _ = load_raw_split()
l2 = 1.0 / len(y_train)  # the same strength as scikit-learn's default C = 1.0

oof = np.empty(len(y_train))
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for fit_idx, val_idx in folds.split(X_train, y_train):
    scaler = StandardScaler().fit(X_train[fit_idx])  # per fold: no leakage
    model = LogisticRegressionScratch(l2=1.0 / len(fit_idx))
    model.fit(scaler.transform(X_train[fit_idx]), y_train[fit_idx])
    oof[val_idx] = model.predict_proba(scaler.transform(X_train[val_idx]))

It then reads precision and recall at each threshold, picks the highest threshold that keeps out-of-fold recall at 0.98 or more, and only then applies the final model to the test rows:

out-of-fold results on the 455 training rows (170 malignant):
threshold precision  recall  missed  false alarms
      0.1     0.861   0.982       3            27
      0.2     0.927   0.971       5            13
      0.3     0.938   0.971       5            11
      0.4     0.959   0.971       5             7
      0.5     0.982   0.959       7             3
      0.6     0.994   0.941      10             1
      0.7     0.994   0.906      16             1
      0.8     0.993   0.894      18             1
      0.9     0.993   0.871      22             1

highest threshold with out-of-fold recall >= 0.98: 0.10

test rows: 114 (42 malignant)
threshold precision  recall  missed  false alarms
     0.50     0.975   0.929       3             1
     0.10     0.891   0.976       1             5
0.0 0.2 0.4 0.6 0.8 1.0 decision threshold on P(malignant) 0.800 0.825 0.850 0.875 0.900 0.925 0.950 0.975 1.000 score (5-fold cross-validation) default 0.5 chosen 0.10: recall at least 0.98 Lowering the threshold finds more tumours and raises more false alarms recall (malignant tumours found) precision (malignant calls that were right)
Figure 2: Precision and recall for every threshold from 0.01 to 0.99, from out-of-fold predictions on the 455 training rows. The threshold is chosen here, before the test rows are used.

On the training folds, lowering the threshold from 0.5 to 0.1 cut missed tumours from 7 to 3 and raised false alarms from 3 to 27. On the 114 untouched test rows, the chosen threshold of 0.10 missed 1 malignant tumour instead of 3 and raised 5 false alarms instead of 1. Recall rose from 0.929 to 0.976 and precision fell from 0.975 to 0.891. Neither threshold is “correct”; the point is that the trade-off is a decision you can make deliberately, from data the test set never saw. The probabilities are the model’s output, and the threshold is a separate policy on top of them.

What Happens Without Regularization

The 455 standardized training rows can be split perfectly by a hyperplane: some combination of the 30 features puts every malignant tumour on one side and every benign one on the other. On such data the unpenalized log loss has no minimum. Pushing the weights further along the separating direction always makes every probability more confident and the loss smaller, so the “best” weights are infinite.

The separation experiment runs unpenalized gradient descent for a million steps and reads the loss and weight norm at checkpoints; the rest of the script compares three models on the test rows:

# Gradient descent with no penalty, stopped at increasing step counts.
with warnings.catch_warnings():
    warnings.simplefilter("ignore", RuntimeWarning)
    gd = LogisticRegressionScratch(method="gd", l2=0.0, max_iter=1_000_000).fit(
        X_train, y_train
    )
print("gradient descent, no penalty, on the training rows:")
print(f"{'steps':>9} {'train loss':>11} {'weight norm':>12}")
checkpoints = [10, 100, 1_000, 10_000, 100_000, 1_000_000]
for k in checkpoints:
    print(f"{k:9,} {gd.loss_history_[k]:11.2e} {gd.weight_norm_history_[k]:12.1f}")
print(f"converged: {gd.converged_}")

Output:

gradient descent, no penalty, on the training rows:
    steps  train loss  weight norm
       10    1.52e-01          1.0
      100    7.73e-02          2.2
    1,000    5.03e-02          4.3
   10,000    3.15e-02         10.1
  100,000    1.75e-02         26.9
1,000,000    6.31e-03         77.6
converged: False

model                           test acc test loss  weight norm
scikit-learn, C=inf (none)         0.939    1.8900       1545.0
scratch gd, no penalty, 1e6        0.930    0.9640         77.6
scratch newton, l2 = 1/n           0.965    0.0772          3.8

warnings from scikit-learn with C=inf: none
training accuracy without a penalty: 1.000
1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 gradient descent step 1 0 − 2 1 0 − 1 training log loss Loss falls toward 0 1 0 0 1 0 1 1 0 2 1 0 3 1 0 4 1 0 5 1 0 6 gradient descent step 0 10 20 30 40 50 60 70 80 weight norm Weights grow without limit No penalty, separable training data: there is no minimum to converge to
Figure 3: Unpenalized gradient descent on the 455 standardized training rows, which a hyperplane separates perfectly. After 1,000,000 steps the loss is 0.0063 and still falling, and the weight norm is 77.6 and still rising.

After a million steps the training loss is 0.0063 and still falling and the weight norm is 77.6 and still rising: the model is never “done”. Training accuracy is 100%, but test performance is worse than the penalized model on every measure: accuracy 0.930 instead of 0.965 and a test log loss of 0.964 instead of 0.077, because a few overconfident wrong predictions are punished heavily. scikit-learn with C=np.inf (no penalty) stopped at a weight norm of 1,545 with a test log loss of 1.89, and printed no warning. A small L2 penalty gives the loss a real minimum: Newton’s method finds it in 9 iterations with a weight norm of 3.8.

This is not an exotic case. Separation is common when there are many features relative to the number of rows, or when one feature (or a combination) almost determines the label. The practical rule: keep a penalty on, and if you remove it, check that the weights stay finite.

Complexity and Scaling

MethodTime per iterationTypical iterations hereUse when
Newton’s method (IRLS)O(n k²) to build the Hessian, O(k³) to solve5 to 9Up to a few thousand features; the default for exact fits
Batch gradient descentO(n k)2,487 to 15,980Teaching, or as the basis for the methods below
L-BFGS (scikit-learn’s default)O(n k) plus a small historyTens to hundredsGeneral purpose, many features
Stochastic or mini-batch gradient descentO(b k) per batch of b rowsMany passes over the dataData too large for memory, or streaming

Prediction costs O(k) per example: one weighted sum and one sigmoid, which is why a trained logistic regression is easy to deploy in almost any language; machine learning with C++ covers running trained models outside Python. As with linear regression, gradient descent needs standardized features to converge in a reasonable number of steps.

Common Mistakes With Logistic Regression

1. Comparing with scikit-learn’s defaults. LogisticRegression regularizes unless told otherwise; its documentation says regularization is applied by default. An unpenalized from-scratch model will “disagree” with it even when both are correct:

ours = LogisticRegressionScratch().fit(hours, passed)
default = LogisticRegression().fit(hours, passed)
unpenalized = LogisticRegression(C=np.inf).fit(hours, passed)
matched = LogisticRegressionScratch(l2=1.0 / len(passed)).fit(hours, passed)

Output:

model                                  intercept  weight
from scratch, no penalty                 -3.7219  1.3534
scikit-learn, defaults (C=1.0)           -2.5236  0.9177
scikit-learn, C=np.inf                   -3.7234  1.3539
from scratch, l2 = 1 / (C * n)           -2.5233  0.9176

With C=np.inf, scikit-learn agrees with the unpenalized fit to three decimals (the last digits differ because L-BFGS stops at its default tolerance of 10⁻⁴); with the same penalty, the from-scratch model agrees with the defaults. Note that the old way to switch the penalty off, penalty=None, is deprecated since scikit-learn 1.8 and will be removed in 1.10; C=np.inf is the current spelling.

2. Judging by accuracy on unbalanced classes. The always-benign baseline scored 63.2% accuracy and found no malignant tumour. Report recall and precision for the class that matters, and the ROC AUC or log loss for the probabilities.

3. Keeping the 0.5 threshold without asking what an error costs. The same model missed 3 or 1 malignant tumours depending only on the threshold. Choose it on training or validation data, never on the test set.

4. Removing the penalty on separable data. The weights grow without limit, the probabilities become overconfident and test log loss went from 0.077 to 1.89, with no warning from scikit-learn.

5. Reading a weight as a change in probability. A weight changes the log-odds by a fixed amount; the change in probability depends on where you start. In the worked example, one extra hour added 0.32 to the probability of passing between 2 and 3 hours, and only 0.11 between 4 and 5.

ModelOutputDecision boundaryKey difference from logistic regression
Logistic regressionProbability of a classStraight (a hyperplane)The baseline: log loss, convex, weights as odds ratios
Linear regressionA numberNot a classifierSame weighted sum without the sigmoid; squared error
Linear support vector machineA score and a labelStraightMaximizes the margin with hinge loss; no probabilities by default
Naive BayesProbability of a classStraight or curvedGenerative: models each feature given the class, assuming independence
k-nearest neighborsVote of the nearest examplesAny shapeNo training; needs scaled features and stores all the data
Decision treeClass from a leafAxis-aligned stepsLearns thresholds on single features; captures interactions

Key Takeaways

  • Logistic regression turns a weighted sum into a probability with the sigmoid and is fitted by minimizing the log loss; there is no closed-form solution.
  • Newton’s method converged in 5 to 9 iterations here; gradient descent needed thousands of steps for the same answer.
  • The threshold is a decision, not part of the model. Moving it from 0.5 to 0.10, chosen by cross-validation on the training rows, cut missed malignant tumours in the test set from 3 to 1 and raised false alarms from 1 to 5.
  • scikit-learn’s LogisticRegression is regularized by default (C=1.0); use C=np.inf for an unpenalized fit, since penalty=None is deprecated.
  • On separable data an unpenalized model never converges. Its weights grew without limit and test log loss rose from 0.077 to 1.89, with no warning.
  • Weights are changes in log-odds, and eweight is an odds ratio; the effect on probability depends on the starting point.

Conclusion

Logistic regression is linear regression with two changes: a sigmoid on the output and a loss that punishes confident mistakes. Those two changes are enough to make it a probability model, and they bring the questions every classifier raises: which threshold, measured how and on which data. A model with an ROC AUC of 0.996 still missed three malignant tumours at the default threshold, and the fix was not a better model but a deliberate choice of how to use it.

The same pieces carry forward. The sigmoid becomes the softmax for more than two classes and the activation inside neural networks, the log loss is the training objective of most modern classifiers, and the penalty that kept the weights finite here is the regularization used everywhere else. More tutorials in this series are collected in the artificial intelligence section.

Source Code and Tests

Logistic regression build status

All programs on this page are in the machine-learning/logistic-regression directory of the MYCPLUS Python examples repository.

Build and test:

python -m pip install -r requirements-dev.txt
python -m unittest discover -s tests -v
sh run_all.sh

What the build checks. On Linux and Windows, with Python 3.13, 3.14 and 3.15 and the pinned NumPy and scikit-learn versions, the build runs ruff and mypy --strict, the 20 unit tests, and checks that the worked example and the threshold experiment print exactly the output shown on this page. It also runs the breast cancer experiment and the default-regularization program, and on Linux re-applies 11 deliberate bugs and confirms that each one makes a test fail. The million-step separation experiment is not run in CI.

What I Verified

CheckUbuntu 24.04Windows 11
EnvironmentPython 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1; every output block on this page captured from these runsWindows 11 (build 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1
Same programs on Python 3.13.18Identical output for the worked example, both experiments and the pitfall programNot applicable
20 unit tests (unittest)PassPass
ruff check, ruff format --check, mypy --strictNo issuesNo issues
Output of the worked example and the threshold experimentMatches this pageMatches this page
Breast cancer experimentMetrics as shown; Newton vs scikit-learn weights within 1.2 × 10⁻⁶Same printed output; saved values agree with Ubuntu to within a relative 10⁻⁸
Separation experimentWeight norm 77.6 after 1,000,000 steps; no warning from scikit-learn with C=np.infSame printed output; saved values agree with Ubuntu to within a relative 10⁻¹¹
11 deliberate bugsAll 11 caughtAll 11 caught

Not covered: macOS, ARM processors, other NumPy or scikit-learn versions and multi-threaded BLAS settings other than the defaults.

Scroll to Top