Count-Feature Text Classifier via Command Replay
Data Structure DesignAuto-graded · 12 test casesLast 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]
Xis a list of rows, and each row is a list ofdnon-negative counts.yis a list of class labels with one label per row ofX. 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]
Qis a list of query rows, each withdnon-negative counts, wheredis the feature count from the latestfit.- 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:
commandsandpayloadshave different lengths.- A
fithas emptyX,Xandyof different lengths, rows of inconsistent length, zero features, or any negative value. - A
predictis issued before anyfit. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function is a small state machine. The state is the trained model: the sorted list of labels, a log prior per class, and a log-likelihood vector per class.
fit
- Validate the input.
- Collect the distinct labels in sorted order.
- For each class, compute the log prior
log(N_c / N). - For each class, sum each feature over the class's rows and apply add-one smoothing:
theta[c][j] = (count[c][j] + 1) / (total_c + d). Store the logs. - Replace any previous model and return
None.
predict
- Check that a model exists and that every query row has the right length and non-negative values.
- For each row, compute
log prior + sum_j q[j] * log_theta[c][j]for every class. - Pick the class with the maximum score. Iterating over the sorted labels and keeping the first maximum (which is what Python's
maxdoes) gives the required tie-break.
Why it is correct
- Bayes' rule gives
P(c | q)proportional toP(c) * P(q | c). The evidence term is the same for every class, so it does not affect the argmax. - Under the multinomial model,
P(q | c)is proportional to the product oftheta[c][j] ** q[j]. The multinomial coefficient is the same for all classes and drops out. - Taking logs turns the product into a sum, avoids underflow, and preserves the ordering of scores.
- Add-one smoothing keeps every
thetastrictly positive, sologis always finite, even for features never seen in a class. - A zero query row scores each class by its log prior alone, so the most frequent class wins (ties go to the smallest label).
Complexity
Let n be the number of training rows, d the number of features, C the number of classes and m the number of query rows.
fit: O(n·d + C·n) time, with the per-class row collection dominating. Space is O(C·d).predict: O(m·C·d) time and O(C) extra space per row.
Reference solution
import math
from typing import List
def run_count_classifier(commands: List[str], payloads: List[List]) -> List:
labels_sorted = None
log_prior = {}
log_theta = {}
d = 0
out = []
if len(commands) != len(payloads):
raise ValueError("commands and payloads must have equal lengths")
for cmd, args in zip(commands, payloads):
if cmd == "fit":
X, y = args
if len(X) != len(y) or not X:
raise ValueError("fit requires equally sized, nonempty X and y")
d = len(X[0])
if d == 0 or any(len(r) != d for r in X):
raise ValueError("X must have a consistent, nonzero feature count")
if any(v < 0 for r in X for v in r):
raise ValueError("features must be nonnegative")
labels_sorted = sorted(set(y))
n = len(y)
log_prior = {}
log_theta = {}
for c in labels_sorted:
rows = [X[i] for i, lab in enumerate(y) if lab == c]
log_prior[c] = math.log(len(rows) / n)
totals = [sum(r[j] for r in rows) for j in range(d)]
denom = sum(totals) + d
log_theta[c] = [math.log((t + 1) / denom) for t in totals]
out.append(None)
elif cmd == "predict":
if labels_sorted is None:
raise ValueError("predict requires a preceding fit")
(Q,) = args
if any(len(r) != d for r in Q):
raise ValueError("query rows must match the fitted feature count")
preds = []
for row in Q:
if any(v < 0 for v in row):
raise ValueError("features must be nonnegative")
scores = {
c: log_prior[c] + sum(v * log_theta[c][j] for j, v in enumerate(row))
for c in labels_sorted
}
preds.append(max(labels_sorted, key=lambda c: scores[c]))
out.append(preds)
else:
raise ValueError("command must be 'fit' or 'predict'")
return out