KatInterview

Count-Feature Text Classifier via Command Replay

Data Structure DesignAuto-graded · 12 test cases
MediumAuto-gradedData Structure Designnaive-bayessimulationlog-probabilities

Last updated

Simulate a stateful multinomial Naive Bayes model driven by fit and predict commands, using smoothed log-probabilities and a deterministic tie-break.

Replaying a Count-Based Classifier

You are given a sequence of commands that drive a small classifier. The classifier is a multinomial Naive Bayes model over non-negative integer count features, and it uses add-one (Laplace) smoothing. Implement a function that executes the commands in order and returns one result per command.

Commands

commands[i] is either "fit" or "predict", and payloads[i] holds that command's arguments.

"fit": payloads[i] = [X, y]

  • X is a list of rows, and each row is a list of d non-negative counts.
  • y is a list of class labels with one label per row of X. Labels are all strings or all integers.
  • Training replaces any previously learned model completely.
  • The result for this command is None.

"predict": payloads[i] = [Q]

  • Q is a list of query rows, each with d non-negative counts, where d is the feature count from the latest fit.
  • The result is a list containing one predicted label per query row, in order.

Model definition

Let N be the number of training rows, N_c the number of rows with label c, and d the number of features. For class c, let count[c][j] be the sum of feature j over all training rows labeled c.

  • Prior: P(c) = N_c / N

  • Smoothed likelihood: theta[c][j] = (count[c][j] + 1) / (sum_k count[c][k] + d)

  • Score for query row q:

    score(c) = log P(c) + sum over j of q[j] * log(theta[c][j])

The prediction is the class with the largest score.

Tie-breaking

Compute the scores as written above, summing the terms in increasing order of j. If two or more classes have exactly equal scores, predict the one that comes first when the distinct labels are sorted in ascending order.

Error handling

Raise ValueError in each of these cases:

  • commands and payloads have different lengths.
  • A fit has empty X, X and y of different lengths, rows of inconsistent length, zero features, or any negative value.
  • A predict is issued before any fit.
  • A query row has a length different from the fitted feature count, or contains a negative value.
  • A command name is neither "fit" nor "predict".

Constraints

  • The number of commands is small (at most a few hundred).
  • Each training set has at most a few hundred rows and at most a few dozen features.
  • Counts are non-negative integers.
  • A query row may be all zeros. Its score is then just the log prior.
  • A single training class is allowed.

Examples

Example 1

Input: run_count_classifier(['fit', 'predict'], [[[[2, 0], [1, 1], [0, 2], [0, 3]], ['fruit', 'fruit', 'vehicle', 'vehicle']], [[[3, 0], [0, 2], [1, 1]]]])

Output: [None, ['fruit', 'vehicle', 'fruit']]

Example 2

Input: run_count_classifier(['fit', 'predict'], [[[[3, 0], [0, 4]], ['A', 'B']], [[[0, 0], [1, 2], [5, 0]]]])

Output: [None, ['A', 'B', 'A']]

Hints

Hint 1

Treat the model as state held between commands: each fit rebuilds the priors and the per-class log-likelihood tables from scratch, and predict only reads them.

Hint 2

Per class, sum each feature column over that class's rows, add 1 to every feature total, and divide by (the class's total count + d). Take the log of each result.

Hint 3

Score each class as log prior plus the sum of q[j] times the log-likelihood. Iterate over the classes in sorted label order and keep the first maximum, which gives the required tie-break.