Premium problem76. Naive Bayes Over Many Words

Medium Locked

priors[c] is the prior probability of class c, likelihoods[c][j] is P(feature j=1∣c)P(\text{feature } j = 1 \mid c), and features is a list of 0/1 values. Assume the features are conditionally independent given the class. Return the normalised posterior probability of each class.

Work in log space and subtract the maximum before exponentiating. Multiplying a few hundred small probabilities directly underflows to exactly zero, and then every class looks equally likely because they are all 0.

Input

priors = [0.5, 0.5]
likelihoods = [[0.9, 0.1, 0.8], [0.2, 0.7, 0.3]]
features = [1, 0, 1]

Output

[0.972972972972973, 0.027027027027027032]

Premium problem

This one's part of Premium. Unlock the full Probability track plus every other premium problem on the site.

Implement solve(...)