49Ranking from few ratings

mediumpython
40:00

49 Ranking from few ratings

A Netflix data science guide asks how you would analyze focus-group ratings when each of 1,000 participants rated a random 100 of the pilot episodes (1 source). Some pilots end up with few ratings and some raters are harsh. This is practice in that shape, not a leaked question. Use only the standard library.

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

Level 1. Bayesian averages. bayesian_average(ratings, prior_mean, weight) is the average after adding weight imaginary ratings at prior_mean. With no ratings it's the prior mean, and with weight 0 it's the plain average. rank_by_bayes(items, weight) takes a dict from name to ratings and returns the names, best first, by Bayesian average, where the prior mean is the mean of every rating of every item pooled together (not the mean of the item means). Ties go by name, A to Z.

Level 2. Thumbs up. wilson_lower(ups, n, z=1.96) is the lower end of the Wilson score interval for ups out of n: with p = ups / n, it's (p + z²/2n − z √(p(1 − p)/n + z²/4n²)) / (1 + z²/n), and 0 when n is 0. rank_by_wilson(items) takes a dict from name to (ups, n) and returns the names, best first, by that lower bound. Ties go by name, A to Z.

Level 3. Empirical Bayes and harsh raters. shrink(items) pulls each item's mean toward the grand mean, the mean of the item means. Estimate the noise σ² by pooling the items with more than one rating: the sum of (n − 1) times each item's sample variance, over the sum of (n − 1). Estimate the real spread τ² as the sample variance of the item means (divide by the number of items minus 1) minus the average of σ²/n over the items, and never below 0. Each item keeps a weight w = τ² / (τ² + σ²/n) on its own mean, or 0 if τ² is 0, and returns w × its mean + (1 − w) × the grand mean. Every item has at least one rating, and at least one item has two. rater_adjusted(rows) takes (rater, item, score) rows, subtracts from each score its rater's mean minus the mean of all scores (every row counts once, so a rater with more rows weighs more), and returns each item's average adjusted score.

Things to get right: which mean is the prior, the Wilson interval's own center, floors and empty cases, and adding back the overall mean when you remove a rater's offset. Follow-ups from the lesson: why the top of a raw ranking is all small samples, and the winner's curse.

solution.py
Run the tests to see which pass.