Summit Stream, a made-up video streaming service in Denver, wanted to know which subscribers are about to cancel. A scikit-learn logistic regression model answers that with a churn probability for each customer, using LogisticRegression inside a pipeline.
from sklearn.linear_model import LogisticRegression
model = LogisticRegression().fit(X_train, y_train)
model.predict_proba(X_new)[:, 1] # probability of class 1 (churn)
In this tutorial, I’ll build that scikit-learn logistic regression churn model step by step, from a CSV of 2,000 customers to probabilities for three new sign-ups.
My Command Prompt printed every score on this page while running Python 3.12.5, scikit-learn 1.9.1 and pandas 3.0.6.
Here’s what we’re building: the finished model scoring three new customers and flagging the one worth a call.

Before You Start: Python, scikit-learn and the Churn Data
You need scikit-learn 1.8 or newer (several logistic regression parameters changed in 1.8), plus pandas and matplotlib. Install them with pip install scikit-learn pandas matplotlib.
If you’re still picking tools, my list of the best Python libraries for data science explains where each one fits.
The sample is a simulated customer table with a fixed seed, so you get the same 2,000 rows I did:
| Column | Type | Notes |
|---|---|---|
plan | text | Basic ($9.99), Standard ($15.49) or Premium ($22.99) |
contract | text | Monthly or Annual |
tenure_months | int | 1-60 months as a customer |
monthly_charge | float | Plan price plus add-ons, in USD |
support_calls | int | Calls to support in the last 90 days |
watch_hours_week | float | Average viewing hours per week |
churned | 0/1 | 1 = canceled (the target) |
Save this as make_data.py and run it once to write customers.csv:
import numpy as np
import pandas as pd
rng = np.random.default_rng(2026)
n = 2000
plan = rng.choice(["Basic", "Standard", "Premium"], n, p=[0.4, 0.4, 0.2])
price = pd.Series(plan).map({"Basic": 9.99, "Standard": 15.49,
"Premium": 22.99})
contract = rng.choice(["Monthly", "Annual"], n, p=[0.6, 0.4])
tenure = rng.integers(1, 61, n)
calls = rng.poisson(1.2, n)
hours = rng.gamma(4, 3, n).round(1)
addons = rng.choice([0, 4.99, 7.99], n, p=[0.6, 0.25, 0.15])
logit = (-1.2 + 1.8 * (contract == "Monthly") - 0.05 * tenure
+ 0.6 * calls + 0.08 * (price + addons - 15) - 0.06 * hours)
churned = rng.random(n) < 1 / (1 + np.exp(-logit))
df = pd.DataFrame({
"customer_id": [f"C{10001 + i}" for i in range(n)],
"plan": plan, "contract": contract, "tenure_months": tenure,
"monthly_charge": (price + addons).round(2),
"support_calls": calls, "watch_hours_week": hours,
"churned": churned.astype(int),
})
df.to_csv("customers.csv", index=False)
print(df.head(3).drop(columns="customer_id").to_string(index=False))
print(f"\n{len(df):,} customers, churn rate {df['churned'].mean():.1%}")
Output:
plan contract tenure_months monthly_charge support_calls watch_hours_week churned
Basic Annual 14 9.99 2 3.6 0
Standard Annual 52 15.49 2 3.9 0
Standard Monthly 34 15.49 1 14.0 0
2,000 customers, churn rate 26.1%
About one customer in four churned, an imbalance that matters in Step 6.
What does logistic regression predict in scikit-learn?
Despite the name, logistic regression is a classifier. It squeezes a weighted sum of the features (the log-odds) through the sigmoid function into a probability:
p(churn) = 1 / (1 + exp(-(b0 + b1*x1 + b2*x2 + ...)))
The “regression” part is that linear sum, the same idea as multiple linear regression in Python. The S-shaped curve itself is covered in my post on the sigmoid function in Python.
predict_proba() returns those probabilities, and predict() turns them into 0 or 1 at a fixed 0.5 cutoff, which we’ll move in Step 6.
Step 1: Load the Customer CSV and Split Train and Test Data
Create churn_model.py. It loads the CSV, separates the features from the target and holds back 25% of the rows for testing:
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("customers.csv")
X = df.drop(columns=["customer_id", "churned"])
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42)
stratify=y keeps the churn rate the same in both parts (without it, a small test set can end up with too few churners). Adding two print lines shows the split:
print("train:", X_train.shape, f"churn {y_train.mean():.1%}")
print("test: ", X_test.shape, f"churn {y_test.mean():.1%}")
Output:
train: (1500, 6) churn 26.1%
test: (500, 6) churn 26.0%

Checkpoint: 1,500 training rows and 500 test rows, each with six feature columns and about 26% churn.
Step 2: Build a Scaling Pipeline Around LogisticRegression
Logistic regression needs numbers on similar scales, and it can’t read text. Append this to churn_model.py:
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
num = ["tenure_months", "monthly_charge", "support_calls",
"watch_hours_week"]
cat = ["plan", "contract"]
prep = ColumnTransformer([
("num", StandardScaler(), num),
("cat", OneHotEncoder(drop="first"), cat),
])
model = make_pipeline(prep, LogisticRegression())
model.fit(X_train, y_train)
StandardScaler centers each number column, and OneHotEncoder(drop="first") turns plan and contract into 0/1 columns (dropping one level avoids a redundant column). The data preprocessing steps in machine learning guide explains both.
The pipeline also keeps test rows out of the scaler. To confirm the settings, print a few attributes:
clf = model[-1]
print("classes:", clf.classes_, "| iterations:", clf.n_iter_[0])
print("C =", clf.C, "| l1_ratio =", clf.l1_ratio, "| solver =", clf.solver)
Output:
classes: [0 1] | iterations: 14
C = 1.0 | l1_ratio = 0.0 | solver = lbfgs

Checkpoint: the lbfgs solver converged in 14 iterations with the defaults C=1.0 and l1_ratio=0.0, which means plain L2 regularization.
Step 3: Score the Model with Accuracy, a Confusion Matrix and a Report
A second script imports the fitted model and scores the 500 test customers in Command Prompt:
from sklearn.metrics import (accuracy_score, classification_report,
confusion_matrix)
from churn_model import X_test, model, y_test
pred = model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, pred):.3f}\n")
print(confusion_matrix(y_test, pred), "\n")
print(classification_report(y_test, pred, digits=3,
target_names=["Stayed", "Churned"]))
Output:
Accuracy: 0.782
[[343 27]
[ 82 48]]
precision recall f1-score support
Stayed 0.807 0.927 0.863 370
Churned 0.640 0.369 0.468 130
accuracy 0.782 500
macro avg 0.724 0.648 0.666 500
weighted avg 0.764 0.782 0.760 500

Accuracy looks fine at 0.782, but read the Churned row: the model finds just 48 of 130 churners. My post on the scikit-learn accuracy_score shows why accuracy flatters imbalanced data like this.
Checkpoint: 343 stayers and 48 churners classified correctly, 82 churners missed.
Step 4: Plot the Logistic Regression Confusion Matrix
ConfusionMatrixDisplay.from_estimator() predicts and plots the same numbers in one call:
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
from churn_model import X_test, model, y_test
ConfusionMatrixDisplay.from_estimator(
model, X_test, y_test, display_labels=["Stayed", "Churned"],
cmap="Blues")
plt.title("Churn model on 500 test customers")
plt.tight_layout()
plt.show()
