Naive Bayes Log-Probability

~20 mincode completion

Implement naive_bayes_log_probs(x, log_priors, means, stds) that returns the unnormalized log-posterior for each class. Return a 1D array of shape (n_classes,).

Examples

2 classes, 1 feature: higher prior wins with equal likelihood

Input
naive_bayes_log_probs([0], [-0.5, -1], [[0], [0]], [[1], [1]])
Output
[-1.41894, -1.91894]

Hints

Hint 1

is the natural log, which is what this formula wants.

Hint 2

Do not forget to log prior term. That step is easy to skip.

Requirements

  • x: Feature vector, shape (d,)

  • log_priors: Log prior for each class, shape (n_classes,)

  • means: Class-conditional means, shape (n_classes, d)

  • stds: Class-conditional stds, shape (n_classes, d)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~20 min

8 employers weight this skill

4 quant funds, 2 health and bio companies, 1 enterprise vendor, 1 big tech firm. Top match scores 63.

Python
import numpy as np

def naive_bayes_log_probs(x: np.ndarray, log_priors: np.ndarray, means: np.ndarray, stds: np.ndarray) -> np.ndarray:
    """
    Compute unnormalized log-posterior for each class.

    Args:
        x:           Feature vector, shape (d,)
        log_priors:  Log prior for each class, shape (n_classes,)
        means:       Class-conditional means, shape (n_classes, d)
        stds:        Class-conditional stds, shape (n_classes, d)

    Returns:
        Unnormalized log-posteriors, shape (n_classes,).
        (log_prior + sum of Gaussian log-likelihoods over features)
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.