FastPrepBayesian Scenario Classifier

Bayesian Scenario Classifier

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

For this exercise, implement a Bayesian classifier for binary feature observations using a supplied model. There are c classes labeled 0..c-1 and d features.

  • classWeights[k] is a nonnegative prior weight. The class prior is that weight divided by the sum of all weights.
  • positivePercentages[k][j] is the integer percentage probability that feature j is 1 in class k. The probability of 0 is its complement.
  • For this exercise, features are conditionally independent given the class, and the supplied probabilities are used directly without smoothing.

For each row x of observations, select the class with the largest posterior probability. Equivalently compare the exact integer scores classWeights[k] * product_j factor[k][j], where the factor is positivePercentages[k][j] if x[j] = 1 and 100 - positivePercentages[k][j] otherwise.

If the largest score is positive, return the smallest class label attaining it. If all scores are zero, return -1: the observation has zero probability under this model. Return one label per observation in input order. An empty observation matrix returns an empty array.

Function

classifyScenarios(classWeights: int[], positivePercentages: int[][], observations: int[][]) → int[]

Examples

Example 1

classWeights = [1,1]positivePercentages = [[80,20],[20,80]]observations = [[1,0],[0,1],[1,1],[0,0]]return = [0,1,0,0]

For [1,0], integer scores are6400 and400. The reversed scenario chooses class1; the other two tie and choose class0.

Example 2

classWeights = [3,1]positivePercentages = [[20],[80]]observations = [[1],[0]]return = [1,0]

For a one, scores60 and80 choose class1. For a zero, scores240 and20 choose class0, so the prior participates in both decisions.

Example 3

classWeights = [1,1]positivePercentages = [[100,0],[0,100]]observations = [[1,1],[0,0],[1,0],[0,1]]return = [-1,-1,0,1]

The first two scenarios have zero evidence under every class; the last two match the two possible patterns.

Constraints

  • 2 <= c <= 10 and 1 <= d <= 8.
  • classWeights.length = c; each weight is in 0..100, with at least one positive weight.
  • positivePercentages has c rows of length d; each entry is in 0..100.
  • 0 <= observations.length <= 500; every row has length d and contains only 0 or 1.
  • Scores are compared exactly. A score is at most 10^18, so use signed64-bit arithmetic where needed.

More Amazon problems

See Amazon hiring insights
public int[] classifyScenarios(int[] classWeights, int[][] positivePercentages, int[][] observations) {
    // Write your code here.
}
classWeights[1,1]
positivePercentages[[80,20],[20,80]]
observations[[1,0],[0,1],[1,1],[0,0]]
expected[0,1,0,0]
Checking account…