← All posts

Machine learning algorithms › Linear models

What is logistic regression? How it predicts yes or no

What logistic regression is, how the sigmoid turns a weighted sum into a probability, how it learns and reads its weights, and how it handles three classes.

If you’ve started learning machine learning, logistic regression is probably the first model you met for yes-or-no questions, like whether an email is spam. The name may confuse you a little, though, since a model called regression is used almost entirely for classification.

Logistic regression is a classification model that weights each feature, an input value such as hours studied, adds them up, and passes the sum through the sigmoid, or logistic, function to get a probability between 0 and 1. The name regression comes from what happens inside, where the log odds of the answer are modeled as a straight line, and the scikit-learn user guide likewise calls it a linear model for classification despite its name (Logistic regression). It also comes up often because many neural network classifiers end with the same step. The Transformer paper, for one, produces next-token probabilities with “the usual learned linear transformation and softmax function” (Attention Is All You Need).

What goes wrong with a straight line

The code below makes up 40 students with the hours they studied and whether they passed (1), then fits linear regression and logistic regression to the same data and predicts for 0, 2, 4, 6, 8, and 10 hours. The hidden rule gives an even chance at 5 hours, and the seed is fixed, so you’ll see the same numbers.

import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression

rng = np.random.default_rng(seed=10)
hours = rng.uniform(0, 10, size=40).round(1)  # 40 made-up students
passed = (rng.random(40) < 1 / (1 + np.exp(5 - hours))).astype(int)  # 1 = passed
X = hours.reshape(-1, 1)

linear = LinearRegression().fit(X, passed)
logistic = LogisticRegression().fit(X, passed)
grid = [[0], [2], [4], [6], [8], [10]]
print("linear  ", linear.predict(grid).round(2))
print("logistic", logistic.predict_proba(grid)[:, 1].round(3))  # chance of passing
linear   [-0.27  0.03  0.32  0.62  0.92  1.22]
logistic [0.002 0.024 0.219 0.765 0.974 0.998]

Linear regression gives −0.27 for a student who didn’t study and 1.22 for one who studied 10 hours, and both fall outside the 0 to 1 range a probability has to stay in. Clipping the line at 0 and 1 wouldn’t fix its shape, either. A straight line climbs by the same amount every hour, while the real chance barely moves at first, jumps between 4 and 6 hours, and then levels off. The logistic row follows that S-shaped curve.

How the sigmoid turns a score into a probability

Logistic regression first computes a score as linear regression would, score = weight × hours + intercept, adding one weight × feature term for each extra feature. Then the sigmoid turns the score into a value between 0 and 1. A score of 0 becomes exactly 0.5, and the further the score goes up or down, the closer it gets to 1 or 0.

w, b = logistic.coef_[0, 0], logistic.intercept_[0]
for h in [3, 7]:
    score = w * h + b
    p = 1 / (1 + np.exp(-score))  # the sigmoid
    odds = p / (1 - p)
    print(f"{h} hours: score {score:+.2f}, p {p:.3f}, odds {odds:.2f}, log odds {np.log(odds):+.2f}")
print(f"weight {w:.2f}, odds ratio {np.exp(w):.2f}, p = 0.5 at {-b / w:.2f} hours")
3 hours: score -2.50, p 0.076, odds 0.08, log odds -2.50
7 hours: score +2.40, p 0.917, odds 11.07, log odds +2.40
weight 1.22, odds ratio 3.40, p = 0.5 at 5.04 hours

Odds are the chance of passing divided by the chance of failing, so a probability of 0.917 means odds of about 11 to 1. Their logarithm, the log odds or logit, is exactly the score, as the output shows. So logistic regression fits a straight line to the log odds and uses the sigmoid to turn it back into a probability. That’s also how you read the weight. Each extra hour adds 1.22 to the log odds and multiplies the odds by exp(1.22), about 3.40, a number called the odds ratio. The probability itself, though, moves most in the middle of the curve.

Where the model draws the line

To answer yes or no, you need a threshold. For two classes, scikit-learn’s predict says yes when the probability is above 0.5 (Tuning the decision threshold). The point where the probability crosses 0.5 is called the decision boundary, and the last line above puts it at 5.04 hours for this model. Since the score is a weighted sum, the boundary stays a straight line or a flat plane even with many features.

Of course, 0.5 isn’t always the right value. If a wrong “pass” costs more than a wrong “fail,” you might call it a pass only when the model is 80% sure, and when I worked it out, that moves the boundary to 6.17 hours. A higher threshold usually raises precision, the share of predicted passes that are real, and lowers recall, the share of real passes the model catches.

How the model learns

The model looks for the weight and intercept that make the log loss, also called cross-entropy, as small as possible. Log loss applies a negative logarithm to the probability the model gave to the answer that actually happened. Telling a student who passed that they had a 90% chance costs 0.105, while saying 10% costs 2.303, so the model learns to be careful with its probabilities. Unlike least squares, though, log loss has no formula that gives the best weights in one step, so they’re improved little by little, with the gradient showing which way lowers the loss. Gradient descent is the basic form of this, and scikit-learn’s default solver, lbfgs, is a related method that also estimates the curvature of the loss.

The penalty scikit-learn adds by default

scikit-learn’s LogisticRegression applies regularization by default, and its documentation says so in bold (LogisticRegression). Regularization adds a penalty for large weights to help against overfitting, where a model fits its training data so closely that it does worse on new data. In 1.9.1, the version I checked, the default is an L2 penalty on the squared weights with C=1.0. C is the inverse of the strength, so a smaller C means a stronger penalty. As the user guide notes, this default is common in machine learning but not in statistics. The Logit model in statsmodels, a statistics package, fits plain maximum likelihood, which here means minimizing the log loss alone, so its weights come out different.

import statsmodels.api as sm

free = LogisticRegression(C=np.inf).fit(X, passed)  # C=np.inf: no penalty
sm_fit = sm.Logit(passed, sm.add_constant(hours)).fit(disp=0)
print("default    ", w.round(2), b.round(2))  # weight, intercept
print("C=inf      ", free.coef_[0, 0].round(2), free.intercept_[0].round(2))
print("statsmodels", sm_fit.params[1].round(2), sm_fit.params[0].round(2))
default     1.22 -6.17
C=inf       1.43 -7.19
statsmodels 1.43 -7.19

The penalty pulled the weight down from 1.43 to 1.22, and once C=np.inf turned it off, the two packages agreed. The penalty parameter has also been deprecated since 1.8 and is set to be removed in 1.10. That’s why the 1.8 release notes say to pick L1 or L2 with l1_ratio and to turn the penalty off with C=np.inf.

More than two classes

With three or more classes, each class gets its own weights and score, and the softmax function, the many-class version of the sigmoid, turns the scores into probabilities that add up to 1. This is called multinomial, or softmax, logistic regression. scikit-learn’s wine data has 178 wines from three cultivators in one region of Italy, each measured on 13 chemical properties (Wine recognition dataset). A quarter goes to a test set, and StandardScaler rescales each feature to a mean of 0 and a standard deviation of 1 before the model learns.

from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X_wine, y_wine = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X_wine, y_wine, test_size=0.25, stratify=y_wine, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
print("test accuracy:", model.score(X_test, y_test))
probs = model.predict_proba(X_test)
i = probs.max(axis=1).argmin()  # least confident wine
print("least sure:", probs[i].round(3), "true class:", y_test[i])
test accuracy: 1.0
least sure: [0.243 0.756 0.001] true class: 1

All 45 test wines came out right, though it’s fair to remember that this is small data that’s easy to separate. For the wine it was least sure about, the model gave 0.756 to class 1, the right answer, and 0.243 to class 0. The multi_class="multinomial" you may see in older code was deprecated in 1.5 and removed in 1.8 (1.5 release notes). In 1.9.1, every solver except liblinear uses the multinomial loss for three or more classes, and for one-vs-rest, one yes-or-no model per class, you wrap the model in OneVsRestClassifier.

Why the features are scaled first

Scaling matters for two reasons. First, the L2 penalty looks only at the size of each weight, and that size depends on the feature’s units. Proline runs from 278 to 1,680 while hue stays between 0.48 and 1.71, so the same penalty presses on them very differently. Second, the solver has a harder time. When I fit the model without StandardScaler, lbfgs used up its default 100 iterations without converging, raised a ConvergenceWarning, and scored only 0.933 on the test set. The scaled version finished in 15.

Where the name came from

The logistic function itself is older than the model. According to J. S. Cramer’s history, Pierre-François Verhulst gave it its name in an 1845 paper on population growth (The Origins of Logistic Regression). In 1944, Joseph Berkson proposed it for bio-assay, which measures how living things respond to doses of a substance, and coined the word logit by analogy with Bliss’s probit (Berkson, 1944). In 1958, David Cox’s “The Regression Analysis of Binary Sequences” studied how the chance of a 1 depends on one or more variables (Cox, 1958). In their obituary of Cox, Heather Battey and Nancy Reid list it among the works through which he developed logistic regression (Obituary: D. R. Cox).

How it compares with linear regression

Side by side, the two models differ mainly in what they predict.

Linear regression Logistic regression
What it predicts A number, such as a price The probability of a class
What it minimizes Squared error Log loss
One more unit of a feature Adds the weight to the prediction Multiplies the odds by exp(weight)

When it fits and when it doesn’t

Logistic regression fits well when you need a probability you can act on and a model you can explain. Each weight reads as an odds ratio, and the threshold can follow the cost of each mistake. That’s why it often serves as the first baseline, the model a more complex one has to beat.

It fits less well when the boundary isn’t straight. If a risk is high at both very low and very high values of a measurement, a single weight that pushes only one way can’t draw that U shape. It also misses interactions, where one feature’s effect depends on another, like a treatment that works only for younger patients. You can add squared or multiplied features by hand, or turn to trees and neural networks.

If you’re trying it for the first time

If you’re new to this, I’d suggest running the code blocks above in order and then changing one thing at a time. When I lowered C from 1.0 to 0.1, the weight shrank from 1.22 to 0.76, and the chance at 10 hours dropped from 0.998 to 0.977. The user guide linked above goes further into solvers and penalties. I ran these examples on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, NumPy 2.5.4, and statsmodels 0.15.0, and 1.9.1 was the stable release on scikit-learn.org that day.

AI tools helped with the research for this post.