-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreeNode.js
255 lines (226 loc) · 7.01 KB
/
TreeNode.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import mean from './indexMlArrayMean.js';
import { Matrix } from './indexMatrix.js';
import * as Utils from './utilsMLCart.js';
const gainFunctions = {
gini: Utils.giniGain,
regression: Utils.regressionError,
};
const splitFunctions = {
mean: Utils.mean,
};
export default class TreeNode {
/**
* @private
* Constructor for a tree node given the options received on the main classes (DecisionTreeClassifier, DecisionTreeRegression)
* @param {object|TreeNode} options for loading
* @constructor
*/
constructor(options) {
// options parameters
this.kind = options.kind;
this.gainFunction = options.gainFunction;
this.splitFunction = options.splitFunction;
this.minNumSamples = options.minNumSamples;
this.maxDepth = options.maxDepth;
this.gainThreshold = options.gainThreshold || 0;
}
/**
* @private
* Function that retrieve the best feature to make the split.
* @param {Matrix} XTranspose - Training set transposed
* @param {Array} y - labels or values (depending of the decision tree)
* @return {object} - return tree values, the best gain, column and the split value.
*/
bestSplit(XTranspose, y) {
// Depending in the node tree class, we set the variables to check information gain (to classify)
// or error (for regression)
let bestGain = this.kind === 'classifier' ? -Infinity : Infinity;
let check = this.kind === 'classifier' ? (a, b) => a > b : (a, b) => a < b;
let maxColumn;
let maxValue;
let numberSamples;
for (let i = 0; i < XTranspose.rows; ++i) {
let currentFeature = XTranspose.getRow(i);
let splitValues = this.featureSplit(currentFeature, y);
for (let j = 0; j < splitValues.length; ++j) {
let currentSplitVal = splitValues[j];
let splitted = this.split(currentFeature, y, currentSplitVal);
let gain = gainFunctions[this.gainFunction](y, splitted);
if (check(gain, bestGain)) {
maxColumn = i;
maxValue = currentSplitVal;
bestGain = gain;
numberSamples = currentFeature.length;
}
}
}
return {
maxGain: bestGain,
maxColumn: maxColumn,
maxValue: maxValue,
numberSamples: numberSamples,
};
}
/**
* @private
* Makes the split of the training labels or values from the training set feature given a split value.
* @param {Array} x - Training set feature
* @param {Array} y - Training set value or label
* @param {number} splitValue
* @return {object}
*/
split(x, y, splitValue) {
let lesser = [];
let greater = [];
for (let i = 0; i < x.length; ++i) {
if (x[i] < splitValue) {
lesser.push(y[i]);
} else {
greater.push(y[i]);
}
}
return {
greater: greater,
lesser: lesser,
};
}
/**
* @private
* Calculates the possible points to split over the tree given a training set feature and corresponding labels or values.
* @param {Array} x - Training set feature
* @param {Array} y - Training set value or label
* @return {Array} possible split values.
*/
featureSplit(x, y) {
let splitValues = [];
let arr = Utils.zip(x, y);
arr.sort((a, b) => {
return a[0] - b[0];
});
for (let i = 1; i < arr.length; ++i) {
if (arr[i - 1][1] !== arr[i][1]) {
splitValues.push(
splitFunctions[this.splitFunction](arr[i - 1][0], arr[i][0]),
);
}
}
return splitValues;
}
/**
* @private
* Calculate the predictions of a leaf tree node given the training labels or values
* @param {Array} y
*/
calculatePrediction(y) {
if (this.kind === 'classifier') {
this.distribution = Utils.toDiscreteDistribution(
y,
Utils.getNumberOfClasses(y),
);
if (this.distribution.columns === 0) {
throw new TypeError('Error on calculate the prediction');
}
} else {
this.distribution = mean(y);
}
}
/**
* @private
* Train a node given the training set and labels, because it trains recursively, it also receive
* the current depth of the node, parent gain to avoid infinite recursion and boolean value to check if
* the training set is transposed.
* @param {Matrix} X - Training set (could be transposed or not given transposed).
* @param {Array} y - Training labels or values.
* @param {number} currentDepth - Current depth of the node.
* @param {number} parentGain - parent node gain or error.
*/
train(X, y, currentDepth, parentGain) {
if (X.rows <= this.minNumSamples) {
this.calculatePrediction(y);
return;
}
if (parentGain === undefined) parentGain = 0.0;
let XTranspose = X.transpose();
let split = this.bestSplit(XTranspose, y);
this.splitValue = split.maxValue;
this.splitColumn = split.maxColumn;
this.gain = split.maxGain;
this.numberSamples = split.numberSamples;
let splittedMatrix = Utils.matrixSplitter(
X,
y,
this.splitColumn,
this.splitValue,
);
if (
currentDepth < this.maxDepth &&
this.gain > this.gainThreshold &&
this.gain !== parentGain &&
splittedMatrix.lesserX.length > 0 &&
splittedMatrix.greaterX.length > 0
) {
this.left = new TreeNode(this);
this.right = new TreeNode(this);
let lesserX = new Matrix(splittedMatrix.lesserX);
let greaterX = new Matrix(splittedMatrix.greaterX);
this.left.train(
lesserX,
splittedMatrix.lesserY,
currentDepth + 1,
this.gain,
);
this.right.train(
greaterX,
splittedMatrix.greaterY,
currentDepth + 1,
this.gain,
);
} else {
this.calculatePrediction(y);
}
}
/**
* @private
* Calculates the prediction of a given element.
* @param {Array} row
* @return {number|Array} prediction
* * if a node is a classifier returns an array of probabilities of each class.
* * if a node is for regression returns a number with the prediction.
*/
classify(row) {
if (this.right && this.left) {
if (row[this.splitColumn] < this.splitValue) {
return this.left.classify(row);
} else {
return this.right.classify(row);
}
}
return this.distribution;
}
/**
* @private
* Set the parameter of the current node and their children.
* @param {object} node - parameters of the current node and the children.
*/
setNodeParameters(node) {
if (node.distribution !== undefined) {
this.distribution =
node.distribution.constructor === Array
? new Matrix(node.distribution)
: node.distribution;
} else {
this.distribution = undefined;
this.splitValue = node.splitValue;
this.splitColumn = node.splitColumn;
this.gain = node.gain;
this.left = new TreeNode(this);
this.right = new TreeNode(this);
if (node.left !== {}) {
this.left.setNodeParameters(node.left);
}
if (node.right !== {}) {
this.right.setNodeParameters(node.right);
}
}
}
}