Skip to content

Commit 5cbc382

Browse files
committed
major: changing the logic
1 parent 3ffbf49 commit 5cbc382

2 files changed

Lines changed: 9 additions & 7 deletions

File tree

src/main/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifier.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,14 @@ public void fit(double[][] features, int[] labels) {
7676
}
7777

7878
int totalSamples = features.length;
79-
for (Map.Entry<Integer, Integer> entry : classCounts.entrySet()) {
79+
for (Map.Entry<Integer, double[]> entry : featureSums.entrySet()) {
8080
int label = entry.getKey();
81-
int count = entry.getValue();
81+
double[] sums = entry.getValue();
82+
int count = classCounts.getOrDefault(label, 0);
83+
double total = totalFeatureCount.getOrDefault(label, 0.0);
84+
8285
logPriors.put(label, Math.log((double) count / totalSamples));
8386

84-
double[] sums = featureSums.get(label);
85-
double total = totalFeatureCount.get(label);
8687
double denom = total + alpha * numFeatures;
8788
double[] logLikelihood = new double[numFeatures];
8889
for (int j = 0; j < numFeatures; j++) {
@@ -109,10 +110,10 @@ public int predict(double[] sample) {
109110
int bestLabel = -1;
110111
double bestScore = Double.NEGATIVE_INFINITY;
111112

112-
for (Map.Entry<Integer, Double> entry : logPriors.entrySet()) {
113+
for (Map.Entry<Integer, double[]> entry : logLikelihoods.entrySet()) {
113114
int label = entry.getKey();
114-
double score = entry.getValue();
115-
double[] logLikelihood = logLikelihoods.get(label);
115+
double[] logLikelihood = entry.getValue();
116+
double score = logPriors.getOrDefault(label, Double.NEGATIVE_INFINITY);
116117
for (int j = 0; j < numFeatures; j++) {
117118
score += sample[j] * logLikelihood[j];
118119
}

src/test/java/com/thealgorithms/machinelearning/MultinomialNaiveBayesClassifierTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import static org.junit.jupiter.api.Assertions.assertEquals;
44
import static org.junit.jupiter.api.Assertions.assertThrows;
55
import static org.junit.jupiter.api.Assertions.assertTrue;
6+
67
import org.junit.jupiter.api.Test;
78

89
class MultinomialNaiveBayesClassifierTest {

0 commit comments

Comments
 (0)