Section 3 · Lesson 1

Logistic regression: predicting probabilities

Model the probability of a yes/no outcome with the sigmoid, scale features in a pipeline and read coefficients as odds ratios.

40 min 2 practice tasks
StatQuest: Logistic Regression by StatQuest with Josh Starmer on YouTube

Classification predicts a category. Here the question is binary: will this visitor convert (1) or not (0)? You could fit a straight line to the 0s and 1s, but it would predict values like −0.2 or 1.3, which are meaningless as probabilities. Logistic regression bends the line so predictions always land between 0 and 1.

The sigmoid

Logistic regression computes a linear score exactly as linear regression does, then squashes it with the sigmoid (logistic) function:

z = b0 + b1*x1 + b2*x2 + ...      # any number from -∞ to +∞
p = 1 / (1 + e^(-z))              # a probability between 0 and 1

A score of 0 maps to p = 0.5, large positive scores approach 1 and large negative scores approach 0. Equivalently, the model is linear in the log-odds: log(p / (1 - p)) = z. The coefficients are found by maximum likelihood, which picks the values that make the observed 0s and 1s most probable.

Probabilities first, labels second

model.predict_proba(X_test)[:, 1]   # P(converted = 1) for each visitor
model.predict(X_test)               # 1 if that probability >= 0.5, else 0

predict_proba returns two columns, P(class 0) and P(class 1), so [:, 1] selects the probability of converting. In ad targeting the probability is usually what you want. You’ll rank visitors by it, compare it with the cost of an impression or choose your own cut-off.

On our test set the average predicted probability is 15.3%, matching the actual conversion rate almost exactly. Logistic regression tends to be well calibrated like this. Yet only 61 of 1,250 test visitors get a probability of 0.5 or more, while 191 actually converted. With a 15% base rate the model is rarely more likely than not to see a conversion, which is why predict looked so timid in the first section. The next lesson moves the threshold.

Scale first, in a pipeline

scikit-learn’s LogisticRegression applies regularization by default (an L2 penalty with C=1.0), which shrinks coefficients toward zero. The penalty only treats features fairly if they’re on comparable scales, and minutes on site and email sign-up (0/1) are not. Standardizing each feature to mean 0 and standard deviation 1 fixes that and helps the solver converge:

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)

A pipeline chains steps into one model. fit learns the scaling from the training data only, and predict_proba applies the same scaling to new rows automatically.

Reading coefficients

With standardized features, each coefficient is the change in log-odds per one standard deviation of the feature, so you can compare their sizes. Exponentiate a coefficient to get an odds ratio: cart_adds_30d has a coefficient of about 0.58, so one standard deviation more cart adds multiplies the odds of converting by e^0.58 ≈ 1.79. days_since_last_visit has the largest negative coefficient: visitors who haven’t been back in a while are much less likely to buy.

One coefficient looks strange. sessions_30d is negative, even though visitors with more sessions convert more often. The reason is that pages_viewed_30d is also in the model, and holding pages fixed, more sessions means fewer pages per session, which is a sign of shallow browsing. Correlated features make individual coefficients tricky, so treat them as descriptions of the model, not as causal effects.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Predicted probabilities

Fit model = make_pipeline(StandardScaler(), LogisticRegression()) on the training data.

  • proba: each test visitor's predicted probability of converting,

model.predict_proba(X_test)[:, 1]

  • mean_proba: the average of proba, rounded to 4 decimals
  • actual_rate: the actual conversion rate in y_test, rounded to 4 decimals
  • n_above_half: how many test visitors have proba >= 0.5

How does n_above_half compare with the number of test visitors who actually converted?

Need a hint?
  1. make_pipeline(...) returns a model with the usual .fit and .predict_proba methods.
  2. (proba >= 0.5) is an array of True/False values, and .sum() counts the Trues.
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)

model = None
proba = None
mean_proba = None
actual_rate = None
n_above_half = None
print(mean_proba, actual_rate, n_above_half)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Read the coefficients

The last step of the pipeline is the logistic regression, model[-1]. Because the features were standardized, each coefficient is the change in log-odds for a one standard deviation increase in that feature, so the coefficients are comparable.

  • coefs: a Series of model[-1].coef_[0] indexed by features
  • top_positive: the name of the feature with the largest coefficient
  • top_negative: the name of the feature with the most negative coefficient
  • odds_ratio_cart: np.exp of the cart_adds_30d coefficient, rounded to 3 decimals
Need a hint?
  1. model[-1] is the LogisticRegression step; its coef_ has shape (1, n_features), so take coef_[0].
  2. coefs.idxmax() returns the index label (the feature name) of the largest value.
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)

coefs = None
top_positive = None
top_negative = None
odds_ratio_cart = None
print(coefs)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status