Code RoomMultinomial naive Bayes
MediumPrep Room Coding #225

Multinomial naive Bayes

CodingML systemsMid–Senior~25 min

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.

Implement
nb_predict(class_counts: dict[str,int], feature_counts: dict[str,dict[str,int]], vocab: list[str], doc: list[str]) → str
Examples
in[{"ham":2,"spam":2},{"ham":{"hello":2,"friend":1},"spam":{"buy":3,"now":2}},["buy","now","hello","friend"],["buy","now"]]out"spam"
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 25 min
InputExpectedGot
[{"ham":2,"spam":2},{"ham":{"hello":2,"friend":1},"spam":{"buy":3,"now":2}},["buy","now","hello","friend"],["buy","now"]]"spam"not run yetsample