Logistic Regression Explained: How It Works, With a Python Example
On this page
Short answer: Logistic regression is a classification algorithm that predicts the probability that an example belongs to a class, such as “will this customer churn?”. It computes a weighted sum of the features, then passes it through the sigmoid function to squeeze the result between 0 and 1. A threshold (0.5 by default, but tunable) turns the probability into a yes/no decision. It’s fast, interpretable and a strong baseline for binary classification.
Key takeaways
- Despite the name, it’s used for classification.
- Output is a probability; you choose the decision threshold.
- Coefficients are interpretable as changes in log-odds.
- Scale features and use regularisation.
How it works
- Compute a score:
z = b0 + b1·x1 + b2·x2 + … - Convert to probability with the sigmoid:
p = 1 / (1 + e^(−z)) - Predict class 1 if
p ≥ threshold, otherwise class 0 - Training finds coefficients that minimise log loss (cross-entropy)
A large positive z gives a probability near 1; a large negative z gives a probability near 0.
Python example
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, roc_auc_score
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
model = make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=1000))
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print('ROC-AUC:', roc_auc_score(y_test, proba))
print(classification_report(y_test, (proba >= 0.5).astype(int)))
Interpreting coefficients
- A positive coefficient increases the probability of class 1; a negative one decreases it
exp(coefficient)is the odds ratio: how the odds multiply for a one-unit increase in that feature (holding others constant)- With scaled features, coefficient size roughly indicates relative influence
import numpy as np, pandas as pd
clf = model.named_steps['logisticregression']
pd.Series(np.exp(clf.coef_[0]), index=X.columns).sort_values(ascending=False)
Choosing the threshold
0.5 isn’t always right. For fraud or disease detection, you may lower the threshold to catch more positives (higher recall, more false alarms). For costly interventions, you may raise it (higher precision). Choose it based on business costs; see how to evaluate a machine learning model.
Regularisation
- L2 (Ridge): default in scikit-learn; shrinks coefficients
- L1 (Lasso): can shrink some coefficients to zero (feature selection); use
solver='liblinear'or'saga' - C is the inverse of regularisation strength: smaller C = stronger regularisation
Multi-class logistic regression
For more than two classes, scikit-learn fits a multinomial (softmax) model with suitable solvers, returning a probability for each class.
Assumptions and limitations
- Assumes a roughly linear relationship between features and log-odds
- Struggles with complex non-linear patterns unless you engineer features
- Sensitive to highly correlated features (multicollinearity) when interpreting coefficients
- Needs enough examples of each class; handle imbalance with
class_weight='balanced'or threshold tuning
Logistic regression vs other classifiers
| Model | Strength | Trade-off |
|---|---|---|
| Logistic regression | Fast, interpretable, good probabilities | Linear decision boundary |
| Random forest | Captures non-linearity, little tuning | Less interpretable |
| XGBoost | Often highest accuracy on tabular data | More tuning, less transparent |
Frequently asked questions
Why is it called regression if it classifies?
It regresses the log-odds of the outcome on the features (a linear model), then converts that into a probability for classification.
Do I need to scale features?
It’s strongly recommended, especially with regularisation, so all features are penalised fairly and the solver converges.
Is logistic regression still used in industry?
Yes, widely, especially where interpretability matters, such as credit risk and healthcare, and as a baseline.
Is it asked in interviews?
Very often. See machine learning interview questions.
Conclusion
With logistic regression explained, the core idea is a linear score turned into a probability by the sigmoid, with a threshold you choose for the business. Scale features, regularise, tune the threshold and interpret odds ratios, and you have a fast, trustworthy baseline for any binary classification problem.
Practise classification models hands-on in our Machine Learning course.
Related reading
- Gradient descent explained: how models learn
- Regression vs classification
- Naive Bayes explained: a fast text classifier
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.