🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Logistic Regression: Log-Odds, Odds Ratios, Metrics

StatisticsClassificationđŸŸĸ Free Lesson

Why a straight line cannot be a probability

Linear regression applied to a zero-or-one outcome produces fitted values that can fall below zero or above one, which are impossible as probabilities, and the errors are necessarily non-normal with variance that depends on the fitted level. The workaround that actually works is to stop modelling the probability directly and instead model a transformation of it that is unbounded. Feed the linear predictor through the logistic function and you get a curve that is steep near the centre, flat at both ends, and always strictly between zero and one.

The consequence is a model that is linear where it needs to be and nonlinear where reality is. Probabilities change slowly when the predictor is already extreme — moving a near-certain event even closer to certainty is hard — and fastest around the fifty percent mark. This S-shape is also the reason logistic regression cannot be fit by least squares: there is no closed-form solution, so the coefficients are obtained by maximising a likelihood numerically.

The logit link and what linearity means now

The model states that the log-odds of success — the logarithm of the probability divided by one minus the probability — equals a linear combination of the predictors. The logit transformation maps the unit interval onto the whole real line, so an unrestricted linear predictor is always permissible on that scale. Linearity is claimed for the log-odds, not for the probability, and forgetting which scale is which is the most frequent source of misinterpretation.

The odds themselves have a plain reading: the probability of success divided by the probability of failure. Odds of one mean a coin flip, odds above one mean success is more likely than not, odds of three mean three chances of success for every one of failure. Because the logit is the logarithm of odds, exponentiating a coefficient turns it back into a multiplicative effect on odds, which is the quantity you report to a clinical or business audience.

MetricFormulaOptimise when
AccuracyCorrect predictions over all predictionsClasses are balanced and errors cost the same
PrecisionTrue positives over predicted positivesFalse alarms are expensive
RecallTrue positives over actual positivesMisses are expensive
F1 scoreHarmonic mean of precision and recallYou need one number balancing both
AUCProbability a random positive outranks a random negativeYou want threshold-independent ranking quality

Odds ratios: the interpretable output

Exponentiating a logistic coefficient gives the odds ratio for a one-unit increase in that predictor, holding the others fixed. An odds ratio of one point six five means each extra year of age multiplies the odds of the outcome by one point six five — a sixty-five percent increase in odds, not in probability. That distinction matters: the same odds ratio produces a large probability change when the baseline risk is high and a tiny one when the baseline risk is near zero, which is why odds ratios should always be reported alongside a baseline risk or a predicted probability at representative values.

An odds ratio below one indicates a protective factor, and zero point five halving the odds is exactly as strong in the multiplicative sense as two doubling them. Confidence intervals for the odds ratio come from exponentiating the interval for the coefficient, and an interval spanning one corresponds to an interval for the coefficient spanning zero. Categorical predictors are handled with indicator variables, so each level's odds ratio is read against the reference level, and the choice of reference changes the numbers without changing the model.

Fitting by maximum likelihood

Logistic regression is fitted by maximising the likelihood of the observed labels under the model, which for binary outcomes is a product of Bernoulli probabilities. Taking logarithms converts the product into a sum, and because the log-likelihood is smooth and concave, a local maximum is the global maximum. The standard algorithms — Newton-Raphson, iteratively reweighted least squares, and gradient-based optimisers — all converge reliably on datasets of ordinary size.

Maximum likelihood carries through to inference: coefficient standard errors come from the inverse observed information matrix, and Wald tests divide each coefficient by its standard error. Likelihood-ratio tests compare nested models by the difference in log-likelihoods, and they behave better than Wald tests for small samples or separated data. Separation is the degenerate case where a predictor perfectly predicts the outcome, sending the coefficient and its standard error toward infinity; the fix is penalised likelihood, most commonly Firth's correction, or simply more data.

Thresholds, confusion matrices, and the metrics that follow

The model outputs probabilities; a decision rule turns them into labels. The default threshold of zero point five is arbitrary and encodes an implicit assumption that the two error types cost the same and the classes are balanced. Change either assumption and the right threshold moves: a fraud detection system that must catch almost every incident should threshold low and accept more false alarms, while a spam filter for a corporate inbox may prefer the opposite trade.

Every metric in the table above is a function of the confusion matrix, and choosing between them is choosing which error you refuse to tolerate. Accuracy misleads badly when one class dominates: predicting the majority class every time scores ninety-nine percent on a one-percent-positive dataset while catching nothing. Precision answers how much of what the model flagged is real, recall answers how much of what is real the model flagged, and the F1 score balances them by taking the harmonic rather than arithmetic mean, which punishes a model that is strong on only one. AUC summarises ranking quality across every possible threshold, which makes it the right metric when the score will be recalibrated later rather than used at zero point five.

Fitting and evaluating in Python

python
import numpy as np
from scipy.optimize import minimize

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

def fit_logistic(X, y):
    """Maximum likelihood fit via Newton-style optimisation of negative log-likelihood."""
    n, p = X.shape

    def neg_log_lik(beta):
        eta = X @ beta
        return float(np.sum(np.logaddexp(0, eta) - y * eta))

    def grad(beta):
        eta = X @ beta
        return X.T @ (sigmoid(eta) - y)

    start = np.zeros(p)
    res = minimize(neg_log_lik, start, jac=grad, method="BFGS")
    beta = res.x
    p_hat = sigmoid(X @ beta)
    weights = p_hat * (1 - p_hat)
    information = X.T @ (X * weights[:, None])
    se = np.sqrt(np.diag(np.linalg.inv(information)))
    return beta, se, p_hat

rng = np.random.default_rng(13)
n = 400
age = rng.uniform(30, 80, n)
smoker = rng.binomial(1, 0.3, n)
logit = -4.5 + 0.06 * age + 1.1 * smoker
disease = rng.binomial(1, sigmoid(logit))

X = np.column_stack([np.ones(n), age, smoker])
beta, se, p_hat = fit_logistic(X, disease)
for name, b, s in zip(["intercept", "age", "smoker"], beta, se):
    print(f"{name:9s} beta = {b:6.3f}  se = {s:.3f}  "
          f"odds ratio = {np.exp(b):.3f}")

The recovered coefficients sit close to the true values, and exponentiating the age coefficient gives the per-year odds ratio that a clinician can act on. The standard errors come from the observed information matrix, which is the logistic analogue of the inverse cross-product used in least squares.

The second block builds the confusion matrix at several thresholds and computes the metrics that depend on it.

python
import numpy as np

def confusion(y_true, y_pred):
    tp = int(np.sum((y_true == 1) & (y_pred == 1)))
    fp = int(np.sum((y_true == 0) & (y_pred == 1)))
    fn = int(np.sum((y_true == 1) & (y_pred == 0)))
    tn = int(np.sum((y_true == 0) & (y_pred == 0)))
    return tp, fp, fn, tn

def metrics(y_true, y_prob, threshold):
    tp, fp, fn, tn = confusion(y_true, (y_prob >= threshold).astype(int))
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    accuracy = (tp + tn) / len(y_true)
    return accuracy, precision, recall, f1

def auc_roc(y_true, y_prob):
    pos = y_prob[y_true == 1]
    neg = y_prob[y_true == 0]
    comparisons = (pos[:, None] > neg[None, :]).mean()
    ties = (pos[:, None] == neg[None, :]).mean()
    return comparisons + 0.5 * ties

for t in (0.3, 0.5, 0.7):
    acc, prec, rec, f1 = metrics(disease, p_hat, t)
    print(f"threshold {t}: acc={acc:.3f} prec={prec:.3f} "
          f"rec={rec:.3f} f1={f1:.3f}")
print("AUC =", round(auc_roc(disease, p_hat), 3))

Dropping the threshold trades precision for recall, and the printed row makes the exchange visible rather than implicit. The AUC line summarises the model's ranking ability independently of where you finally set the cut-off.

Classification mistakes that hide behind accuracy

Common Mistakes

Reporting accuracy on a heavily imbalanced dataset

Fix: Report precision, recall, F1, and AUC; a majority-class baseline exposes a useless model.

Reading an odds ratio as a change in probability

Fix: It multiplies the odds; translate it into probability at a stated baseline before quoting it.

Keeping the default threshold because it is conventional

Fix: Set the threshold from the relative cost of false positives and false negatives.

Fitting logistic regression with ordinary least squares

Fix: Use maximum likelihood; the sigmoid and log-likelihood are what keep predictions in the unit interval.

Ignoring separation or perfect predictors

Fix: Penalise the likelihood, merge sparse categories, or collect more data before trusting the coefficients.

Comparing two models only by their accuracy

Fix: Compare ROC curves or AUC, and test the difference on held-out predictions.

Logistic regression essentials

Where to go next

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Mathematics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement