Logistic Regression
After this lesson, you will be able to:
- Understand why you cannot use a straight line for yes/no predictions and how the S-shaped sigmoid curve fixes it
- Build the logistic regression model step by step and interpret its output as a probability (like '73% chance of spam')
- Understand binary cross-entropy — the loss function that tells the model how wrong its probability predictions are
- Visualize the decision boundary — the line where the model switches from 'yes' to 'no'
- Know when to choose logistic regression over a decision tree or SVM, and what 'linearly separable' actually means in practice
Before you start
Don't worry if "logistic regression" sounds complicated — it is really just linear regression with one extra step: squishing the output through an S-curve so it becomes a probability between 0% and 100%. That is the whole trick!
#From Lines to S-Curves
#End-to-End: How Logistic Regression Classifies
#Step 1: Input Features
You start with a set of features for each example — hours studied, previous test scores, attendance rate. Each example also has a binary label: pass or fail, spam or not spam, malignant or benign. The goal is to learn a function that maps features to the probability of the positive class.
#Step 2: Linear Combination (wx + b)
#Step 3: Sigmoid Squashes to [0, 1]
The raw score z is passed through the sigmoid function: sigma(z) = 1 / (1 + e^(-z)). This S-shaped curve maps any real number to a value between 0 and 1. Large positive z maps to near 1, large negative z maps to near 0, and z = 0 maps to exactly 0.5. The output is now a valid probability.
#Step 4: Threshold Decision
P(y=1|x) > 0.5, predict the positive class. If P(y=1|x) <= 0.5, predict the negative class. The threshold is a business decision — for cancer screening, you might lower it to 0.3 to catch more true positives at the cost of more false alarms.#Step 5: Classification Output
The model outputs both a probability and a class label. During training, binary cross-entropy loss measures how far the predicted probabilities are from the true labels, and gradient descent adjusts the weights to minimize this loss. The decision boundary, where P = 0.5 — is always a straight line (hyperplane) in feature space.
#The Sigmoid Function
Try it! Open the Python REPL and type these lines yourself. See the sigmoid in action:import numpy as np; sigmoid = lambda z: 1/(1+np.exp(-z)); print(f"sigmoid(-5)={sigmoid(-5):.5f}, sigmoid(0)={sigmoid(0):.1f}, sigmoid(5)={sigmoid(5):.5f}")— watch how it squishes any number into the 0-to-1 range!
Key properties of the sigmoid:
- Range: Always between 0 and 1 (perfect for probabilities)
- Monotonic: Higher input = higher output (preserves ranking)
- Symmetric: sigma(-z) = 1 - sigma(z)
- Differentiable: sigma'(z) = sigma(z)(1 - sigma(z)) — elegant, fast to compute
- Saturation: For |z| > 5, the output is very close to 0 or 1 (the "flat tails")
The slope formula in the last bullet is derived in Linear Regression: Your First Model. The symmetry takes three lines.
#The Logistic Regression Model
Combine a linear function with the sigmoid:
P(y=1|x) > 0.5→ predict class 1P(y=1|x) <= 0.5→ predict class 0
A fair question is why the sigmoid of a straight line is the right shape for a probability. One honest answer: when each class is a bell-shaped cloud and the two clouds share the same shape, Bayes' rule (from the Probability and Bayes' Theorem lesson) produces exactly this model, with no guessing.
For logistic regression with weights w = [2, -3] and bias b = 1, what is the predicted class for input x = [1, 1]?
With w = [2, -3] and x = [1, 1]: z = 2(1) + (-3)(1) + 1 = 0. sigmoid(0) = 0.5. The point is exactly on the decision boundary. In practice, most implementations assign this to class 0 (since P is not strictly greater than 0.5), but the key insight is that z = 0 defines the decision boundary.
#Worked Example: Predicting Exam Pass from Hours Studied
w = 1.2 and bias b = -6. Now plug in real students:| Student | Hours (x) | z = 1.2·x − 6 | σ(z) = P(pass) | Predict |
|---|---|---|---|---|
| Ana | 2 | −3.6 | 0.027 | FAIL (3%) |
| Ben | 4 | −1.2 | 0.231 | FAIL (23%) |
| Cara | 5 | 0.0 | 0.500 | borderline |
| Dev | 6 | 1.2 | 0.769 | PASS (77%) |
| Eli | 8 | 3.6 | 0.973 | PASS (97%) |
#The Decision Boundary
Interactive Lab
Click to add training points and watch the logistic-regression boundary re-fit. Compare it with KNN and SVM on the same data — same problem, very different shapes.
LogisticRegression, draw the learned boundary, and check accuracy on a held-out test set.A logistic regression model on customer-churn data learns weight w_age = +0.20 for age (after standardizing the feature). What does the coefficient mean?
#The Loss Function: Binary Cross-Entropy
Slide the predicted probability toward the wrong answer on the Binary tab and watch cross-entropy climb while squared error flattens. The derivations after the gradient show why in symbols.
#Why Log Loss Works
Consider the two cases:
- True label y = 1: Loss = -log(p_hat). If p_hat is near 1, loss is near 0 (good). If p_hat is near 0, loss goes to infinity (terrible).
- True label y = 0: Loss = -log(1 - p_hat). If p_hat is near 0, loss is near 0 (good). If p_hat is near 1, loss goes to infinity (terrible).
The gradient is beautifully simple:
That the loss is bowl-shaped is the reason gradient descent cannot get lost on this problem. The gradient above is derived in Linear Regression: Your First Model, and the slope of the sigmoid in the same place. What is new here is the curvature, the Hessian from Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules, and the proof that it is never negative.
#The Curvature of the Loss
The same bowl-shape argument fails for squared error. One example is enough to see it.
#Newton's Method and IRLS
Gradient descent uses only the slope. Because the loss is smooth and convex, you can also use the curvature, which turns the slope into a direct jump toward the bottom. The result is Newton's method, and for logistic regression it takes the form of a weighted least-squares problem, which is why it is called iteratively reweighted least squares (IRLS). It usually needs only a handful of steps.
#Multiclass Extension: Softmax Regression
Drag the scores and watch the probabilities. Then switch on the add 100 to every score option: nothing changes in the result, which the second derivation below explains.
The gradient of softmax followed by cross-entropy is derived in Vector & Matrix Calculus: Jacobian, Hessian & Backprop Rules. Two smaller facts about softmax are new here.
In softmax regression with 4 classes, you compute scores z = [2.0, 1.0, 0.1, -1.0]. Without doing the full computation, which class wins, and roughly why?
#Regularization in Logistic Regression
Just like linear regression, logistic regression benefits from regularization:
The penalty strength lambda and scikit-learn's C are two names for the same dial. The link between them depends on how the library writes the objective, so it is worth deriving once. That a squared-weight penalty is a Gaussian prior on the weights is derived in MLE, MAP & Fisher Information.
#Try It Yourself
Tests: Check the printed decision boundary (about 3.7 hours after 200 epochs; the converged fit is 4.73). Check that P(pass|1 hour) is about 0.19 and P(pass|10 hours) about 0.97 after 200 epochs. Modify the learning rate and observe convergence speed.
#When to Use Logistic Regression vs. Alternatives
| Situation | Reach for | Why |
|---|---|---|
| Roughly linear decision boundary, you need explanations | Logistic regression | Coefficients directly explain each feature's effect |
| Boundary is clearly non-linear (rings, spirals) | SVM with RBF kernel or tree ensembles | Logistic regression draws only straight lines |
| Mixed feature types, you don't want to engineer features | Random Forest / Gradient Boosting | Handles non-linearities and interactions automatically |
| Severe class imbalance (1% positives) | Logistic regression with class_weight='balanced' + PR-AUC metric | Plain accuracy is meaningless on imbalanced data |
| You need calibrated probabilities for ranking/risk scoring | Logistic regression (with calibration check) | Among the best-calibrated classifiers by default |
| Tens of millions of samples, billions of feature crosses | SGD logistic regression (Vowpal Wabbit, sklearn SGDClassifier) | Trains in one pass over the data |
#Key Takeaways
- The sigmoid squeezes any number into a probability. By wrapping a linear function in the sigmoid, logistic regression outputs calibrated probabilities between 0 and 1 instead of unbounded predictions
- Cross-entropy is the correct loss for classification. It creates a convex loss surface (guaranteed single global minimum) and catastrophically penalizes confident wrong predictions, driving well-calibrated probabilities
- The decision boundary is always linear. Logistic regression can only separate classes with a straight line/hyperplane; for non-linear boundaries, you need polynomial features, kernels, or neural networks
- Softmax generalizes to multiple classes. For K > 2 classes, softmax computes a probability distribution over all classes, with binary logistic regression as a special case
- Accuracy is misleading for imbalanced classes. With 99% negative examples, always predicting negative gives 99% accuracy but catches nothing; use precision, recall, F1, or AUC instead
#Quick Check
Why is cross-entropy used instead of MSE for logistic regression?
S-shaped curve sigma(z) = 1 / (1 + e^(-z)) that squashes any real number into the range (0, 1), turning a raw score into a probability.
The raw linear score z = w^T x + b, also equal to log(p / (1 - p)). Moving one unit in a feature changes the log-odds by that feature's weight.
The set of inputs where the predicted probability equals the threshold (typically 0.5). For logistic regression this is always a linear hyperplane.
The loss function used for logistic regression: -[y log(p) + (1-y) log(1-p)]. It is convex in the model's weights and heavily penalizes confident wrong predictions.
Multi-class generalization of sigmoid. Takes a vector of scores and normalizes them into a probability distribution over K classes via exp() and division by the sum.
When one class is far more common than others. Accuracy becomes misleading and models tend to ignore the minority class; mitigated with class weights, resampling, or threshold tuning.
How closely predicted probabilities match observed frequencies. A well-calibrated model that says '70% chance' is right about 70% of the time.
Penalty added to the loss (sum of |w| for L1, sum of w^2 for L2) to shrink weights and prevent overfitting. Scikit-learn's C parameter is the inverse of the regularization strength.
Spam Detection at Gmail
Gmail's classic spam pipeline (still a core signal even alongside deep models) uses logistic regression over features like sender reputation, link patterns, and user interaction signals to output a spam probability.
One of the best-known text-classification uses; figures change, so check current sources
Credit Scoring (FICO / Banks)
FICO and most consumer lenders use logistic regression for credit risk scoring because regulators (ECOA, Fair Lending Act) require that every denial be explainable via concrete factor weights.
A standard, explainable choice for consumer credit scorecards
Ad Click Prediction at Meta / Google
Before a click-through-rate model upgrades to deep networks, the production baseline is large-scale logistic regression (often trained on very large numbers of feature crosses) because it serves predictions in microseconds at global scale.
Fast enough to serve predictions in microseconds