-
Notifications
You must be signed in to change notification settings - Fork 1
/
naive_bayes_classifier.js
86 lines (75 loc) · 2.37 KB
/
naive_bayes_classifier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const fs = require('fs');
// read in data from csv file
let data = fs.readFileSync('./data.csv', 'utf8').split('\n');
// split each line into an array of values
data = data.map(line => line.split(','));
// create a mapping of unique class labels
let classLabels = new Set();
data.forEach(line => {
classLabels.add(line[line.length - 1]);
});
classLabels = Array.from(classLabels);
// create a mapping of unique feature names
let featureNames = data[0].slice(0, -1);
// split data into training and test sets
let trainingData = [];
let testData = [];
for (let i = 1; i < data.length; i++) {
if (i % 5 === 0) {
testData.push(data[i]);
} else {
trainingData.push(data[i]);
}
}
// create a function to calculate the probability of a given feature value given a class label
function featureProbabilityGivenClass(featureName, featureValue, classLabel) {
let featureCountGivenClass = 0;
let classCount = 0;
trainingData.forEach(line => {
if (line[line.length - 1] === classLabel) {
classCount++;
if (line[featureNames.indexOf(featureName)] === featureValue) {
featureCountGivenClass++;
}
}
});
return featureCountGivenClass / classCount;
}
// create a function to calculate the probability of a given class label
function classProbability(classLabel) {
let classCount = 0;
trainingData.forEach(line => {
if (line[line.length - 1] === classLabel) {
classCount++;
}
});
return classCount / trainingData.length;
}
// create a function to classify a given data point
function classify(dataPoint) {
let probabilities = {};
classLabels.forEach(classLabel => {
probabilities[classLabel] = classProbability(classLabel);
featureNames.forEach(featureName => {
probabilities[classLabel] *= featureProbabilityGivenClass(featureName, dataPoint[featureNames.indexOf(featureName)], classLabel);
});
});
let maxProbability = 0;
let predictedClass = '';
for (let classLabel in probabilities) {
if (probabilities[classLabel] > maxProbability) {
maxProbability = probabilities[classLabel];
predictedClass = classLabel;
}
}
return predictedClass;
}
// test the classifier on the test data
let correct = 0;
testData.forEach(dataPoint => {
let prediction = classify(dataPoint);
if (prediction === dataPoint[dataPoint.length - 1]) {
correct++;
}
});
console.log(Accuracy: ${correct / testData.length});