Merge Sharded Multinomial Naive Bayes Models

Quick Overview

Implement a count-based multinomial Naive Bayes model in NumPy and merge two shard models over the union of their classes and vocabulary so the result equals a single fit on all the data. It tests sufficient statistics, index alignment, smoothing after the merge and stable posterior computation.

Merge Sharded Multinomial Naive Bayes Models

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a count-based Multinomial Naive Bayes model stored as a dict. `merge_models(model_a, model_b)` combines two shard models over the union of classes and vocabulary so the result is identical to `fit_counts` on all the data concatenated. Also implement smoothing and prediction on the merged model. Requirements: - `fit_counts(docs, labels)` tokenizes with `doc.lower().split()` and returns a dict with keys `classes` and `vocab` (both sorted), plus `class_count` with shape (C,) and `word_count` with shape (C, V), both float arrays. - `merge_models` takes the sorted union of classes and vocab and sums the counts. It must be commutative and support repeated merging. - `feature_log_prob(model, alpha=1.0)` returns `log((N_cw + alpha) / (N_c + alpha * V))` with shape (C, V), where `N_cw` is the count of word w in class c and `N_c` is the total word count of class c. - `predict_log_proba` and `predict_proba` use the prior `class_count / total`, ignore out-of-vocabulary tokens, and normalize each row. The output has shape (n_docs, C) in `classes` order. - `predict` returns a numpy array of argmax labels. Ties go to the first (smallest) class. Example: ```python a = fit_counts(["a b a", "b c"], ["x", "y"]) b = fit_counts(["c d"], ["x"]) m = merge_models(a, b) # m["vocab"] == ["a", "b", "c", "d"], m["class_count"] == [2, 1] # m["word_count"] == [[2, 1, 1, 1], [0, 1, 1, 0]] predict_proba(m, ["zzz qqq", ""]) # [[2/3, 1/3], [2/3, 1/3]] ``` Only `numpy` is available. Results are checked against `sklearn.naive_bayes.MultinomialNB`. ```hint What a shard should carry Decide whether a shard model should hold counts or smoothed probabilities, and check which of the two still equals a full fit after you combine them. ``` ```hint Aligning the shards The two shards order their classes and words differently. Build index maps for the union first, then place each shard's block into the merged arrays. ``` ### What a Strong Answer Covers - Which statistics a shard stores, and why combining them reproduces a fit on the concatenated data. - Re-indexing both shards onto the sorted union of classes and vocabulary, with zeros where a shard has no entry. - Why the merge is commutative and can be applied repeatedly. - Smoothing with the merged vocabulary size, out-of-vocabulary handling, stable row normalization and the tie rule. - The cost of a merge and of prediction. ### Follow-up Questions - How would you merge hundreds of shards efficiently? - How would you remove a shard's contribution, for example after a data deletion request? - How would you handle a very large vocabulary?

Overview: Implement a count-based multinomial Naive Bayes model in NumPy and merge two shard models over the union of their classes and vocabulary so the result equals a single fit on all the data. It tests sufficient statistics, index alignment, smoothing after the merge and stable posterior computation.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement a count-based Multinomial Naive Bayes model stored as a dict. merge_models(model_a, model_b) combines two shard models over the union of classes and vocabulary so the result is identical to fit_counts on all the data concatenated. Also implement smoothing and prediction on the merged model.

Requirements:

  • fit_counts(docs, labels) tokenizes with doc.lower().split() and returns a dict with keys classes and vocab (both sorted), plus class_count with shape (C,) and word_count with shape (C, V), both float arrays.
  • merge_models takes the sorted union of classes and vocab and sums the counts. It must be commutative and support repeated merging.
  • feature_log_prob(model, alpha=1.0) returns log((N_cw + alpha) / (N_c + alpha * V)) with shape (C, V), where N_cw is the count of word w in class c and N_c is the total word count of class c.
  • predict_log_proba and predict_proba use the prior class_count / total , ignore out-of-vocabulary tokens, and normalize each row. The output has shape (n_docs, C) in classes order.
  • predict returns a numpy array of argmax labels. Ties go to the first (smallest) class.

Example:

a = fit_counts(["a b a", "b c"], ["x", "y"])
b = fit_counts(["c d"], ["x"])
m = merge_models(a, b)
# m["vocab"] == ["a", "b", "c", "d"], m["class_count"] == [2, 1]
# m["word_count"] == [[2, 1, 1, 1], [0, 1, 1, 0]]
predict_proba(m, ["zzz qqq", ""])  # [[2/3, 1/3], [2/3, 1/3]]

Only numpy is available. Results are checked against sklearn.naive_bayes.MultinomialNB.

What a Strong Answer Covers Guidance

  • Which statistics a shard stores, and why combining them reproduces a fit on the concatenated data.
  • Re-indexing both shards onto the sorted union of classes and vocabulary, with zeros where a shard has no entry.
  • Why the merge is commutative and can be applied repeatedly.
  • Smoothing with the merged vocabulary size, out-of-vocabulary handling, stable row normalization and the tie rule.
  • The cost of a merge and of prediction.

Follow-up Questions Guidance

  • How would you merge hundreds of shards efficiently?
  • How would you remove a shard's contribution, for example after a data deletion request?
  • How would you handle a very large vocabulary?