Semi-Supervised Multinomial Naive Bayes with EM

Quick Overview

Implement a multinomial naive Bayes classifier that also learns from unlabelled count rows with expectation-maximisation, using soft posteriors as fractional class counts. Tests the weighted M-step, log-space normalisation, and the settings where the model must reduce to plain naive Bayes.

Semi-Supervised Multinomial Naive Bayes with EM

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement `SemiSupervisedMultinomialNB` for count matrices, with constructor arguments `alpha`, `n_iter` and `unlabeled_weight`. `fit(X_labeled, y_labeled, X_unlabeled=None)` first runs one M-step on the labelled rows only. It then repeats `n_iter` times: an E-step computes posteriors for the unlabelled rows under the current model, then an M-step refits on all rows. `fit` returns `self`. The M-step takes a responsibility matrix `R` with one row per training row and one column per class. Labelled rows are one-hot over `classes_`; unlabelled rows are `unlabeled_weight * posterior`. ```python class_count = R.sum(0) class_log_prior_ = log(class_count / class_count.sum()) # no prior smoothing feature_count = R.T @ X feature_log_prob_ = log((feature_count + alpha) / (feature_count.sum(1, keepdims=True) + alpha * n_features)) ``` The class must also meet these requirements: - `classes_` holds the sorted unique labels (numeric or string) and is the column order of all outputs. - `predict_log_proba` and `predict_proba` return shape `(n, n_classes)`, normalised with log-sum-exp so they stay finite for huge counts. `predict` breaks ties toward the smallest label. - After `fit`, `unlabeled_proba_` holds the unlabelled posteriors under the final model. - `X_unlabeled=None` (or empty) means no EM: the result is the labelled-only model, and `unlabeled_proba_` has shape `(0, n_classes)`. - With `n_iter=0` or `unlabeled_weight=0` the fitted model must match scikit-learn's `MultinomialNB` fitted on the labelled data. Example: ```python Xl = [[2, 0, 1], [1, 1, 0], [0, 0, 3]] yl = [0, 0, 1] Xu = [[0, 0, 1]] m = SemiSupervisedMultinomialNB(alpha=1.0, n_iter=1).fit(Xl, yl, Xu) np.exp(m.class_log_prior_) # [17/28, 11/28]; the Xu posterior after the first M-step is [3/7, 4/7] m.unlabeled_proba_ # about [[0.3903, 0.6097]] ``` ```hint One update for every step Treat labelled rows as rows of the responsibility matrix that never change. How many different M-step functions do you need then? ``` ```hint Long documents The joint likelihood of a row with large counts underflows to zero for every class. Keep the E-step in log space until the final normalisation. ``` ```hint Degenerate settings Write down what `R` looks like when `unlabeled_weight` is 0 or there are no unlabelled rows, and check that the M-step then gives plain multinomial naive Bayes. ``` ### Constraints & Assumptions - `X_labeled` has shape `(n_labeled, n_features)` and `X_unlabeled` has shape `(n_unlabeled, n_features)` with the same `n_features`. All entries are non-negative counts. - `y_labeled` has one label per labelled row, and every class in `classes_` appears in it. - The unlabelled set can be much larger than the labelled set. ### What a Strong Answer Covers - One weighted M-step over a responsibility matrix, with an unsmoothed class prior and `alpha`-smoothed feature probabilities, used both for initialisation and inside the EM loop. - An E-step that computes posteriors for the unlabelled rows only, under the current model, and scales them by `unlabeled_weight`, in the right order and the right number of times. - Log-sum-exp normalisation, sorted class order and the smallest-label tie rule. - The degenerate cases (no unlabelled rows, `n_iter=0`, `unlabeled_weight=0`) and why each one reduces to plain multinomial naive Bayes. - Why fractional responsibilities are a valid weighted fit, and the time and space cost per iteration. ### Follow-up Questions - How would you replace the fixed iteration count with a convergence test? - Why might unlabelled data hurt accuracy, and what does `unlabeled_weight` do about it? - How would self-training with hard labels or a confidence threshold differ from soft EM?

Overview: Implement a multinomial naive Bayes classifier that also learns from unlabelled count rows with expectation-maximisation, using soft posteriors as fractional class counts. Tests the weighted M-step, log-space normalisation, and the settings where the model must reduce to plain naive Bayes.

PracHub logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement SemiSupervisedMultinomialNB for count matrices, with constructor arguments alpha, n_iter and unlabeled_weight. fit(X_labeled, y_labeled, X_unlabeled=None) first runs one M-step on the labelled rows only. It then repeats n_iter times: an E-step computes posteriors for the unlabelled rows under the current model, then an M-step refits on all rows. fit returns self.

The M-step takes a responsibility matrix R with one row per training row and one column per class. Labelled rows are one-hot over classes_; unlabelled rows are unlabeled_weight * posterior.

class_count = R.sum(0)
class_log_prior_ = log(class_count / class_count.sum())        # no prior smoothing
feature_count = R.T @ X
feature_log_prob_ = log((feature_count + alpha) /
                        (feature_count.sum(1, keepdims=True) + alpha * n_features))

The class must also meet these requirements:

  • classes_ holds the sorted unique labels (numeric or string) and is the column order of all outputs.
  • predict_log_proba and predict_proba return shape (n, n_classes) , normalised with log-sum-exp so they stay finite for huge counts. predict breaks ties toward the smallest label.
  • After fit , unlabeled_proba_ holds the unlabelled posteriors under the final model.
  • X_unlabeled=None (or empty) means no EM: the result is the labelled-only model, and unlabeled_proba_ has shape (0, n_classes) .
  • With n_iter=0 or unlabeled_weight=0 the fitted model must match scikit-learn's MultinomialNB fitted on the labelled data.

Example:

Xl = [[2, 0, 1], [1, 1, 0], [0, 0, 3]]
yl = [0, 0, 1]
Xu = [[0, 0, 1]]
m = SemiSupervisedMultinomialNB(alpha=1.0, n_iter=1).fit(Xl, yl, Xu)
np.exp(m.class_log_prior_)  # [17/28, 11/28]; the Xu posterior after the first M-step is [3/7, 4/7]
m.unlabeled_proba_          # about [[0.3903, 0.6097]]

Constraints & Assumptions

  • X_labeled has shape (n_labeled, n_features) and X_unlabeled has shape (n_unlabeled, n_features) with the same n_features . All entries are non-negative counts.
  • y_labeled has one label per labelled row, and every class in classes_ appears in it.
  • The unlabelled set can be much larger than the labelled set.

What a Strong Answer Covers Guidance

  • One weighted M-step over a responsibility matrix, with an unsmoothed class prior and alpha -smoothed feature probabilities, used both for initialisation and inside the EM loop.
  • An E-step that computes posteriors for the unlabelled rows only, under the current model, and scales them by unlabeled_weight , in the right order and the right number of times.
  • Log-sum-exp normalisation, sorted class order and the smallest-label tie rule.
  • The degenerate cases (no unlabelled rows, n_iter=0 , unlabeled_weight=0 ) and why each one reduces to plain multinomial naive Bayes.
  • Why fractional responsibilities are a valid weighted fit, and the time and space cost per iteration.

Follow-up Questions Guidance

  • How would you replace the fixed iteration count with a convergence test?
  • Why might unlabelled data hurt accuracy, and what does unlabeled_weight do about it?
  • How would self-training with hard labels or a confidence threshold differ from soft EM?