All problems
Naive Bayes Predict
Problem
Predict a class with Gaussian naive Bayes for a single point x.
classes, priors, means, and variances are parallel per-class lists; means[ci][j] and variances[ci][j] are the mean and variance of feature j for class ci. Score each class as log(prior) plus the sum of log Gaussian densities, then return the class with the highest score, breaking ties by the earlier entry in classes.
Hint
Work in log space: log prior plus the sum of per-feature log densities.
Test cases
case 1
in: [[5.1,3.5],["A","B"],[0.5,0.5],[[5,3.4],[6,2.8]],[[0.04,0.09],[0.25,0.16]]]
expected: "A"
case 2
in: [[6.2,3],["A","B"],[0.5,0.5],[[5,3.4],[6,2.8]],[[0.04,0.09],[0.25,0.16]]]
expected: "B"
case 3
in: [[5,3.4],["A","B"],[0.8,0.2],[[5,3.4],[6,2.8]],[[1,1],[1,1]]]
expected: "A"
case 4
in: [[0,0],["neg","pos"],[0.5,0.5],[[0,0],[5,5]],[[1,1],[1,1]]]
expected: "neg"
Starter codePython
import math
def naive_bayes_predict(x, classes, priors, means, variances):
# Your code here
pass4 test cases · run your code against them in the editor