| 50 | } |
| 51 | |
| 52 | array naive_bayes_predict(float *priors, const array &mu, const array &sig2, |
| 53 | const array &test_feats, int num_classes) { |
| 54 | int num_test = test_feats.dims(1); |
| 55 | |
| 56 | // Predict the probabilities for testing data |
| 57 | // Using log of probabilities to reduce rounding errors |
| 58 | array log_probs = constant(1, num_test, num_classes); |
| 59 | |
| 60 | for (int ii = 0; ii < num_classes; ii++) { |
| 61 | // Tile the current mean and variance to the testing data size |
| 62 | array Mu = tile(mu(span, ii), 1, num_test); |
| 63 | array Sig2 = tile(sig2(span, ii), 1, num_test); |
| 64 | |
| 65 | // This is the same as log of the CDF of the normal distribution |
| 66 | array Df = test_feats - Mu; |
| 67 | array log_P = (-(Df * Df) / (2 * Sig2)) - log(sqrt(2 * af::Pi * Sig2)); |
| 68 | |
| 69 | // Accumulate the probabilities, multiply with priors (add log of |
| 70 | // priors) |
| 71 | log_probs(span, ii) = log(priors[ii]) + sum(log_P).T(); |
| 72 | } |
| 73 | |
| 74 | // Get the location of the maximum value |
| 75 | array val, idx; |
| 76 | max(val, idx, log_probs, 1); |
| 77 | return idx; |
| 78 | } |
| 79 | |
| 80 | void benchmark_nb(const array &train_feats, const array test_feats, |
| 81 | const array &train_labels, int num_classes) { |