Logistic Regression in Python, Step by Step

Logistic Regression in Python, Step by Step – DataScienceWay tutorial

Despite its name, logistic regression is a classification model. It predicts the probability that something belongs to a class – a customer will churn, a transaction is fraudulent, a tumour is malignant – and then turns that probability into a yes/no decision. It is quick to train, works well on many tabular problems, and, crucially, its predictions can be explained. That combination makes it a standard first model and a strong baseline.

This step-by-step tutorial builds a logistic regression in Python with scikit-learn: the intuition, preparing mixed numeric and categorical data, training inside a pipeline, evaluating properly, interpreting coefficients as odds ratios, tuning regularisation and handling imbalanced classes. All code runs without downloads.

The intuition

Linear regression (see Linear Regression in Python) produces any number from minus to plus infinity. For a probability we need something between 0 and 1. Logistic regression computes a linear score in the same way, then passes it through the sigmoid (logistic) function:

S-shaped sigmoid curve mapping a linear score from minus 8 to 8 onto a probability between 0 and 1, passing through 0.5 at a score of zero
The logistic (sigmoid) function behind logistic regression.
score       = b0 + b1·x1 + b2·x2 + ... + bn·xn
probability = 1 / (1 + e^(−score))
import numpy as np

def sigmoid(z):
    return 1 / (1 + np.exp(-z))

for z in [-4, -2, 0, 2, 4]:
    print(z, round(sigmoid(z), 3))

A score of 0 gives a probability of 0.5; large positive scores approach 1 and large negative scores approach 0. The model learns coefficients that make the predicted probabilities match the observed outcomes as closely as possible (by maximising the likelihood).

Step 1: Create a realistic dataset

We will simulate a customer-churn dataset, so we know the true relationships and can check the model recovers them sensibly. In a real project you would load your own data instead.

import pandas as pd

rng = np.random.default_rng(42)
n = 3000
df = pd.DataFrame({
    "tenure_months": rng.integers(1, 72, n),
    "monthly_fee": rng.normal(35, 10, n).clip(10, 80).round(2),
    "support_calls": rng.poisson(1.5, n),
    "contract": rng.choice(["Monthly", "Annual", "Two-year"], n, p=[0.5, 0.3, 0.2]),
    "paperless": rng.choice(["Yes", "No"], n),
})
true_score = (-1.0 - 0.04 * df["tenure_months"] + 0.03 * df["monthly_fee"]
              + 0.45 * df["support_calls"]
              + df["contract"].map({"Monthly": 1.0, "Annual": -0.5, "Two-year": -1.5}))
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-true_score))).astype(int)

print(df.head())
print("Churn rate:", round(df["churned"].mean(), 3))

By construction, churn is more likely with short tenure, higher fees, more support calls and monthly contracts. The overall churn rate is the baseline: a model that always predicts “no churn” would be right for every non-churner.

Step 2: Split the data

from sklearn.model_selection import train_test_split

features = ["tenure_months", "monthly_fee", "support_calls", "contract", "paperless"]
X_train, X_test, y_train, y_test = train_test_split(
    df[features], df["churned"], test_size=0.25, random_state=0, stratify=df["churned"])
print(X_train.shape, X_test.shape)

stratify keeps the churn rate equal in both sets. Why this matters is covered in Train/Test Split Explained.

Step 3: Build a preprocessing and model pipeline

Logistic regression needs numeric inputs, and it works best when numeric features are on similar scales (because of regularisation, explained below). A pipeline scales numeric columns, one-hot encodes categories and fits the model, learning everything from training data only:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression

numeric = ["tenure_months", "monthly_fee", "support_calls"]
categorical = ["contract", "paperless"]

pre = ColumnTransformer([
    ("num", StandardScaler(), numeric),
    ("cat", OneHotEncoder(drop="first", handle_unknown="ignore"), categorical),
])
clf = Pipeline([
    ("pre", pre),
    ("model", LogisticRegression(max_iter=1000)),
])
clf.fit(X_train, y_train)
print("Test accuracy:", round(clf.score(X_test, y_test), 3))

drop="first" drops one category per feature to act as the reference level, which makes coefficients easier to interpret. handle_unknown="ignore" stops the model crashing if a new category appears later.

Step 4: Evaluate beyond accuracy

from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score

pred = clf.predict(X_test)
proba = clf.predict_proba(X_test)[:, 1]

print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, digits=3))
print("ROC AUC:", round(roc_auc_score(y_test, proba), 3))
print("Baseline accuracy (always 'no churn'):", round(1 - y_test.mean(), 3))

Compare accuracy with the baseline, then look at recall for the churn class: how many churners did the model actually catch? If you are unsure what these numbers mean, read Classification Metrics Explained.

ROC curve for a logistic regression on a generated imbalanced dataset, with an area under the curve of 0.79, compared with a diagonal random-guessing line
Computed on a generated dataset (2,000 rows, 20% positive) like the one built in this post.

Step 5: Interpret coefficients as odds ratios

Each coefficient is the change in the log-odds of churning for a one-unit increase in the feature. Exponentiating gives an odds ratio, which is easier to explain:

names = clf.named_steps["pre"].get_feature_names_out()
coefs = clf.named_steps["model"].coef_[0]
table = pd.DataFrame({"feature": names, "coef": coefs, "odds_ratio": np.exp(coefs)})
print(table.sort_values("coef").round(3).to_string(index=False))
  • An odds ratio above 1 increases the odds of churn; below 1 decreases them.
  • Numeric features were standardised, so their odds ratios refer to a one standard deviation increase, not one month or one pound.
  • Category coefficients are relative to the dropped reference level. With drop="first", categories are sorted alphabetically, so the reference contract is “Annual”: a coefficient for “Monthly” compares monthly with annual contracts.

The signs should match how we built the data: tenure negative, fees and support calls positive, monthly contracts positive and two-year contracts negative relative to annual. The paperless feature has no effect at all in our simulation, yet it still gets a small non-zero coefficient: random noise always produces some estimated effect, which is why small coefficients should not be over-interpreted. As always, coefficients show associations in the data, not proof of cause and effect.

Step 6: Choose a decision threshold

predict() uses a 0.5 probability threshold. For churn, missing a churner may cost more than contacting a loyal customer, so a lower threshold might be better:

from sklearn.metrics import precision_score, recall_score

for t in [0.3, 0.4, 0.5, 0.6]:
    p = (proba >= t).astype(int)
    print(f"threshold {t}: precision={precision_score(y_test, p):.3f} "
          f"recall={recall_score(y_test, p):.3f} flagged={p.sum()}")

Pick the threshold based on the costs and capacity of the action – for example, how many customers the retention team can call each month – and do so on validation data rather than the final test set.

Step 7: Tune regularisation

scikit-learn applies L2 regularisation by default, which shrinks coefficients to reduce overfitting. The strength is controlled by C: smaller C means stronger regularisation. Tune it with cross-validated grid search:

from sklearn.model_selection import GridSearchCV

grid = GridSearchCV(clf, {"model__C": [0.01, 0.1, 1, 10]}, cv=5, scoring="roc_auc")
grid.fit(X_train, y_train)
print("Best C:", grid.best_params_["model__C"], "CV AUC:", round(grid.best_score_, 3))
print("Test AUC:", round(roc_auc_score(y_test, grid.predict_proba(X_test)[:, 1]), 3))

The model__C syntax targets the C parameter of the pipeline step named model. Cross-validation is covered in Cross-Validation: A Practical Guide.

Step 8: Imbalanced classes

If the positive class is rare, the model may rarely predict it. Two common remedies are adjusting the threshold (Step 6) and weighting classes:

balanced = Pipeline([("pre", pre), ("model", LogisticRegression(max_iter=1000, class_weight="balanced"))])
balanced.fit(X_train, y_train)
print(classification_report(y_test, balanced.predict(X_test), digits=3))

class_weight="balanced" makes errors on the minority class count more during training. It typically increases recall for that class at the expense of precision. Note that it also shifts predicted probabilities, so they should no longer be read as calibrated real-world probabilities.

Common mistakes

  • Not scaling features, which makes regularisation penalise features unevenly and can stop the solver converging (the “ConvergenceWarning”).
  • Label-encoding categories as 1, 2, 3 instead of one-hot encoding.
  • Judging by accuracy alone on imbalanced data.
  • Interpreting standardised coefficients as per-unit effects.
  • Forgetting the reference category when explaining one-hot coefficients.
  • Assuming linearity on the log-odds scale without checking; strongly non-linear effects may need binning or extra features (see Feature Engineering Basics).

FAQ

Can logistic regression handle more than two classes?

Yes. scikit-learn’s LogisticRegression supports multiclass problems automatically, using a multinomial formulation with the default solver.

Why do I get a ConvergenceWarning?

The solver did not finish within the iteration limit. Scale your features and/or increase max_iter.

How do I get p-values?

Use statsmodels (sm.Logit), which reports standard errors and p-values. scikit-learn focuses on prediction and applies regularisation by default.

When should I use a more complex model?

When a well-tuned logistic regression clearly underperforms and interpretability is less important. Tree-based models such as gradient boosting often capture non-linear patterns better. Always compare against the logistic baseline.

Next steps

Strengthen your evaluation with cross-validation and classification metrics, and improve inputs with feature engineering.

LJ

About the author: Lucky Joseph

Lucky is a UK-based writer with a data science background who runs DataScienceWay. Every tutorial is tested before publication; if you spot something that no longer works, please get in touch.

More about DataScienceWay · Contact