DEV Community

Cover image for Logistic Regression
saksham780
saksham780

Posted on

Logistic Regression

Logistic Regression: Turning Evidence into a Yes-or-No Answer

Every morning your email app quietly makes a decision about each message: spam or not spam. It doesn't get to say "probably around 37.2 spam-ness." It has to pick a side. But behind that pick, there's usually a probability, something like "I'm 94% sure this is junk."

Logistic regression is one of the simplest and most dependable ways to produce that probability. The name is a bit unfortunate, because it's a classification method, not a way of predicting numbers.

The problem it solves

You have some features describing a case (how many exclamation marks an email has, whether it contains the word "winner", how many links it carries) and a label that's either 0 or 1. You want a model that looks at fresh features and says how likely the label is to be 1.

The obvious first thought is to fit a straight line and call anything above 0.5 a "yes." It doesn't work well. A straight line happily predicts 1.7 or -0.3, which aren't probabilities, and a few extreme points can tilt the line and wreck your threshold.

So we do something smarter.

Step one: a score

First, combine the features into a single score, using a weight for each:

z = w1*x1 + w2*x2 + ... + b

This score can be any number, big or small, positive or negative. High means "leaning yes", very negative means "leaning no."

Step two: squash it with the sigmoid

Next, pass the score through the sigmoid function:

p = 1 / (1 + e^(-z))

The sigmoid draws an S-shaped curve. Whatever you feed in, what comes out sits strictly between 0 and 1. A score of 0 gives exactly 0.5. A score of +5 gives about 0.993. A score of -5 gives about 0.007. Now you've got something you can honestly call a probability.

Step three: decide

Pick a threshold, most often 0.5, and say "yes" when the probability clears it. That threshold is a choice, not a law of nature. If missing a fraud case is far worse than a false alarm, drop it to 0.2. If false alarms are costly, raise it.

How it learns

At the start, the weights are random and the predictions are junk. Training adjusts them to make the model's probabilities match reality as closely as possible.

The yardstick is log loss, also called binary cross-entropy. Its logic is easy to feel:

  • If the true label is 1 and you said 0.99, the penalty is tiny.
  • If the true label is 1 and you said 0.01, the penalty is enormous. So the model is rewarded for being right, and punished especially hard for being confidently wrong. The weights are then tuned by gradient descent: nudge each weight in whichever direction lowers the loss, repeat thousands of times.

A small example

python

from sklearn.linear_model import LogisticRegression
import numpy as np

features: [exclamation marks, number of links]

X = np.array([[0, 0], [1, 0], [0, 1], [5, 3], [7, 4], [6, 5]])
y = np.array([0, 0, 0, 1, 1, 1]) # 1 = spam

clf = LogisticRegression().fit(X, y)
print(clf.predict_proba([[4, 2]])) # [[P(not spam), P(spam)]]
print(clf.predict([[4, 2]]))

The predict_proba call gives you the probabilities, and predict applies the 0.5 cutoff for you.

Reading the weights

Here's a nice bonus. Each weight, once exponentiated, becomes an odds ratio. If the weight for "number of links" is 0.7, then e^0.7 is about 2.0, which means each extra link roughly doubles the odds of spam, holding the other features steady. That's the kind of sentence you can say in a meeting, which is why this model is still big in medicine, finance and the social sciences.

More than two classes

What if you're sorting emails into "spam", "promotions", "social" and "primary"? Swap the sigmoid for softmax, which converts a set of scores into probabilities that add up to 1. Everything else stays the same.

Things that trip people up

  • Imbalanced data. If 99% of your cases are "no", a model that always says "no" scores 99% accuracy and is utterly useless. Look at precision, recall and the F1 score, and consider class weighting.
  • Accuracy alone is a poor judge. A confusion matrix shows what kinds of mistakes you're making.
  • Features on wildly different scales can slow training. Standardize them.
  • Overfitting with many features. Regularization (the default in most libraries) shrinks the weights and helps.
  • It draws a straight boundary. If the two classes are separated by a curve or a ring, the plain version will struggle unless you engineer extra features.

When it's the right tool

Choose logistic regression for a first, honest baseline, whenever you need calibrated probabilities, or when stakeholders need to understand why the model said what it said. It trains in seconds, and it's often much harder to beat than people expect.

Takeaways

  • It outputs a probability between 0 and 1.
  • The sigmoid (or softmax) does the squashing.
  • Log loss punishes confident mistakes.
  • You choose the threshold based on the cost of each kind of error.
  • Weights translate into odds ratios you can explain.

Top comments (0)