51Likelihood and cross entropy from scratch
51 Likelihood and cross entropy from scratch
An OpenAI coding round asked candidates to use cross entropy to find a distribution's minimum error (1 source). This is practice in that shape, not a leaked question. Use the standard library, and numpy in level 2.
Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/51_likelihood -k level1. Earlier levels must keep passing.
Level 1. Likelihoods. log_likelihood(p, outcomes) is the log of the probability of a list of 0/1 outcomes
when each is 1 with chance p: add log p for each 1 and log(1 − p) for each 0. Return float("-inf") when the data
is impossible: a 1 at p = 0, or a 0 at p = 1. Data that is certain scores 0.0, such as only 0s at p = 0. It must work for 10,000 outcomes. normal_mle(xs) returns a tuple (mean, variance), the maximum
likelihood estimates for a normal: the sample mean, and the average squared distance from it, dividing by n.
Level 2. Logistic regression. sigmoid(z) takes one number and returns 1 / (1 + e^−z) as a float. It must not overflow at z = ±1000, so
for negative z use e^z / (1 + e^z).
fit_logistic(columns, y, steps=25) fits P(y = 1) = sigmoid(Xw), where X is a column of ones and then each column,
by Newton's method from w = 0. Each step computes p = sigmoid(Xw), the gradient g = Xᵀ(y − p) and the matrix
H = Xᵀ diag(p(1 − p)) X, then adds the solution of H Δ = g to w. Return w as a numpy array: the intercept, then one
slope per column. odds_ratio(coefficient) is how many times the odds multiply for one more unit of the predictor.
Level 3. Cross entropy. All logs are natural. entropy(p) is −Σ p log p over a list of probabilities, where a
term with p = 0 counts as 0. cross_entropy(p, q) is −Σ p log q, where a term with p = 0 counts as 0, and it's
float("inf") if q is 0 where p isn't. min_log_loss(labels) takes a list of class labels of any kind (numbers or strings) and returns the lowest
average log loss that one constant prediction can reach on them.
Things to get right: logs instead of a product, the impossible case, n against n − 1, overflow in the sigmoid, the intercept, the sign of the Newton step, the order of p and q, and zero terms. Follow-ups from the lesson: why the floor is the entropy, perplexity, and why perfectly separated data sends the coefficients to infinity.