Likelihood, logistic regression and cross entropy

55 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Write a likelihood, and find the maximum likelihood estimate for a rate and for a normal
  • Sum log-likelihoods, and say why a product of many probabilities fails
  • Fit a logistic regression by maximum likelihood, and read its coefficients as odds ratios
  • Show that cross entropy is lowest when the prediction matches the truth, and that its floor is the entropy
  • Turn a language model's loss into perplexity, and name the part of the loss no model removes

Likelihood and cross entropy, the way the coding round asks

An OpenAI coding round asked candidates to use cross entropy to find a distribution's minimum error (1 source). Cross entropy is a likelihood in disguise, so this lesson's practice problem starts there, in three levels:

  1. log_likelihood(p, outcomes) for 0/1 outcomes, safe for 10,000 of them, and normal_mle(xs): the maximum likelihood mean and variance.
  2. sigmoid(z) that never overflows, fit_logistic(columns, y) by Newton's method, and odds_ratio(coefficient).
  3. entropy(p), cross_entropy(p, q) and min_log_loss(labels): the lowest average log loss one constant prediction can reach.
CallReturns
log_likelihood(0.5, [1, 0, 1])−2.079, which is 3 ln 0.5
sigmoid(-1000.0)0.0, with no overflow
odds_ratio(0.9)2.46
cross_entropy([0.5, 0.5], [0.25, 0.75])0.837

The lesson follows the shop's return rate: the likelihood and its logs, maximum likelihood for a normal, logistic regression, then cross entropy, its floor, and a language model's loss. Seven steps end with a small task in the editor.

Part 1 of 7about 8 min
Likelihood

The likelihood scores each rate by how probable it makes the data

An OpenAI coding round asked candidates to use cross entropy to find a distribution's minimum error (1 source). Cross entropy is a likelihood in disguise, so start with the likelihood.

NIST's handbook puts it loosely: the likelihood of a set of data is the probability of getting that data under the chosen model. The parameter values that maximize it are the maximum likelihood estimates, or MLEs. MacKay adds a warning that's worth saying in an interview: it's the likelihood of the parameters, and the likelihood function is not a probability distribution over them.

The shop wants its return rate. If each order comes back with chance p, one particular run of n orders with k returns has probability pk(1−p)n−kp^k (1-p)^{n-k}. Score every rate that way, and keep the best:

import numpy as np

rng = np.random.default_rng(34)
# 5,000 orders, each returned with chance 12%
returned = (rng.random(5_000) < 0.12).astype(int)
k, n = int(returned.sum()), len(returned)
# every rate from 0.0002 to 0.9998
grid = np.arange(1, 5_000) / 5_000


def best_and_range(outcomes):
    m, j = len(outcomes), int(outcomes.sum())
    # the log of p^j (1 - p)^(m - j), at every rate on the grid
    ll = j * np.log(grid) + (m - j) * np.log(1 - grid)
    # rates within 2 log units of the best
    near = grid[ll >= ll.max() - 2]
    return grid[ll.argmax()], near.min(), near.max()


for m in (50, 5_000):
    best, lo, hi = best_and_range(returned[:m])
    print(f"first {m:>5,} orders: best rate {best:.4f}, good rates {lo:.3f} to {hi:.3f}")
Predict

The first 50 orders and all 5,000 give similar best rates. What happens to the range of good rates?

Pick one to see what it prints.
Pick an answer above to see the rest

Add logs instead of multiplying chances

A product of thousands of chances runs into a problem.

Predict

Multiply the 5,000 orders' chances at the best rate in float64. What comes out?

Pick an answer above to see the rest
Part 1 done
Part 2 of 7about 7 min
Maximum likelihood estimates

For a normal, maximum likelihood gives the sample mean, and a variance with a catch

The same recipe works for any model with a density. Delivery times look normal, and a normal's log-likelihood is a sum over the days of a term that depends on the mean and the variance. Here's a search over the variance, with the mean at the sample mean:

# 8 delivery times, in days
days = rng.normal(4.0, 1.2, 8).round(1)


def normal_log_likelihood(mu, var, xs):
    return np.sum(-0.5 * np.log(2 * np.pi * var) - (xs - mu) ** 2 / (2 * var))


# 0.0001 to 5
variances = np.arange(1, 50_001) / 10_000
best = variances[np.argmax([normal_log_likelihood(days.mean(), v, days) for v in variances])]
print(f"best variance {best:.3f}; over n {days.var():.3f}; over n - 1 {days.var(ddof=1):.3f}")
Predict

Which variance makes the 8 delivery times most likely?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

What's the maximum likelihood estimate of the standard deviation?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 13 min
Logistic regression

Logistic regression is maximum likelihood for a 0/1 outcome

The shop also knows, for each order, whether it was bought in a sale and how far its size ran from what the customer usually buys. It wants the chance of a return from those.

Predict

Fit the linear regression lesson's straight line to the 0/1 returns. What goes wrong?

Pick an answer above to see the rest

Newton's method fits it, and each coefficient moves the log odds

Penn State's course notes spell out what that means: the log of the odds, p / (1 − p), is a linear function of the x's. They add that maximizing the likelihood has no closed-form solution, so an iterative method such as reweighted least squares finds it. Newton's method below is that method. Each step uses the curvature and the gradient of the log-likelihood, Xᵀ(y − p). The negative log-likelihood's gradient is the same with the sign flipped, Xᵀ(p − y).

# bought in a sale
sale = (rng.random(n) < 0.3).astype(float)
# how far the size ran from the customer's usual
size_gap = rng.normal(0, 1, n)
chance = 1 / (1 + np.exp(-(-2.2 + 0.7 * sale + 0.9 * size_gap)))
y = (rng.random(n) < chance).astype(float)


def fit_logistic(columns, y, steps=25):
    """Maximum likelihood by Newton's method: the intercept, then one coefficient per column."""
    X = np.column_stack([np.ones(len(y))] + list(columns))
    w = np.zeros(X.shape[1])
    for _ in range(steps):
        p = 1 / (1 + np.exp(-(X @ w)))
        w += np.linalg.solve(X.T @ (X * (p * (1 - p))[:, None]), X.T @ (y - p))
    return w


w = fit_logistic([sale, size_gap], y)
print(f"intercept {w[0]:.2f}, sale {w[1]:.2f}, size gap {w[2]:.2f}")
print(f"e to the sale coefficient: {np.exp(w[1]):.2f}")
Predict

The simulation's true sale coefficient is 0.7. What does a sale do to a return?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 9 min
Cross entropy

Log loss is cross entropy, and its floor is the entropy

Average the negative log-likelihood over the rows, and you get the log loss. scikit-learn's documentation calls it logistic loss or cross-entropy loss, the negative log-likelihood of a logistic model. In general, for a true distribution p over some outcomes and a model's q, the cross entropy is

H(p,q)=−∑ipilog⁡qiH(p, q) = -\sum_i p_i \log q_i

Predict

Is H(p, q) the same number as H(q, p)?

Pick an answer above to see the rest
Predict

Predict the shop's actual return rate, 12.3%, for every order. What's the log loss?

Pick an answer above to see the rest
Part 4 done
Part 5 of 7about 7 min
Language models

A language model's loss is cross entropy per token, and perplexity is its exponent

A language model is scored the same way, one token at a time: minus the log of the chance it gave the token that came next, averaged over tokens. PyTorch's CrossEntropyLoss computes it from the logits, and the GPT from scratch lesson trains on the same loss. Hugging Face's documentation defines perplexity as the exponentiated average negative log-likelihood of a sequence, which it notes is the same as e to the cross entropy.

Predict

A model gives the right next token a 25% chance every time. What's its perplexity?

Pick an answer above to see the rest
Predict

Train ever bigger models on the same text. Where does the loss go?

Pick an answer above to see the rest
Part 5 done
Part 6 of 7about 8 min
The worked example

A worked example: a distribution's minimum error, out loud

Here's the OpenAI question, worked out loud.

Use cross entropy to find a distribution's minimum error. The report is one line (1 source), so most of the work is pinning it down.

1. Pin down the words. Error is the cross entropy H(p, q) of a model q against data from p. Minimum is over every possible q. Say both before coding.

2. Answer, then show it. The minimum is the entropy H(p), at q = p, by Gibbs' inequality. Then check it in code: make q a softmax of logits z and run gradient descent.

Predict

What's the gradient of H(p, softmax(z)) with respect to the logits z?

Pick an answer above to see the rest
Predict

You have 1,000 labeled rows, not p itself. What's the lowest log loss a constant prediction reaches on them?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 3 min
Follow-ups

Perfectly separated data

Three follow-ups come up after likelihood questions.

Predict

Every sale order was returned, and no other order was. What happens to the sale coefficient as the fit runs?

Pick an answer above to see the rest

A prior is a penalty

Multiply the likelihood by a prior on the parameters, and maximize that instead: the maximum a posteriori estimate. A normal prior on the coefficients adds −λ Σ b² to the log-likelihood, which is L2 regularization, the same thing ridge regression does. It also stops the runaway coefficient from the last step. The shrinkage lesson's Bayesian average is the same move for a rating.

Log loss punishes confident mistakes

The last one compares log loss with accuracy.

Predict

A model gives an order a 1% chance of a return, and it comes back. What does that order add to the log loss?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.Why sum log probabilities instead of multiplying the probabilities?

  2. 2.The maximum likelihood variance of 8 delivery times divides the summed squared distances by what?

  3. 3.A logistic regression gives a sale a coefficient of 0.7. What does a sale do?

  4. 4.The true return rate is 20%. What's the lowest log loss any prediction can reach?

  5. 5.A language model's loss stops falling near 1.7 nats per token, however big the model. What's the likeliest reading?

Practice

Sources (23)
  1. 8.4.1.2. Maximum likelihood estimation · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
    “Loosely speaking, the likelihood of a set of data is the probability of obtaining that particular set of data, given the chosen probability distribution model.”
  2. 8.4.1.2. Maximum likelihood estimation · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
    “The values of these parameters that maximize the sample likelihood are known as the Maximum Likelihood Estimates or MLEs.”
  3. Information Theory, Inference, and Learning Algorithms, Chapter 2: Probability, Entropy, and Inference · David J. C. MacKay, Cambridge University Press · Nov 19, 2026
    “Never say ‘the likelihood of the data’. Always say ‘the likelihood of the parameters’. The likelihood function is not a probability distribution.”
  4. Deep Learning, Chapter 5: Machine Learning Basics · Goodfellow, Bengio and Courville, MIT Press · Nov 19, 2026
    “This product over many probabilities can be inconvenient for various reasons. For example, it is prone to numerical underflow.”
  5. CS229 Lecture Notes · Andrew Ng and Tengyu Ma, Stanford University · Nov 19, 2026
    “Instead of maximizing L(θ), we can also maximize any strictly increasing function of L(θ).”
  6. Deep Learning, Chapter 5: Machine Learning Basics · Goodfellow, Bengio and Courville, MIT Press · Nov 19, 2026
    “Therefore, the sample variance is a biased estimator.”
  7. 1.3.6.5.2. Maximum Likelihood · NIST/SEMATECH e-Handbook of Statistical Methods · Nov 19, 2026
    “They become minimum variance unbiased estimators as the sample size increases.”
  8. CS229 Lecture Notes · Andrew Ng and Tengyu Ma, Stanford University · Nov 19, 2026
    “let’s endow our classification model with a set of probabilistic assumptions, and then fit the parameters via maximum likelihood.”
  9. Lesson 15.1: Logistic Regression · Penn State STAT 462, Applied Regression Analysis · Nov 19, 2026
    “the (natural) logarithm of the odds is a linear function of the X variables (and is often called the log odds).”
  10. Lesson 15.1: Logistic Regression · Penn State STAT 462, Applied Regression Analysis · Nov 19, 2026
    “Maximizing the likelihood (or log likelihood) has no closed-form solution, so a technique like iteratively reweighted least squares is used to find an estimate of the regression coefficients”
  11. FAQ: How do I interpret odds ratios in logistic regression? · UCLA Statistical Methods and Data Analytics (OARC) · Nov 19, 2026
    “So we can get the odds ratio by exponentiating the coefficient for female.”
  12. sklearn.metrics.log_loss · scikit-learn · Nov 19, 2026
    “Log loss, aka logistic loss or cross-entropy loss. This is the loss function used in (multinomial) logistic regression ... defined as the negative log-likelihood of a logistic model”
  13. Deep Learning, Chapter 5: Machine Learning Basics · Goodfellow, Bengio and Courville, MIT Press · Nov 19, 2026
    “Any loss consisting of a negative log-likelihood is a cross-entropy between the empirical distribution ... and the probability distribution”
  14. A Mathematical Theory of Communication · C. E. Shannon, Bell System Technical Journal · Jul 1, 1948
    “play a central role in information theory as measures of information, choice and uncertainty.”
  15. A Mathematical Theory of Communication · C. E. Shannon, Bell System Technical Journal · Jul 1, 1948
    “Thus only when we are certain of the outcome does H vanish.”
  16. Information Theory, Inference, and Learning Algorithms, Chapter 2: Probability, Entropy, and Inference · David J. C. MacKay, Cambridge University Press · Nov 19, 2026
    “The relative entropy satisfies Gibbs’ inequality ... with equality only if P = Q.”
  17. Deep Learning, Chapter 3: Probability and Information Theory · Goodfellow, Bengio and Courville, MIT Press · Nov 19, 2026
    “Minimizing the cross-entropy with respect to Q is equivalent to minimizing the KL divergence, because Q does not participate in the omitted term.”
  18. CrossEntropyLoss · PyTorch documentation · Nov 19, 2026
    “This criterion computes the cross entropy loss between input logits and target.”
  19. Perplexity of fixed-length models · Hugging Face Transformers documentation · Nov 19, 2026
    “Perplexity is defined as the exponentiated average negative log-likelihood of a sequence.”
  20. Perplexity of fixed-length models · Hugging Face Transformers documentation · Nov 19, 2026
    “This is also equivalent to the exponentiation of the cross-entropy between the data and model predictions.”
  21. Scaling Laws for Neural Language Models · Kaplan et al., OpenAI (arXiv 2001.08361) · Jan 23, 2020
    “Our trends must eventually level off, though, since natural language has non-zero entropy.”
  22. Scaling Laws for Autoregressive Generative Modeling · Henighan et al., OpenAI (arXiv 2010.14701) · Oct 28, 2020
    “In other words, the irreducible loss estimates the entropy of the true data distribution, while the reducible loss is an estimate of the KL divergence between the true and model distributions.”
  23. Training Compute-Optimal Large Language Models · Hoffmann et al., DeepMind (arXiv 2203.15556) · Mar 29, 2022
    “The first term captures the loss for an ideal generative process on the data distribution, and should correspond to the entropy of natural text.”