Logistic regression

Turn a weighted sum of the inputs into a probability, and use a threshold to choose a class.

Lesson 26 of 6614 minIntermediate

You will learn to

  • Explain how logistic regression turns inputs into a probability and then into a class
  • Describe the effect of the regularization strength C and of the decision threshold
  • Say when logistic regression is a good first choice for classification

Before this lesson

Intuition

Linear regression predicts a number. For a yes-or-no question we need a probability between 0 and 1, and a straight line does not stay between 0 and 1. Logistic regression keeps the same idea, a weighted sum of the inputs, and then squeezes the result through an S-shaped curve so that it always lands between 0 and 1.

Think of the weighted sum as a score. Rows with a high score are very likely to be positive, rows with a very negative score are very likely to be negative, and rows near zero are a toss-up. The S-shaped curve (the sigmoid) turns that score into a probability.

To get a class you apply a threshold. By default the class is positive when the probability is above 0.5, but the threshold is a business choice: if missing a positive is expensive, lower it. Despite the word "regression" in its name, logistic regression is a classifier.

Picture it

Threshold 0.510z = -1: p = 0.27z = 0: p = 0.50z = 2: p = 0.88Linear score zProbability of the positive class
The sigmoid maps any score to a probability. A score of 0 gives 0.5, large positive scores approach 1 and large negative scores approach 0.

The curve is steepest around zero: that is where a small change in the inputs changes the prediction most. Far from zero it flattens, so very confident predictions move little. The boundary between the two classes is the set of rows where the score is exactly zero. Because the score is linear in the inputs, that boundary is a straight line, or a flat plane with more inputs.

The math

The score is the same weighted sum as in linear regression, and the sigmoid turns it into a probability:

z=b+w1x1+⋯+wpxp,P(y=1∣x)=11+e−zz = b + w_1 x_1 + \dots + w_p x_p, \qquad P(y=1 \mid x) = \frac{1}{1 + e^{-z}}

Here bb is the intercept and wjw_j are the weights. Rearranging shows what the weights mean. The odds of the positive class are p/(1−p)=ezp / (1-p) = e^{z}. Adding 1 to input xjx_j multiplies the odds by ewje^{w_j}.

The weights are chosen to make the training labels as likely as possible, which is the same as minimising the log loss (cross-entropy):

−1n∑i=1n[yiln⁡pi+(1−yi)ln⁡(1−pi)]-\frac{1}{n}\sum_{i=1}^{n}\Big[y_i \ln p_i + (1-y_i)\ln(1-p_i)\Big]

where yiy_i is 1 or 0 and pip_i is the predicted probability. A confident wrong answer costs a lot: predicting 0.01 for a row that is positive costs −ln⁡0.01≈4.6-\ln 0.01 \approx 4.6. See Loss functions.

To limit overfitting, a penalty on the size of the weights is added to the loss. The strength is controlled by CC, which is the inverse of the penalty strength: small CC means strong regularization. See Regularization.

Worked example

These weights are illustrative, not fitted. Suppose a model for churn uses one input, the number of support calls xx, with b=−3b = -3 and w=0.5w = 0.5, so z=−3+0.5 xz = -3 + 0.5\,x.

Support calls xScore zProbability of churnClass at threshold 0.5
4-11 / (1 + e^1) = 0.27stay
600.50on the boundary
1021 / (1 + e^-2) = 0.88churn

The weight 0.5 means that each extra call multiplies the odds of churn by e^0.5, about 1.65. The boundary sits at x = 6, where z = 0.

Log loss shows why the model punishes confidence. If the customer with x = 4 actually churned, the loss is -ln(0.27) = 1.31. If the customer with x = 10 churned, the loss is -ln(0.88) = 0.13.

Now a computed reference. On a sample dataset with 768 rows (35% positive), always predicting the majority class gives an accuracy of 0.65. Logistic regression with a standard scaler, scored with 5-fold stratified cross-validation in scikit-learn (seed 42), reaches an accuracy of 0.775. It is a strong baseline for very little work, and nearly the same without scaling (0.771) because the default penalty is mild; scaling matters more as you raise the penalty or add many columns.

How mlflow does it

The classification algorithm is Logistic Regression (lr). It trains with up to 1,000 iterations, and the parameters you can tune are C (searched between 0.001 and 10) and class_weight (balanced or none). The Ridge Classifier (ridge) is a related linear model with an L2 penalty that does not produce probabilities directly. The other metrics, such as the ROC curve and calibration, work on the probabilities. Put a scaler step before logistic regression and encode categorical columns first.

Common mistakes

  • Treating the 0.5 threshold as fixed. It is only a default. With imbalanced classes or unequal costs, move the threshold using the precision-recall trade-off.
  • Skipping the scaler when you penalise the weights. The penalty is not scale free. Scale the inputs so one column does not get a lighter penalty by accident.
  • Reading probabilities as perfectly calibrated. They are often decent but can be off, especially with a strong penalty. Check a calibration plot before using them as risks.
  • Expecting a curved boundary. The boundary is a straight line. If the classes are not linearly separable, add interaction features or try trees or kernels.
  • Reading a big weight as an important feature. Weights depend on the scale of the column. Compare standardised weights or use permutation importance.

Try it in mlflow

Train logistic regression as a baseline

  1. Open Pipelines and pick a classification pipeline (the Churn prediction use case works).
  2. In the Columns part choose Standardise for the numeric columns, then open the Models part and add Logistic Regression.
  3. Click Train 1 algorithm and open the run.
  4. Note the cross-validated AUC and accuracy. Every more complex model you try later must beat these numbers.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A logistic regression model gives a row a linear score z of 0. What probability does it assign to the positive class?
  2. 2. In scikit-learn style logistic regression, what does lowering C do?
  3. 3. Why is logistic regression a good first model for a classification problem?