What Is Logistic Regression? How It Works in ML
What is logistic regression? Learn how this classification algorithm uses the sigmoid function, log loss, and gradient descent to predict probabilities and class labels.
We covered univariate and multivariate linear regression, which predict a continuous number: a price, a temperature, a length. Logistic regression answers a different question: which class does this example belong to? It is a classification algorithm, not a regression one, despite the name.
The simplest case is binary classification: the target is one of two labels, encoded as or (spam / not spam, fraud / legit, churn / stay). Instead of predicting the label directly, logistic regression predicts the probability that the example belongs to the positive class, then turns that probability into a label.
Why Not Just Use Linear Regression?
A linear model outputs any real number, from to . A probability must live in . Feeding raw as a probability breaks immediately: a confident example could score or , which means nothing as a probability.
We need to squash that unbounded score into . That is exactly what the sigmoid (logistic) function does.
Sigmoid Function
The sigmoid maps any real number to the open interval :

Its behavior is what we want from a probability:
- : ;
- : ;
- : (the midpoint).
The curve is smooth and S-shaped: small near the extremes, steepest around . That steep middle is what lets a small change in the input flip the predicted class.
Logistic Regression Equation
Logistic regression is a linear model wrapped in a sigmoid. First it computes the same weighted sum as linear regression, the logit :
Then it passes through the sigmoid to get a probability:
Where:
- : the feature vector;
- : the weight vector (one weight per feature);
- : the model bias;
- : the predicted probability that , i.e. .
The linear part is identical to multivariate regression. The only new piece is the sigmoid on top, which is what converts a score into a probability.
Decision Boundary
A probability is not yet a label. To get a class, we compare to a threshold, usually :
- predict class ;
- predict class .
Because exactly when , the threshold on is equivalent to a threshold on the logit:
The set of points where is the decision boundary. With two features it is a straight line; with features it is a hyperplane, splitting the feature space into the two predicted classes.

The boundary is linear in the features, even though the probability surface is curved by the sigmoid. The threshold does not have to be : raise it to be more conservative about predicting the positive class (higher precision), lower it to catch more positives (higher recall). More on that below.
Loss and Cost Function
For linear regression we used MSE. For logistic regression MSE is a bad choice: paired with the sigmoid it produces a non-convex cost surface full of local minima, so gradient descent can get stuck. We need a loss that is convex for this model and that punishes confident wrong answers hard.
That loss is log loss, also called binary cross-entropy. For a single example:
Only one term is ever active, because is or :
| Actual | Loss reduces to | Meaning |
|---|---|---|
| small when , as | ||
| small when , as |
The logarithm is the key: a prediction that is both confident and wrong (say when ) drives the loss toward infinity, so the model is strongly pushed to fix it.
The cost function averages this loss over all training examples:
Where:
- : the actual label ( or ) of the -th sample;
- : the predicted probability for the -th sample;
- : the total number of samples.
Gradient Descent
We minimize the same way as in linear regression: gradient descent. The remarkable part is that, after differentiating log loss through the sigmoid, the gradients come out in exactly the same form as the MSE gradients for linear regression:
Where is the value of feature in sample . The only difference from linear regression is hidden inside : here it is rather than the raw linear output. There is also no factor of , because it comes from log loss, not the squared error.
The update rule is unchanged, and all parameters are updated simultaneously using the old values:
repeat until convergence {
for j = 1 to n {
grad_w[j] = (1/N) * Σ (σ(w·x + b) - y) * x[j]
}
grad_b = (1/N) * Σ (σ(w·x + b) - y)
for j = 1 to n {
w[j] = w[j] - α * grad_w[j]
}
b = b - α * grad_b
}
Everything we learned for the regression series carries over: feature scaling still speeds up convergence, and the learning rate is still the knob you tune the most.
Evaluating a Classifier
For regression we judged the fit with R². That metric makes no sense for classes, so classification has its own toolbox, built from the confusion matrix: the four ways a binary prediction can land.
| Predicted | Predicted | |
|---|---|---|
| Actual | True Positive (TP) | False Negative (FN) |
| Actual | False Positive (FP) | True Negative (TN) |
From these four counts we derive the core metrics:
| Metric | Formula | Reads as |
|---|---|---|
| Accuracy | share of all predictions that are correct | |
| Precision | of those predicted positive, how many truly are | |
| Recall | of the actual positives, how many we caught | |
| F1 | harmonic mean of precision and recall |
Accuracy alone is misleading on imbalanced data: if of examples are negative, a model that always predicts scores accuracy while catching zero positives. Precision and recall expose that. They also trade off against each other through the threshold: raising it lifts precision but lowers recall, and vice versa. F1 balances the two in a single number.
To judge the model across all thresholds at once, plot the ROC curve (true-positive rate vs false-positive rate) and report the AUC, the area under it. AUC ranges from (random guessing) to (perfect ranking), and unlike accuracy it does not depend on a single threshold choice.
Beyond Two Classes: Multiclass
Just as multivariate regression generalized univariate to many features, logistic regression generalizes from two classes to many. Logistic regression is binary by nature, so the common trick is to break a -class problem into many binary problems and combine their answers. Two strategies do this:
- One-vs-All (OvA), also called one-vs-rest: train one binary classifier per class, each asking “this class vs everyone else”. To predict, run all classifiers and pick the class whose classifier returns the highest probability.
- One-vs-One (OvO): train one binary classifier per pair of classes, each asking “class vs class ” using only the data of those two. That is classifiers. To predict, every classifier votes for one of its two classes, and the class with the most votes wins.
| Strategy | Classifiers | Decision rule | Trade-off |
|---|---|---|---|
| OvA | highest probability | fewest models; each trains on the full, imbalanced set | |
| OvO | majority vote | many models, but each trains on a small balanced pair |
With classes, OvA trains classifiers, OvO trains . OvO grows quadratically, so it builds more models, but each one sees only two classes worth of data, which helps when training cost grows fast with dataset size. Both collapse to plain binary logistic regression at : a single classifier either way.
References
Related
How I built a speech emotion recognition model in Python — parsing MFCC voice features, pruning them with mutual information, and benchmarking five classifiers (logistic regression, naïve Bayes, KNN, decision tree, MLP) in scikit-learn against WEKA.
How I predicted California house prices with linear regression trained by gradient descent (SGDRegressor) — mutual-information feature selection, a scaling gotcha that breaks SGD, and an honest benchmark against KNN, a decision tree, and WEKA.
What is multivariate (multiple) linear regression? Learn how this ML algorithm fits a hyperplane with one weight per feature plus a bias to predict values from many inputs.
Get new posts by email
No hype, unsubscribe anytime. · Powered by Buttondown