Logistic regression
Logistic regression is a linear classification algorithm that maps a weighted sum of input features through the sigmoid function to predict probabilities between 0 and 1. Its parameters are learned via Maximum Likelihood Estimation (minimizing binary cross-entropy loss), yielding an interpretable linear decision boundary and log-odds feature weights.
Study Card: Logistic regression
Direct Answer
Logistic regression is a supervised classification model that predicts the probability of a categorical outcome by passing a linear combination of features through the logistic (sigmoid) function:
Unlike linear regression, which outputs unbounded continuous values, logistic regression models the log-odds linearly and outputs calibrated probabilities in . Parameters are fit by Maximum Likelihood Estimation (equivalently minimizing convex log loss), making it fast, regularized, and interpretable for both binary and multi-class (softmax / multinomial) classification.
Key Terms
- Sigmoid Function: , mapping real-valued logits smoothly into .
- Maximum Likelihood Estimation (MLE): Estimates by maximizing , equivalent to minimizing binary cross-entropy.
- Odds Ratio: The ratio ; increasing feature by one unit multiplies the odds by while holding other features fixed.
- Log-Odds (Logit): , which is linear in the input features.
- Decision Boundary: The hyperplane (corresponding to ) separating the two classes.
Example
Consider predicting customer churn (yes/no) from age and monthly_bill. Suppose the learned weights are 0.1 for age and 0.2 for monthly_bill. Holding age fixed, each 1-unit increase in monthly_bill increases the log-odds of churning by 0.2, multiplying the odds by (a ~22% increase in odds), twice the log-odds effect of a 1-unit increase in age (). The intercept captures the baseline log-odds when all features equal zero (or at the mean when features are standardized).
Code Implementation
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from sklearn.datasets import load_breast_cancer
# Load the breast cancer dataset
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale features to speed up solver convergence and make regularization balanced across features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Fit logistic regression (scikit-learn uses L2 regularization C=1.0 and L-BFGS by default)
model = LogisticRegression(solver='lbfgs', max_iter=1000, random_state=42)
model.fit(X_train_scaled, y_train)
# Predict probabilities and class labels
probabilities = model.predict_proba(X_test_scaled)
predictions = model.predict(X_test_scaled)
# Evaluate the model
accuracy = accuracy_score(y_test, predictions)
classification_rep = classification_report(y_test, predictions)
print(f"Accuracy: {accuracy:.4f}")
print("\nClassification Report:\n", classification_rep)
# Interpret coefficients (note: multicollinearity can split weights across correlated features)
print("\nCoefficients:\n", model.coef_)
feature_importance = np.abs(model.coef_[0])
feature_names = X.columns
feature_importance_dict = dict(zip(feature_names, feature_importance))
sorted_feature_importance = dict(
sorted(feature_importance_dict.items(), key=lambda item: item[1], reverse=True)
)
print(f"\nFeature importance (|coef| on scaled features):\n{sorted_feature_importance}")
Related Concepts
- Linear Regression: Predicts continuous targets via least squares without a sigmoid link; cannot guarantee valid probabilities in and is sensitive to outliers far from the boundary when misapplied to classification.
- Regularization (L1, L2): Crucial to prevent coefficients from diverging toward infinity on linearly separable data and to control variance under collinearity.
- Optimization Solvers: Since logistic regression has no closed-form solution, numerical optimizers like L-BFGS, Newton-Raphson (IRLS), SAGA, or SGD are used.
- Evaluation Metrics: Accuracy can mislead on imbalanced classes; inspect precision, recall, F1, ROC-AUC, PR-AUC, and log loss.
- Multi-class Classification: Generalizes to classes via multinomial (softmax) regression using categorical cross-entropy, or via One-vs-Rest (OvR) binary classifiers.