Skip to content
E
Educatum

Logistic regression

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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:

p^(y=1∣x)=σ(wTx+b)=11+e−(wTx+b),log⁡(p^1−p^)=wTx+b\hat{p}(y = 1 \mid x) = \sigma(w^T x + b) = \frac{1}{1 + e^{-(w^T x + b)}}, \qquad \log\left(\frac{\hat{p}}{1 - \hat{p}}\right) = w^T x + b

Unlike linear regression, which outputs unbounded continuous values, logistic regression models the log-odds linearly and outputs calibrated probabilities in (0,1)(0, 1). Parameters (w,b)(w, b) 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: σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}, mapping real-valued logits z∈Rz \in \mathbb{R} smoothly into (0,1)(0, 1).
  • Maximum Likelihood Estimation (MLE): Estimates (w,b)(w, b) by maximizing ∏ip^iyi(1−p^i)1−yi\prod_i \hat{p}_i^{y_i}(1-\hat{p}_i)^{1-y_i}, equivalent to minimizing binary cross-entropy.
  • Odds Ratio: The ratio p^1−p^\frac{\hat{p}}{1-\hat{p}}; increasing feature xjx_j by one unit multiplies the odds by ewje^{w_j} while holding other features fixed.
  • Log-Odds (Logit): log⁡(p^1−p^)=wTx+b\log\left(\frac{\hat{p}}{1 - \hat{p}}\right) = w^T x + b, which is linear in the input features.
  • Decision Boundary: The hyperplane wTx+b=0w^T x + b = 0 (corresponding to p^=0.5\hat{p} = 0.5) 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 e0.2≈1.22e^{0.2} \approx 1.22 (a ~22% increase in odds), twice the log-odds effect of a 1-unit increase in age (e0.1≈1.11e^{0.1} \approx 1.11). The intercept bb 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}")
  • Linear Regression: Predicts continuous targets via least squares without a sigmoid link; cannot guarantee valid probabilities in [0,1][0, 1] 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 KK classes via multinomial (softmax) regression using categorical cross-entropy, or via One-vs-Rest (OvR) binary classifiers.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.