Comparison

Linear Regression vs Logistic Regression: Differences

Use linear regression when the answer is a number on a continuous scale: a price, a temperature, a score. Use logistic regression when the answer is a category, such as pass or fail, and you want a probability for it. Both start from the same weighted sum; logistic regression passes it through a sigmoid.

Last updated · By Rohit Ghumare

Linear vs logistic regression at a glance

Linear regressionLogistic regression
TaskRegression: predict a continuous numberClassification: predict a class
Modely = w^T x + bp = \sigma(w^T x + b), where \sigma is the sigmoid
Output rangeAny real numberA probability between 0 and 1
What the output meansThe predicted value itselfP(y = 1 \mid x), the chance the input is in class 1
Loss functionMean squared errorBinary cross-entropy (log loss)
How it is solvedNormal equation in one step, or gradient descentGradient descent; there is no one-step formula
What a weight tells youChange in y when that feature goes up by 1Change in the log-odds when that feature goes up by 1
Decision ruleNoneCompare p with a threshold, usually 0.5
EvaluationMSE, R^2Confusion matrix, precision, recall, F1
GeometryFits a line or plane through the pointsPlaces a line or plane between the classes

When to choose each

Choose linear regression when

  • The target is a quantity and differences between values mean something: 70 is ten more than 60.
  • You want to explain the result in the target's own units: each extra study hour adds about four and a half points.
  • You need a fast baseline. With few features, the normal equation gives the best weights with no iteration and no learning rate.
  • The relationship is roughly a straight line, or becomes one after you add polynomial features.

Choose logistic regression when

  • The target is one of two classes: spam or not, churned or not, malignant or benign.
  • You need a probability, not only a label, so you can set a threshold that fits the cost of each kind of mistake.
  • You want a baseline classifier that trains quickly and whose weights you can read.
  • There are several classes. The softmax version handles them with the same idea.

When neither fits

Both draw straight boundaries. If the pattern is curved, add polynomial features or move to a nonlinear model such as a decision tree or a neural network. If the target is a count, a rank or a time until an event, other models fit better than either one.

Code: one example per side

Both scripts use only the Python standard library. Same input (hours studied), two different questions.

Linear regression: what score will this student get?

python
hours = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
score = [52, 55, 61, 64, 70, 73, 79, 82, 88, 91]

w, b, lr, n = 0.0, 0.0, 0.01, len(hours)
for _ in range(20000):
    pred = [w * x + b for x in hours]
    dw = sum((p - y) * x for p, y, x in zip(pred, score, hours)) / n
    db = sum(p - y for p, y in zip(pred, score)) / n
    w, b = w - lr * dw, b - lr * db

print(f"score = {w:.2f} * hours + {b:.2f}")
print(f"6.5 hours -> {w * 6.5 + b:.1f}")
output
score = 4.45 * hours + 47.00
6.5 hours -> 76.0

Logistic regression: will this student pass?

python
import math

hours = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
passed = [0, 0, 0, 1, 0, 1, 1, 1, 1, 1]


def sigmoid(z):
    return 1 / (1 + math.exp(-z))


w, b, lr, n = 0.0, 0.0, 0.1, len(hours)
for _ in range(20000):
    prob = [sigmoid(w * x + b) for x in hours]
    dw = sum((p - y) * x for p, y, x in zip(prob, passed, hours)) / n
    db = sum(p - y for p, y in zip(prob, passed)) / n
    w, b = w - lr * dw, b - lr * db

print(f"P(pass) = sigmoid({w:.2f} * hours + {b:.2f})")
print(f"6.5 hours -> {sigmoid(w * 6.5 + b):.2f}")
print(f"boundary at {-b / w:.1f} hours")
output
P(pass) = sigmoid(1.30 * hours + -5.82)
6.5 hours -> 0.93
boundary at 4.5 hours

Look at the two training loops. The gradient lines are identical. The only change is that the prediction goes through sigmoid first. That one function is the whole difference between the two models.

Common mistakes

  • Using linear regression on 0 and 1 labels. The outputs leave the 0 to 1 range and a single outlier moves the line for everyone.
  • Using logistic regression to predict a quantity. It models a probability and is used to classify. The "regression" in the name refers to fitting the log-odds as a linear function.
  • Training logistic regression with mean squared error. With a sigmoid in the model, that loss is non-convex. Use cross-entropy.
  • Reading a logistic weight as a change in probability. It is a change in log-odds. The effect on the probability depends on where you are on the S-curve.
  • Judging a classifier by accuracy alone. With 95% of examples in one class, always predicting that class scores 95% and is useless. Check precision and recall.
  • Keeping the 0.5 threshold by habit. Lower it when missing a positive is costly, as in screening. Raise it when a false alarm is costly, as in a spam filter.
  • Skipping feature scaling with gradient descent. Features on very different scales make the same learning rate too large for one weight and too small for another.
  • Expecting a curved boundary. Logistic regression always separates classes with a straight line or flat plane unless you add features.

Frequently asked questions

Is logistic regression a regression or a classification algorithm?

It is used for classification, and it is a regression in the statistical sense: it fits the log-odds as a linear function of the inputs. The logistic function, also called the sigmoid, turns that into a probability between 0 and 1. You get a class by comparing the probability with a threshold, usually 0.5.

Can I use linear regression for classification?

You can fit it to 0 and 1 labels, but the predictions are not probabilities: they fall below 0 and rise above 1. A single extreme point also drags the whole line and shifts every prediction. Logistic regression keeps predictions between 0 and 1, though outliers can still move its boundary, so use it for classes.

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

Mean squared error combined with a sigmoid gives a non-convex cost surface, so gradient descent can stall in a poor spot. Binary cross-entropy is convex for logistic regression, so every local minimum is a global one. It also penalizes confident wrong answers much more heavily than hesitant ones.

What do linear and logistic regression have in common?

Both compute the same weighted sum of the inputs plus a bias, and both are trained with gradient descent using an update of the same form: the average of prediction minus target, times the input. Logistic regression only adds a sigmoid on top of the weighted sum before comparing with the target.

Can logistic regression handle more than two classes?

Yes. Replace the sigmoid with softmax, which turns one score per class into probabilities that sum to 1, and train with categorical cross-entropy. This is often called multinomial or softmax regression. The decision boundaries between classes are still straight lines or flat planes in the input space.

Learn it by building

These free lessons build both models from scratch in Python, Julia and Rust:

  1. Linear Regression: gradient descent, the normal equation, multiple and polynomial regression, and R^2.
  2. Logistic Regression: the sigmoid, cross-entropy, the decision boundary, softmax and threshold tuning.
  3. Model Evaluation: how to measure a regression model and a classifier properly.
  4. Loss Functions: why mean squared error and cross-entropy are the right losses for each task.

More comparisons

All comparisons · All how-to guides · Course catalog