Top Indicative Words per Naive Bayes Class

Quick Overview

Implement one-vs-rest log-likelihood ratios from a fitted multinomial Naive Bayes model and return the top-k most indicative words for each class. It tests smoothing from raw feature counts, pooling the other classes correctly, and a deterministic ranking with an alphabetical tie-break.

Top Indicative Words per Naive Bayes Class

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given a fitted scikit-learn `MultinomialNB` model, implement `log_likelihood_ratios(model)`, which returns an `(n_classes, n_words)` matrix of one-vs-rest log-likelihood ratios. Then implement `top_indicative_words(model, vocabulary, k)`, which returns a dict mapping each class label to its top-`k` words ranked by that ratio. The ratio for class `c` and word `w` is defined as: ```python # N = model.feature_count_, alpha = model.alpha, V = n_words # rest = counts pooled over all other classes theta_cw = (N[c, w] + alpha) / (N[c].sum() + alpha * V) theta_rest = (rest[w] + alpha) / (rest.sum() + alpha * V) ratio[c, w] = log(theta_cw) - log(theta_rest) ``` For example: ```python X = [[0,1,2,1], [0,0,1,1], [2,1,0,0], [1,2,0,0]] y = ["ham", "ham", "spam", "spam"] model = MultinomialNB(alpha=1.0).fit(X, y) vocabulary = ["cash", "free", "hello", "meet"] log_likelihood_ratios(model)[0] # log([1/4, 2/4, 4, 3]) (ham row) top_indicative_words(model, vocabulary, 2) # {"ham": ["hello", "meet"], "spam": ["cash", "free"]} ``` ```hint Where the rest counts come from `feature_count_` stores raw, unsmoothed counts per class. Look at what the column totals over all classes give you once you take away one class's row. ``` ```hint One sort key for both rules Python sorts ascending. Build a single key that puts larger ratios first and falls back to the word itself when two ratios are equal. ``` ### Constraints & Assumptions - Rank by descending ratio. Break ties alphabetically by word. - Dict keys follow `model.classes_` order. - If `k` exceeds the vocabulary size, return all words ranked. Negative `k` is treated as `0`. - If `len(vocabulary)` differs from the number of features, raise `ValueError`. - Read `alpha` from the fitted model. The model has at least 2 classes. ### What a Strong Answer Covers - Building the rest distribution from pooled raw counts, smoothed with the model's own `alpha`, and why the per-class probabilities stored on the model cannot simply be combined. - A ratio matrix of shape `(n_classes, n_words)` whose rows line up with `model.classes_`. - A ranking that orders by descending ratio, breaks ties by word, and handles `k` above the vocabulary size and negative `k`. - Raising `ValueError` for a vocabulary of the wrong length. - The cost of computing the ratios and of sorting each row. ### Follow-up Questions - Averaging the other classes' `feature_log_prob_` rows gives a different rest distribution than pooling their counts. When is the gap between the two largest? - How does a larger `alpha` change which words rank at the top, especially rare ones? - With a vocabulary of several million words and `k = 20`, how would you avoid a full sort for every class? - With ten or more classes, the rest pool mixes very different classes. What other contrast could you rank words by, and what would it tell you?

Overview: Implement one-vs-rest log-likelihood ratios from a fitted multinomial Naive Bayes model and return the top-k most indicative words for each class. It tests smoothing from raw feature counts, pooling the other classes correctly, and a deterministic ranking with an alphabetical tie-break.

General logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given a fitted scikit-learn MultinomialNB model, implement log_likelihood_ratios(model), which returns an (n_classes, n_words) matrix of one-vs-rest log-likelihood ratios. Then implement top_indicative_words(model, vocabulary, k), which returns a dict mapping each class label to its top-k words ranked by that ratio.

The ratio for class c and word w is defined as:

# N = model.feature_count_, alpha = model.alpha, V = n_words
# rest = counts pooled over all other classes
theta_cw    = (N[c, w] + alpha) / (N[c].sum() + alpha * V)
theta_rest  = (rest[w] + alpha) / (rest.sum() + alpha * V)
ratio[c, w] = log(theta_cw) - log(theta_rest)

For example:

X = [[0,1,2,1], [0,0,1,1], [2,1,0,0], [1,2,0,0]]
y = ["ham", "ham", "spam", "spam"]
model = MultinomialNB(alpha=1.0).fit(X, y)
vocabulary = ["cash", "free", "hello", "meet"]

log_likelihood_ratios(model)[0]  # log([1/4, 2/4, 4, 3])  (ham row)
top_indicative_words(model, vocabulary, 2)
# {"ham": ["hello", "meet"], "spam": ["cash", "free"]}

Constraints & Assumptions

  • Rank by descending ratio. Break ties alphabetically by word.
  • Dict keys follow model.classes_ order.
  • If k exceeds the vocabulary size, return all words ranked. Negative k is treated as 0 .
  • If len(vocabulary) differs from the number of features, raise ValueError .
  • Read alpha from the fitted model. The model has at least 2 classes.

What a Strong Answer Covers Guidance

  • Building the rest distribution from pooled raw counts, smoothed with the model's own alpha , and why the per-class probabilities stored on the model cannot simply be combined.
  • A ratio matrix of shape (n_classes, n_words) whose rows line up with model.classes_ .
  • A ranking that orders by descending ratio, breaks ties by word, and handles k above the vocabulary size and negative k .
  • Raising ValueError for a vocabulary of the wrong length.
  • The cost of computing the ratios and of sorting each row.

Follow-up Questions Guidance

  • Averaging the other classes' feature_log_prob_ rows gives a different rest distribution than pooling their counts. When is the gap between the two largest?
  • How does a larger alpha change which words rank at the top, especially rare ones?
  • With a vocabulary of several million words and k = 20 , how would you avoid a full sort for every class?
  • With ten or more classes, the rest pool mixes very different classes. What other contrast could you rank words by, and what would it tell you?