Multinomial naive Bayes

Write codeMedium25 minMeta style

Your task

Implement a single multinomial naive-Bayes prediction with Laplace smoothing. You are given class_counts, a dict mapping class label (string) to number of training docs in that class; feature_counts, a dict mapping class label to a dict of {word: count of that word across docs of the class}; vocab, the list of all words; and doc, the list of words in the document to classify. Using add-one (Laplace) smoothing, compute for each class the log score = ln(P(class)) + sum over words in doc of ln((count_of_word_in_class + 1) / (total_words_in_class + |vocab|)). Return the class with the highest log score; break ties by choosing the lexicographically smallest class label. Words in doc not in vocab are ignored.

Examples

nb_predict(class_counts: dict[str,int], feature_counts: dict[str,dict[str,int]], vocab: list[str], doc: list[str]) -> str
Example 1
Inputnb_predict({"spam": 2, "ham": 2}, {"spam": {"buy": 3, "now": 2}, "ham": {"hello": 2, "friend": 1}}, ["buy", "now", "hello", "friend"], ["buy", "now"])
Output"spam"