BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Supervised models11 of 18 in topic

129. Classify binary feature vectors with Bernoulli Naive Bayes

MediumSupervised models
Asked atMeta

Why it matters Bernoulli NB suits short texts and yes/no feature sets such as app permissions or symptom checklists, where absence is informative.

Bernoulli Naive Bayes models whether each feature is present or absent, so a missing word is evidence too.

Write bernoulli_nb(X_train, y_train, X_test, alpha=1.0). Binarise inputs with x > 0. For each class c (sorted): log prior = log(n_c / n) and p_cv = (number of class c rows with feature v present + alpha) / (n_c + 2 * alpha). The score of test row x is log prior_c + sum_v [x_v log p_cv + (1 - x_v) log(1 - p_cv)]. Return (pred, scores) like multinomial NB: a list of labels (smaller label on ties) and an (m, C) float array.

Functiondef bernoulli_nb(X_train, y_train, X_test, alpha=1.0)

Example 1

Input: X_train [[1, 1, 0], [1, 0, 0], [0, 1, 1], [0, 0, 1]], y_train [0, 0, 1, 1], X_test [[1, 1, 0], [0, 1, 1]]

Output: pred [0, 1] and scores [[-1.961659, -4.158883], [-4.158883, -1.961659]] (rounded)

Example 2

Input: X_train = [[1, 1, 1], [1, 1, 1], [1, 0, 0], [1, 0, 0]], y_train = [0, 0, 1, 1], X_test = [[1, 0, 0], [1, 1, 0]]

Output: ([1, 0], [[-3.753418, -1.556193], [-2.654806, -2.654806]])

Example 3

Input: X_train = [[3, 0], [5, 2], [0, 4]], y_train = [1, 1, 2], X_test = [[7, 0], [0, 9]], alpha = 0.5

Output: ([1, 2], [[-1.280934, -3.871201], [-2.890372, -1.673976]])

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

Absent features add log(1 - p) to the score.

Hint 2

Binarise with (X > 0).

Hint 3

Each feature has two outcomes, so smoothing adds 2 alpha to the denominator.

Hint 4

Use matrix products for both the present and absent parts.

Common mistakes
  • Ignoring absent features.
  • Using n_c + alpha in the denominator.
  • Feeding raw counts without binarising.
Understand the idea

Bernoulli Naive Bayes looks at every feature as a yes/no question: does this message contain the word 'offer'? Unlike the multinomial version, a word that does not appear also counts as evidence. If spam emails almost always say 'offer', an email without it is a little less likely to be spam.

Worked example

class 0 has 2 rows and feature 'offer' appears in both. With alpha = 1, p = (2 + 1) / (2 + 2) = 0.75. A test email without 'offer' gets log(1 - 0.75) = log(0.25) added to its class 0 score, a penalty. With the word present it would get log(0.75).

p_cv = (present count + alpha) / (n_c + 2 alpha); score_c = log prior_c + sum_v [x_v log p_cv + (1 - x_v) log(1 - p_cv)]

Bernoulli NB works well for short texts and checklists. For long documents with repeated words, the multinomial version that uses counts is usually better.

Topics
Supervised models
Companies1
  • Meta a candidate reported this question Timed ML screen: concept questions then classic models from scratch (Land the Lab)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Find the best decision tree split with Gini impurityMedium
  • Train a linear SVM with hinge loss subgradient descentMedium
  • Predict with distance-weighted k nearest neighboursMedium
  • Run one round of gradient boosting for squared errorMedium
All Supervised models problems
Report
129 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def bernoulli_nb(X_train, y_train, X_test, alpha=1.0):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS