-
Notifications
You must be signed in to change notification settings - Fork 0
/
ml.js
70 lines (52 loc) · 1.73 KB
/
ml.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
const bayes = require('node-bayes');
const dataset = require('./dataset_v2.js');
class Classifier {
constructor(className, docs) {
console.log(`Building classifier for: ${className}`);
this.className = className;
let training = this.docsToMatrix(docs);
console.log(training)
this.model = new bayes.NaiveBayes({
columns: dataset.labels,
data: training,
columnTypes: dataset.types,
verbose: true,
});
this.model.train();
console.log(this.className);
try {
console.log(this.model.predict([ true, true, false, false, true, false, true, false, false]));
} catch (e) {
console.log('Predict failed. Possibly untrained?');
}
}
docsToMatrix(docs) {
let matrix = [];
for (let item of docs) {
if (item.goodLocations.includes(this.className)) {
matrix.push([...dataset.getFeaturesFromData(item), "yes"]);
} else if (item.badLocations.includes(this.className)) {
matrix.push([...dataset.getFeaturesFromData(item), "no"]);
}
}
return matrix;
}
retrain() {
//todo: pull in new data
this.model.train();
}
predict(data) {
let features = dataset.getFeaturesFromData(data);
let rankings = [];
console.log(features);
console.log(this.model);
console.log(this.className);
try {
let prediction = this.model.predict(features);
return prediction;
} catch (e) {
console.log(`${this.className} failed to classify. Was it trained?`);
}
}
}
module.exports = Classifier;