A logistic regression mannequin skilled on 455 breast tumours missed 3 of the 42 malignant tumours within the take a look at set on the ordinary 0.5 threshold. Moved to a threshold of 0.10, chosen beforehand from the coaching knowledge alone, the identical mannequin missed 1, at the price of 4 additional false alarms. Nothing concerning the mannequin modified. Solely the rule for turning its possibilities into selections did, and that rule is the half most tutorials depart at its default.
This tutorial explains logistic regression from the sigmoid and the log loss to Newton’s technique and gradient descent, implements each from scratch in NumPy, checks the outcome in opposition to scikit-learn and assessments it on the Wisconsin breast most cancers knowledge with a baseline, a threshold chosen by cross-validation and an experiment on what occurs with out regularization. Each program was run for this text with Python 3.15.2, NumPy 2.5.5 and scikit-learn 1.9.1 on Ubuntu 24.04. The printed output was similar on Python 3.13 and on Home windows 11 with Python 3.14; all 20 unit assessments move on each programs, and each output block on this web page is captured from the companion repository.
What Is Logistic Regression?
Logistic regression is a supervised studying algorithm for classification. It computes a weighted sum of the enter options, like linear regression, and passes it by the sigmoid perform to get a chance between 0 and 1 that an instance belongs to the constructive class. Coaching picks the weights that decrease the log loss, and a threshold on the chance turns it right into a sure or no choice.
Regardless of the identify, it’s a classification mannequin, not a regression mannequin: “regression” refers back to the weighted sum it matches on the log-odds scale. It’s the usual first mannequin for binary questions corresponding to spam or not spam, churn or keep and malignant or benign, as a result of it’s quick, provides calibrated possibilities on many issues and has weights that may be learn as odds ratios. In case you have not met the weighted sum and gradient descent but, linear regression from scratch builds each step-by-step; this text reuses that construction. In Python, the usual implementation is scikit-learn’s LogisticRegression, which this text rebuilds by hand after which makes use of as a reference.
When to Use Logistic Regression (and When Not To)
| Scenario | Good match? | Why |
|---|---|---|
| A sure or no consequence from numeric or encoded options | Sure | That is the duty the mannequin was made for |
| You want a chance, not solely a label | Sure | The output is a chance you possibly can threshold, rank or common |
| You’ll want to clarify the choice | Sure | Every weight is a change in log-odds, or an odds ratio per unit of its function |
| A baseline earlier than attempting bushes or neural networks | Sure | Suits in milliseconds; something extra advanced has to beat it |
| The lessons are separated by a curve, not a airplane | Not as is | Add interplay or polynomial options, or use a tree-based mannequin |
| Greater than two lessons | With an extension | Multinomial (softmax) logistic regression; scikit-learn handles it mechanically |
| The coaching lessons might be separated completely | With a penalty | With out regularization the weights develop with out restrict (measured under) |
How Logistic Regression Works
- Compute a rating. For every instance, take the weighted sum of its options plus an intercept, precisely as linear regression does.
- Flip the rating right into a chance. Go the rating by the sigmoid, which squeezes any quantity into the vary 0 to 1.
- Measure the error with the log loss. Assured improper solutions price way over hesitant ones.
- Match the weights. There isn’t any closed-form resolution, so use an iterative technique: Newton’s technique or gradient descent.
- Select a threshold. Predict the constructive class when the chance is at or above a threshold. 0.5 is the default, not a legislation.
- Consider per class. Report precision and recall, not simply accuracy, and evaluate with a baseline.
In pseudocode:
Xb = [1 | X] # prepend a column of ones
theta = 0
repeat till the gradient is tiny:
p = sigmoid(Xb theta) # one chance 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 mannequin
The sigmoid maps a rating z of any dimension to a chance: σ(0) = 0.5, massive constructive scores method 1 and huge unfavorable scores method 0. The mannequin applies it to the weighted sum of the ok options:
the place x1 to xok are the options of 1 instance, θ0 is the intercept and θ1 to θok are the weights.
Log-odds: what the weights imply
Inverting the sigmoid exhibits what the weighted sum truly fashions:
The left aspect is the log of the percentages p / (1 − p). So a weight is the change in log-odds per unit of its function, and eθj is the issue by which the percentages are multiplied. The impact on the chance itself will not be fixed: it relies on the place on the S-curve the instance begins, because the labored instance exhibits.
The loss: log loss (binary cross-entropy)
the place pi is the mannequin’s chance for instance i and yi is 0 or 1. For a constructive instance 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 assured mistake prices way over an not sure one. The second time period is an optionally available L2 penalty with energy λ on the weights (not the intercept). The log loss is convex, so there aren’t any native minima, however not like the squared error of linear regression it has no closed-form minimizer.
Gradient descent and Newton’s technique
The gradient has the identical form as in linear regression, with possibilities instead of predictions:
the place p − y is the vector of errors and the penalty time period applies to the weights solely. Gradient descent steps in opposition to it with a set step 1/L, the place L is an higher certain on the curvature (every p(1 − p) is at most 1/4). Newton’s technique additionally makes use of the curvature itself, the Hessian H, and jumps to the minimal of an area quadratic approximation:
Newton’s technique wants a ok × ok resolve per step however converges in a handful of iterations; this technique, utilized to logistic regression, is also referred to as iteratively reweighted least squares (Hastie, Tibshirani and Friedman, The Parts of Statistical Studying, part 4.4.1).
Measuring a classifier
At a threshold, each prediction is a real constructive (TP), false constructive (FP), true unfavorable or false unfavorable (FN):
Precision is the share of constructive calls that had been proper; recall is the share of precise positives that had been discovered. Accuracy hides each when one class is uncommon, which is why the experiment under experiences all of them, plus the ROC AUC (how nicely the chances rank positives above negatives, impartial of any threshold) and the log loss on the take a look at set.
A Labored Instance by Hand
Ten college students report hours studied and whether or not they handed (1) or failed (0); a small, made-up dataset chosen so step one might be checked by hand:
| Hours | 0.5 | 1.0 | 1.5 | 2.0 | 2.5 | 3.0 | 3.5 | 4.0 | 4.5 | 5.0 |
|---|---|---|---|---|---|---|---|---|---|---|
| Handed | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 1 |
Initially, all weights are 0, so each rating is 0 and each chance is σ(0) = 0.5. Every instance’s loss is −log 0.5 = ln 2, so the imply loss is 0.6931. The gradient is the imply of (p − y) for the intercept and of (p − y) × hours for the load. 5 college students handed and 5 failed, so the primary is (5 × 0.5 − 5 × 0.5) / 10 = 0. For the second, the hours sum to 27.5 and the hours of the scholars who handed sum to 18.5, so it’s (0.5 × 27.5 − 18.5) / 10 = −0.475. The unfavorable signal says: enhance the load on hours.
This system under repeats that calculation, then matches the mannequin with each strategies of the from-scratch class:
"""The article's labored instance: hours studied vs move (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])
handed = 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: each chance is 0.5, the loss is ln 2.
theta0 = np.zeros(2)
print(
f"at theta = 0: loss = {log_loss(Xb, handed, theta0):.4f} (ln 2 = {np.log(2):.4f})"
)
g = gradient(Xb, handed, theta0)
print(f"gradient: d/d(intercept) = {g[0]:.4f}, d/d(weight) = {g[1]:.4f}")
newton = LogisticRegressionScratch(technique="newton").match(X, handed)
descent = LogisticRegressionScratch(technique="gd").match(X, handed)
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"ultimate loss = {newton.loss_history_[-1]:.4f}")
boundary = -newton.intercept_ / newton.coef_[0]
print(f"nP(move) = 0.5 at {boundary:.2f} hours")
print(
f"every additional hour multiplies the percentages of passing by {np.exp(newton.coef_[0]):.2f}"
)
print("nhours P(move)")
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)
ultimate loss = 0.4335
P(move) = 0.5 at 2.75 hours
every additional hour multiplies the percentages of passing by 3.87
hours P(move)
1.0 0.086
2.0 0.266
3.0 0.584
4.0 0.844
5.0 0.955
Newton’s technique reaches the reply in 5 iterations; gradient descent wants 2,487 steps for a similar 4 decimals. The fitted mannequin says the chance of passing crosses 0.5 at 2.75 hours, and every additional hour multiplies the percentages of passing by 3.87. The chance column exhibits why a weight will not be a chance change: yet one more hour provides 0.18 going from 1 to 2 hours, 0.32 going from 2 to three and 0.11 going from 4 to five, whereas the percentages ratio stays at 3.87 all through.
Logistic Regression in Python From Scratch
The mannequin lives in logistic_regression.py and wishes solely NumPy. The sigmoid splits constructive and unfavorable scores in order that np.exp by no means overflows, even for scores like ±1000:
def sigmoid(z: FloatArray) -> FloatArray:
"""1 / (1 + e^-z), computed with out overflow for giant |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 comply with the equations above. The loss makes use of np.logaddexp(0, z) − y z, which equals the cross-entropy however by no means takes the log of 0:
def log_loss(
Xb: FloatArray, y: FloatArray, theta: FloatArray, l2: float = 0.0
) -> float:
"""Imply 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)], with out log(0)
knowledge = float(np.imply(np.logaddexp(0.0, z) - y * z))
return knowledge + 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.form[0])
h[1:, 1:] += l2 * np.eye(Xb.form[1] - 1)
return h
match begins from zero and runs both Newton steps or gradient descent till the gradient has shrunk by an element of 10⁸, and warns if it runs out of iterations, which is what occurs on separable knowledge with no penalty:
def match(self, X: ArrayLike, y: ArrayLike) -> LogisticRegressionScratch:
X_arr, y_arr = _validate(X, y)
Xb = add_intercept(X_arr)
theta = np.zeros(Xb.form[1])
grad = gradient(Xb, y_arr, theta, self.l2)
stop_at = self.tol * float(np.linalg.norm(grad))
lr = self.learning_rate
if self.technique == "gd" and lr is None:
lr = 1.0 / lipschitz_constant(Xb, self.l2)
historical past = [log_loss(Xb, y_arr, theta, self.l2)]
norms = [0.0]
converged = float(np.linalg.norm(grad)) <= stop_at
iteration = 0
whereas not converged and iteration < self.max_iter:
iteration += 1
if self.technique == "newton":
step = np.linalg.lstsq(hessian(Xb, theta, self.l2), grad)[0]
theta = theta - step
else:
assert lr will not be None
theta = theta - lr * grad
grad = gradient(Xb, y_arr, theta, self.l2)
historical past.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.technique} stopped after {self.max_iter} iterations with out "
"converging; the lessons could also be separable (attempt l2 > 0)",
RuntimeWarning,
stacklevel=2,
)
self.learning_rate_ = lr
self.n_iter_ = iteration
self.converged_ = converged
self.loss_history_ = historical past
self.weight_norm_history_ = norms
self.intercept_ = float(theta[0])
self.coef_ = theta[1:]
return self
The repository’s assessments examine what’s most definitely to go improper: the sigmoid at excessive inputs, the loss and gradient at zero in opposition to the hand calculation, the gradient and Hessian in opposition to finite variations, settlement with scikit-learn with and with no penalty, Newton and gradient descent agreeing, iteration counts, separable knowledge failing to converge with no penalty and converging with one and enter validation corresponding to labels aside from 0 and 1. A separate script re-applies 11 believable bugs to a duplicate of the code, from a flipped sigmoid signal to a penalized intercept; each one makes a take a look at fail.
Logistic Regression on a Actual Dataset
The Breast Most cancers Wisconsin (Diagnostic) dataset has 569 tumours, every described by 30 measurements of cell nuclei computed from a digitized picture of a fine-needle aspirate (UCI Machine Studying Repository). It ships with scikit-learn as load_breast_cancer.
| Property | Worth |
|---|---|
| Supply | Wolberg, Mangasarian, Avenue and Avenue (1993), UCI Machine Studying Repository, doi:10.24432/C5DW2B; bundled with scikit-learn |
| License | CC BY 4.0 |
| Rows and options | 569 tumours, 30 numeric options (imply, normal error and worst worth of 10 nucleus measurements) |
| Lessons | 212 malignant, 357 benign |
| Labels used right here | 1 = malignant, 0 = benign (scikit-learn codes malignant as 0; the labels are flipped in order that the category a screening should not miss is the constructive class) |
| Preprocessing | Standardized with a scaler fitted on the coaching rows solely |
| Cut up | 80/20, stratified, random_state=42: 455 coaching rows (170 malignant), 114 take a look at rows (42 malignant) |
The experiment matches 4 fashions on the identical coaching rows: a baseline that all the time predicts the category frequencies, the from-scratch mannequin with Newton’s technique and with gradient descent, and scikit-learn. All three logistic fashions use the identical L2 energy. scikit-learn’s default is C=1.0, and its penalty (1/2)‖w‖² on a summed loss is similar as λ = 1 / (C n) on the imply loss used right here:
C = 1.0
l2 = 1.0 / (C * n)
fashions = {
"baseline (class prior)": DummyClassifier(technique="prior"),
"scratch, newton": LogisticRegressionScratch(technique="newton", l2=l2),
"scratch, gradient descent": LogisticRegressionScratch(technique="gd", l2=l2),
"scikit-learn (C=1.0)": LogisticRegression(C=C, tol=1e-10, max_iter=10_000),
}
print(
f"{'mannequin':27} {'acc':>6} {'prec':>6} {'recall':>6} {'F1':>6} {'AUC':>6} {'logloss':>8}"
)
outcomes = {}
proba = {}
for label, mannequin in fashions.objects():
mannequin.match(X_train, y_train)
p = mannequin.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)),
}
outcomes[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:
practice rows: 455 (170 malignant), take a look at rows: 114 (42 malignant)
mannequin 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 hole, newton vs scikit-learn: 1.2e-06
largest weight hole, gd vs newton: 2.8e-06
confusion matrix, scratch newton at threshold 0.5 (rows: precise, cols: predicted)
benign malignant
benign 71 1
malignant 3 39
largest weights (log-odds per normal 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
imply concave factors 0.95 x 2.58
space error 0.91 x 2.49
Studying the outcomes:
- The baseline appears to be like respectable on accuracy and fails on the whole lot else. At all times guessing benign scores 63.2% accuracy, as a result of 72 of the 114 take a look at tumours are benign, however its recall is 0: it finds no malignant tumour. The log loss and AUC expose it instantly.
- The mannequin is powerful however not excellent. Logistic regression reaches 96.5% accuracy and an ROC AUC of 0.996: the chances rank nearly each malignant tumour above nearly each benign one. On the 0.5 threshold it nonetheless misses 3 of the 42 malignant tumours, with 1 false alarm.
- All three matches agree. The from-scratch Newton weights match scikit-learn to 1.2 × 10⁻⁶, a distinction that comes from the place the iterative solvers cease somewhat than from the mannequin, and gradient descent matches Newton to 2.8 × 10⁻⁶. Newton took 9 iterations; gradient descent took 15,980.
- Odds ratios are per normal deviation. As a result of the options are standardized, a weight of 1.43 on “worst texture” means one normal deviation extra multiplies the percentages of malignancy by 4.17, holding the opposite options mounted. Most of the 30 options are strongly correlated (radius, perimeter and space measure the identical dimension 3 ways), so particular person weights must be learn with the identical warning as in linear regression.
Selecting the Choice Threshold
The 0.5 threshold assumes {that a} missed malignant tumour and a false alarm price the identical. In screening they don’t: a false alarm means one other take a look at, a miss can imply a delayed analysis. The edge ought to come from the prices, and it should be chosen with out wanting on the take a look at set, or the take a look at rating stops being an sincere estimate.
The edge experiment will get an out-of-fold chance for each coaching row from 5-fold cross-validation, with the scaler refitted inside every fold:
X_train, X_test, y_train, y_test, _ = load_raw_split()
l2 = 1.0 / len(y_train) # the identical energy 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.cut up(X_train, y_train):
scaler = StandardScaler().match(X_train[fit_idx]) # per fold: no leakage
mannequin = LogisticRegressionScratch(l2=1.0 / len(fit_idx))
mannequin.match(scaler.remodel(X_train[fit_idx]), y_train[fit_idx])
oof[val_idx] = mannequin.predict_proba(scaler.remodel(X_train[val_idx]))
It then reads precision and recall at every threshold, picks the best threshold that retains out-of-fold recall at 0.98 or extra, and solely then applies the ultimate mannequin to the take a look at rows:
out-of-fold outcomes on the 455 coaching 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
take a look at 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
On the coaching folds, reducing the edge from 0.5 to 0.1 minimize missed tumours from 7 to three and raised false alarms from 3 to 27. On the 114 untouched take a look at rows, the chosen threshold of 0.10 missed 1 malignant tumour as a substitute of three and raised 5 false alarms as a substitute of 1. Recall rose from 0.929 to 0.976 and precision fell from 0.975 to 0.891. Neither threshold is “right”; the purpose is that the trade-off is a call you may make intentionally, from knowledge the take a look at set by no means noticed. The possibilities are the mannequin’s output, and the edge is a separate coverage on prime of them.
What Occurs With out Regularization
The 455 standardized coaching rows might be cut up completely by a hyperplane: some mixture of the 30 options places each malignant tumour on one aspect and each benign one on the opposite. On such knowledge the unpenalized log loss has no minimal. Pushing the weights additional alongside the separating path all the time makes each chance extra assured and the loss smaller, so the “finest” weights are infinite.
The separation experiment runs unpenalized gradient descent for one million steps and reads the loss and weight norm at checkpoints; the remainder of the script compares three fashions on the take a look at rows:
# Gradient descent with no penalty, stopped at growing step counts.
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
gd = LogisticRegressionScratch(technique="gd", l2=0.0, max_iter=1_000_000).match(
X_train, y_train
)
print("gradient descent, no penalty, on the coaching rows:")
print(f"{'steps':>9} {'practice loss':>11} {'weight norm':>12}")
checkpoints = [10, 100, 1_000, 10_000, 100_000, 1_000_000]
for ok in checkpoints:
print(f"{ok: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 coaching rows:
steps practice 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
mannequin take a look at acc take a look at 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
coaching accuracy with no penalty: 1.000
After one million steps the coaching loss is 0.0063 and nonetheless falling and the load norm is 77.6 and nonetheless rising: the mannequin isn’t “carried out”. Coaching accuracy is 100%, however take a look at efficiency is worse than the penalized mannequin on each measure: accuracy 0.930 as a substitute of 0.965 and a take a look at log lack of 0.964 as a substitute of 0.077, as a result of a number of overconfident improper predictions are punished closely. scikit-learn with C=np.inf (no penalty) stopped at a weight norm of 1,545 with a take a look at log lack of 1.89, and printed no warning. A small L2 penalty provides the loss an actual minimal: Newton’s technique finds it in 9 iterations with a weight norm of three.8.
This isn’t an unique case. Separation is frequent when there are numerous options relative to the variety of rows, or when one function (or a mix) nearly determines the label. The sensible rule: maintain a penalty on, and in case you take away it, examine that the weights keep finite.
Complexity and Scaling
| Technique | Time per iteration | Typical iterations right here | Use when |
|---|---|---|---|
| Newton’s technique (IRLS) | O(n ok²) to construct the Hessian, O(ok³) to resolve | 5 to 9 | Up to some thousand options; the default for actual matches |
| Batch gradient descent | O(n ok) | 2,487 to fifteen,980 | Instructing, or as the premise for the strategies under |
| L-BFGS (scikit-learn’s default) | O(n ok) plus a small historical past | Tens to a whole lot | Normal goal, many options |
| Stochastic or mini-batch gradient descent | O(b ok) per batch of b rows | Many passes over the information | Information too massive for reminiscence, or streaming |
Prediction prices O(ok) per instance: one weighted sum and one sigmoid, which is why a skilled logistic regression is simple to deploy in nearly any language; machine studying with C++ covers operating skilled fashions outdoors Python. As with linear regression, gradient descent wants standardized options to converge in an affordable variety of steps.
Frequent Errors With Logistic Regression
1. Evaluating with scikit-learn’s defaults. LogisticRegression regularizes until instructed in any other case; its documentation says regularization is utilized by default. An unpenalized from-scratch mannequin will “disagree” with it even when each are right:
ours = LogisticRegressionScratch().match(hours, handed)
default = LogisticRegression().match(hours, handed)
unpenalized = LogisticRegression(C=np.inf).match(hours, handed)
matched = LogisticRegressionScratch(l2=1.0 / len(handed)).match(hours, handed)
Output:
mannequin 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 match to 3 decimals (the final digits differ as a result of L-BFGS stops at its default tolerance of 10⁻⁴); with the identical penalty, the from-scratch mannequin agrees with the defaults. Observe that the outdated option to change the penalty off, penalty=None, is deprecated since scikit-learn 1.8 and will probably be eliminated in 1.10; C=np.inf is the present spelling.
2. Judging by accuracy on unbalanced lessons. The always-benign baseline scored 63.2% accuracy and located no malignant tumour. Report recall and precision for the category that issues, and the ROC AUC or log loss for the chances.
3. Retaining the 0.5 threshold with out asking what an error prices. The identical mannequin missed 3 or 1 malignant tumours relying solely on the edge. Select it on coaching or validation knowledge, by no means on the take a look at set.
4. Eradicating the penalty on separable knowledge. The weights develop with out restrict, the chances turn out to be overconfident and take a look at log loss went from 0.077 to 1.89, with no warning from scikit-learn.
5. Studying a weight as a change in chance. A weight adjustments the log-odds by a set quantity; the change in chance relies on the place you begin. Within the labored instance, one additional hour added 0.32 to the chance of passing between 2 and three hours, and solely 0.11 between 4 and 5.
| Mannequin | Output | Choice boundary | Key distinction from logistic regression |
|---|---|---|---|
| Logistic regression | Likelihood of a category | Straight (a hyperplane) | The baseline: log loss, convex, weights as odds ratios |
| Linear regression | A quantity | Not a classifier | Similar weighted sum with out the sigmoid; squared error |
| Linear assist vector machine | A rating and a label | Straight | Maximizes the margin with hinge loss; no possibilities by default |
| Naive Bayes | Likelihood of a category | Straight or curved | Generative: fashions every function given the category, assuming independence |
| k-nearest neighbors | Vote of the closest examples | Any form | No coaching; wants scaled options and shops all the information |
| Choice tree | Class from a leaf | Axis-aligned steps | Learns thresholds on single options; captures interactions |
Key Takeaways
- Logistic regression turns a weighted sum right into a chance with the sigmoid and is fitted by minimizing the log loss; there isn’t any closed-form resolution.
- Newton’s technique converged in 5 to 9 iterations right here; gradient descent wanted hundreds of steps for a similar reply.
- The edge is a call, not a part of the mannequin. Transferring it from 0.5 to 0.10, chosen by cross-validation on the coaching rows, minimize missed malignant tumours within the take a look at set from 3 to 1 and raised false alarms from 1 to five.
- scikit-learn’s
LogisticRegressionis regularized by default (C=1.0); useC=np.inffor an unpenalized match, sincepenalty=Noneis deprecated. - On separable knowledge an unpenalized mannequin by no means converges. Its weights grew with out restrict and take a look at log loss rose from 0.077 to 1.89, with no warning.
- Weights are adjustments in log-odds, and eweight is an odds ratio; the impact on chance relies on the start line.
Conclusion
Logistic regression is linear regression with two adjustments: a sigmoid on the output and a loss that punishes assured errors. These two adjustments are sufficient to make it a chance mannequin, they usually convey the questions each classifier raises: which threshold, measured how and on which knowledge. A mannequin with an ROC AUC of 0.996 nonetheless missed three malignant tumours on the default threshold, and the repair was not a greater mannequin however a deliberate selection of how one can use it.
The identical items carry ahead. The sigmoid turns into the softmax for greater than two lessons and the activation inside neural networks, the log loss is the coaching goal of most trendy classifiers, and the penalty that stored the weights finite right here is the regularization used in every single place else. Extra tutorials on this collection are collected within the synthetic intelligence part.
Supply Code and Checks
All applications on this web page are within the machine-learning/logistic-regression listing of the MYCPLUS Python examples repository.
Construct and take a look at:
python -m pip set up -r requirements-dev.txt
python -m unittest uncover -s assessments -v
sh run_all.sh
What the construct checks. On Linux and Home windows, with Python 3.13, 3.14 and three.15 and the pinned NumPy and scikit-learn variations, the construct runs ruff and mypy --strict, the 20 unit assessments, and checks that the labored instance and the edge experiment print precisely the output proven on this web page. It additionally runs the breast most cancers experiment and the default-regularization program, and on Linux re-applies 11 deliberate bugs and confirms that every one makes a take a look at fail. The million-step separation experiment will not be run in CI.
What I Verified
| Test | Ubuntu 24.04 | Home windows 11 |
|---|---|---|
| Atmosphere | Python 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1; each output block on this web page captured from these runs | Home windows 11 (construct 26300), Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1 |
| Similar applications on Python 3.13.18 | An identical output for the labored instance, each experiments and the pitfall program | Not relevant |
20 unit assessments (unittest) |
Go | Go |
ruff examine, ruff format --check, mypy --strict |
No points | No points |
| Output of the labored instance and the edge experiment | Matches this web page | Matches this web page |
| Breast most cancers experiment | Metrics as proven; Newton vs scikit-learn weights inside 1.2 × 10⁻⁶ | Similar printed output; saved values agree with Ubuntu to inside a relative 10⁻⁸ |
| Separation experiment | Weight norm 77.6 after 1,000,000 steps; no warning from scikit-learn with C=np.inf |
Similar printed output; saved values agree with Ubuntu to inside a relative 10⁻¹¹ |
| 11 deliberate bugs | All 11 caught | All 11 caught |
Not coated: macOS, ARM processors, different NumPy or scikit-learn variations and multi-threaded BLAS settings aside from the defaults.

