-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdtree.js
61 lines (56 loc) · 1.67 KB
/
dtree.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
var _ = require('lodash');
var utils = require('./utils');
var DecisionTree = function(examples, attributes, target) {
var targetValues = _.unique(_.pluck(examples, target));
if (targetValues.length === 1) {
return {
type: 'result',
value: targetValues[0],
name: targetValues[0]
};
}
if (attributes.length === 0) {
return {
type: 'result',
value: utils.pluralityValue(examples, target)
};
}
var bestAttribute = utils.chooseAttribute(examples, attributes, target);
this.name = bestAttribute;
this.type = 'attribute';
var uniqueAttributeValues = _.uniq(_.pluck(examples, bestAttribute));
this.branches = uniqueAttributeValues.map(function(v) {
var exs = examples.filter(function(e) {
return e[bestAttribute] === v;
});
return {
name: v,
type: 'branch',
node: new DecisionTree(exs, _.without(attributes, bestAttribute), target)
};
});
}
DecisionTree.prototype.predict = function(data) {
var node = this;
while (node.type !== 'result') {
var attr = node.name;
var givenValue = data[attr];
// console.log("%s: %s", attr, givenValue);
// console.log(node.branches);
var selectedBranch = _.detect(node.branches, function(x) {
// console.log(x.name.toString() == givenValue);
return x.name.toString() == givenValue;
});
// console.log();
// console.log(selectedBranch);
if (!selectedBranch) {
selectedBranch = node.branches[Math.floor(Math.random()*node.branches.length)];
}
node = selectedBranch.node;
}
return node.name;
}
DecisionTree.prototype.toJson = function() {
return JSON.stringify(this);
}
module.exports = DecisionTree;