42A classifier from a model's Yes and No

mediumpython
40:00

42 A classifier from a model's Yes and No

A PracHub report from an Anthropic coding round: the candidate got a helper that takes a batch of inputs and returns a token probability for each, and had to build a binary classifier with it (1 report). The same tool catches hallucinations: ask the model whether an answer is supported by its source, and read how likely it was to say Yes. This is practice in that shape, not a leaked question.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/42_yes_no_classifier -k level1. Earlier levels must keep passing.

Level 1. A probability from two tokens. The helper gives the log probabilities of the tokens Yes and No for an input. yes_probability(logprob_yes, logprob_no) returns the chance of Yes renormalized over just those two tokens: e^yes / (e^yes + e^no). Both log probabilities can be very negative (-800 for tokens the model never picks), where e^yes is 0 in floating point, so compute it from the difference no - yes. classify(probs, threshold) returns True for every probability at or above the threshold.

Level 2. Choosing the threshold. best_threshold(probs, labels, min_precision) takes probabilities and the true labels for them. Try each distinct probability in probs as a threshold (not a fixed grid), flagging every input at or above it. Precision is the share of flagged inputs that are truly True, and recall is the share of all True inputs that got flagged. Skip a threshold that flags nothing. Return the threshold with the highest recall among those whose precision is at least min_precision, the higher threshold on a tie in recall, or None if none qualifies.

Level 3. Calibration. ece(probs, labels, bins=10) returns the expected calibration error: split [0, 1] into bins equal-width bins (bin floor(p × bins), so a probability on an edge goes in the upper bin, and a probability of exactly 1 goes in the last one), and in each non-empty bin take the gap between its mean probability and its share of True labels, weighted by the bin's share of all inputs. fit_temperature(logits, labels, grid) returns the temperature T from grid whose probabilities 1 / (1 + e^(-logit / T)) give the lowest mean log loss, -log(p) for a True label and -log(1 - p) for a False one. A tie goes to the earlier T.

Things to get right: renormalizing over the two tokens, the threshold itself counting as Yes, the tie rule, weighing bins by their counts, and dividing the logit by the temperature. Follow-ups from the lesson: why a model's raw confidence is often too high, and when to let the classifier abstain.

solution.py
Run the tests to see which pass.