Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 1 of 9

Logistic Regression: Sigmoid Mathematics, Log-Odds & Probability Calibration

Despite its historical name, Logistic Regression is the industry-standard parametric binary and multinomial classification algorithm. It maps linear combinations of features z = w^T x + b into bounded probabilities P(y=1|x) using the non-linear Sigmoid activation function: σ(z) = 1 / (1 + e^(-z)). The model optimizes the log-odds (logit): ln(p / (1 - p)) = w^T x, minimizing Cross-Entropy (Log-Loss) via gradient-based optimization.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Mathematical Log-Odds Derivation & Scikit-Learn Training

Mathematical Log-Odds Derivation & Scikit-Learn Training
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.metrics import log_loss, roc_auc_score, brier_score_loss

# Synthetic medical risk dataset
np.random.seed(42)
n = 1000
age = np.random.uniform(20, 80, n)
cholesterol = np.random.normal(200, 35, n)
blood_pressure = np.random.normal(125, 15, n)

# Ground truth log-odds equation
z = 0.05 * age + 0.015 * cholesterol + 0.04 * blood_pressure - 9.5
probs = 1.0 / (1.0 + np.exp(-z))
y = (probs > np.random.uniform(0, 1, n)).astype(int)

df = pd.DataFrame({'age': age, 'cholesterol': cholesterol, 'blood_pressure': blood_pressure})

# Standardized Logistic Regression Pipeline
pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('clf', LogisticRegression(C=1.0, solver='lbfgs', random_state=42))
])
pipe.fit(df, y)

# Inspect weights and Odds Ratios: OR = exp(w_j)
scaler = pipe.named_steps['scaler']
clf = pipe.named_steps['clf']

for feat, coef in zip(df.columns, clf.coef_[0]):
    odds_ratio = np.exp(coef)
    print(f"Feature: {feat:16s} | Standardized Weight: {coef:+.4f} | Odds Ratio: {odds_ratio:.4f}")
    print(f"  -> A 1-std increase in {feat} multiplies odds of disease by {odds_ratio:.2f}x")

# Output calibrated probabilities
pred_probs = pipe.predict_proba(df)[:, 1]
print(f"\nModel Log-Loss    : {log_loss(y, pred_probs):.4f}")
print(f"ROC-AUC Score     : {roc_auc_score(y, pred_probs):.4f}")
print(f"Brier Loss Score  : {brier_score_loss(y, pred_probs):.4f} (lower is better calibrated)")

Pro Tip: Multinomial Classification with `multi_class='multinomial'`

For multi-class targets (3+ classes), default to `LogisticRegression(multi_class='multinomial')` instead of One-vs-Rest (OvR). The multinomial formulation optimizes true Softmax cross-entropy, producing globally normalized probabilities where `sum(P(y=k)) = 1.0`.

Diagram
Loading diagram…

MlLogisticRegression Visual Representation

Hands-On Challenge: Build a Manual Sigmoid Gradient Descent

Write a pure NumPy logistic regression optimizer: Initialize weights w to zero, compute predicted probabilities `p = 1 / (1 + exp(-Xw))`, compute the gradient `grad = (1/n) * X^T (p - y)`, and update weights via gradient descent across 500 iterations.

Quick Quiz & Key Concept Checks

Common Pitfall: Thresholding at 0.5 on Imbalanced Datasets

A default threshold of 0.5 is optimal only when class distributions are 50:50 and the business cost of a false positive equals a false negative. In imbalanced fraud detection (e.g. 1% fraud), the optimal threshold is often between 0.05 and 0.20.

Finished this lesson?

0 of 9 in Module 6
Sign in to save progress

Topics in This Module

0/9 done