CD0059 Gaussian Naive Bayes

Mode B · Build & Trace 30 Min NumPy Only 4 Code Blanks

LinkedIn’s feed-integrity team keeps a Gaussian naive Bayes baseline for spam and bot detection because it is fast to retrain and easy to audit. Every score it emits decomposes into a class prior plus one additive term per feature, so a reviewer can see which signal pushed an account toward the bot class. In this round you implement GaussianNB from scratch in NumPy. Importing anything from sklearn is forbidden, and so is scipy.stats.norm.

fit(X, y) receives a matrix of shape (n, d) and labels of any dtype. It must store the sorted labels in classes_, the per-class class_count_ and class_prior_ (count divided by n, with no smoothing), and per-class, per-feature maximum-likelihood means theta_ and variances var_. It must also set epsilon_ to var_smoothing times the largest per-feature variance of the full training matrix, and floor every entry of var_ at it. _joint_log_likelihood returns the (n_q, k) matrix of log prior plus summed Gaussian log-densities. predict returns labels taken from classes_, and predict_proba returns posterior rows that each sum to 1.

Three edges are graded: a feature that is constant within a class, a class seen exactly once, and a 600-feature input whose density product underflows. Fill the 4 blanks, trace the array shape after each line, and verify against a hand-computed two-class fixture.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  class GaussianNB:
05      # Gaussian naive Bayes: maximum-likelihood fit, log-space scoring
06
07      def __init__(self, var_smoothing=1e-9):
08          self.var_smoothing = var_smoothing
09
10      def fit(self, X, y):
11          X = np.asarray(X, dtype=np.float64)              # (n_samples, n_features)
12          y = np.asarray(y)                                # (n_samples,)
13          n_samples, n_features = X.shape
14          self.classes_ = np.unique(y)                     # (n_classes,), sorted
15          n_classes = len(self.classes_)
16          self.class_count_ = np.zeros(n_classes)
17          self.class_prior_ = np.zeros(n_classes)
18          self.theta_ = np.zeros((n_classes, n_features))  # per-class means
19          self.var_ = np.zeros((n_classes, n_features))    # per-class variances
20          for class_idx, label in enumerate(self.classes_):
21              X_class = X[y == label]                      # (n_class_samples, n_features)
22              # TODO (Blank 1): fill row class_idx of class_count_, class_prior_,
23              #                 theta_ and var_ (maximum-likelihood estimates)
24              ...
25          # TODO (Blank 2): set epsilon_ from var_smoothing and the per-feature
26          #                 variances of X, then floor var_ at epsilon_
27          ...
28          return self
29
30      def _joint_log_likelihood(self, X):
31          X = np.asarray(X, dtype=np.float64)              # (n_queries, n_features)
32          # TODO (Blank 3): log prior + sum over features of the Gaussian
33          #                 log-density, shape (n_queries, n_classes)
34          joint_log_likelihood = ...
35          return joint_log_likelihood
36
37      def _decide(self, X):
38          joint_log_likelihood = self._joint_log_likelihood(X)  # (n_queries, n_classes)
39          # TODO (Blank 4): labels = top-scoring class label per row,
40          #                 proba = posterior rows that each sum to 1
41          labels = ...
42          proba = ...
43          return labels, proba
44
45      def predict(self, X):
46          return self._decide(X)[0]                        # (n_queries,)
47
48      def predict_proba(self, X):
49          return self._decide(X)[1]                        # (n_queries, n_classes)
Contract diagram for GaussianNB: a training set X, y flows through four question-marked steps (per-class statistics, variance floor, log-joint scores, labels and probabilities); below, three boxes list the graded edges: zero within-class variance, a class seen exactly once, and likelihood underflow with hundreds of features

Figure 1: the public contract. The inputs and outputs of fit, predict, and predict_proba are fixed, the four question-marked steps are yours to write, and the three graded edges at the bottom decide the score.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the hand-computed fixture plus the edge-case checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Per-Class Statistics: Every stored statistic must be a finite number for a class with a single training row, and the priors must sum to 1.
(2) Floor Scale: Ask which matrix the floor is measured on (the full training set or one class), and what it evaluates to when every column is constant.
(3) Log-Space Scoring: Each class score is a sum of logarithms; no density is exponentiated or multiplied before the final normalization.
(4) Row Normalization: Probability rows must sum to 1 even when every joint log-likelihood in the row sits below -1000.

2Visual Review Map (Figure 2)
Shape trace for GaussianNB: the top row marks the target shapes of Blanks 1 and 2 inside fit, from X and X_class to the per-class arrays; the bottom row marks the target shapes of Blanks 3 and 4 inside prediction, with every operation shown as a question mark

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; the operations that reach them are the exercise.

3Interviewer Nudge & Line Focus

Pin the input shape, output shape, and numerical range of each blank before writing the NumPy call:

Blank 1 (Per-Class Statistics): Under maximum likelihood, does the variance divide by n_c or n_c - 1, and what number does each choice produce for a class with one row? Which of the two results can a later np.maximum never repair?
Blank 2 (Variance Floor): If one feature is a follower count with variance near 10^{12} and another is a ratio in [0, 1], should the floor be absolute or relative to the data? What does your epsilon_ evaluate to when every column of the training matrix is constant?
Blank 3 (Joint Log-Likelihood): theta_ is (n_classes, n_features) and the queries are (n_queries, n_features). Where must each array gain a new axis so the difference broadcasts to (n_queries, n_classes, n_features), and which axis do you then sum away?
Blank 4 (Labels + Posterior): If both entries of a row are about -900, what does np.exp return for each, and what is 0 / 0? Which per-row constant can you subtract without changing the normalized result, and does np.argmax return a label or a column index?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *