Repository navigation
Expand file tree
/
Copy pathrforest.cpp
More file actions
496 lines (399 loc) · 14.1 KB
/
Copy pathrforest.cpp
File metadata and controls
496 lines (399 loc) · 14.1 KB
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#ifndef RFOREST_CPP
#define RFOREST_CPP
#include <random>
#include "dtree.cpp"
#include "predictor.cpp"
#include "tfidf.cpp"
#include "view.cpp"
class RandomForest : public Predictor {
public:
RandomForest(const Rows& deps, const Rows& syms, const Rows& sym_ths,
long sym_num,
long n_trees, long n_samples, long n_features, double depweight);
~RandomForest();
void import_data(string dirname);
void export_data(string dirname) const;
void learn(long from, long to);
LDPairVec predict(const LVec& csyms, long maxth, long no_adv) const;
private:
long n_of_samples_with_label(const LVec& samples, long label) const;
long n_of_labels_in_samples(const LVec& samples) const;
pair<LUMap, long> labels_of_samples(const LVec& samples) const;
double gini_part(const LVec& samples) const;
double gini_index(const LVec& samples, long feature) const;
LUMap features_frequency(const LVec& samples) const;
long feature_minlabels(const LVec& samples, long feature) const;
long best_feature_gini(const LVec& samples, unsigned min_labels,
const LUMap& features_freq) const;
long best_feature_naive(const LVec& samples) const;
void update_tree(DecisionTree *tree, const LVec& samples);
DecisionTree* grow_tree(const LVec& samples);
DecisionTree* grow_tree(const LVec& samples, unsigned min_labels,
const LUMap& features_freq);
vector<DecisionTree*> forest;
long n_samples; // number of samples to consider per tree
long n_features; // number of features to consider per tree
double depweight;
bool prelearned;
Tfidf labels_ti;
mt19937 rng; // random number generator, in this case Mersenne twister
};
// TODO: seed hard-coded ...
RandomForest::RandomForest(const Rows& deps, const Rows& syms,
const Rows& sym_ths, long sym_num,
long n_trees, long n_samples, long n_features, double depweight)
: Predictor(deps, syms, sym_ths, sym_num), forest(n_trees, NULL),
n_samples(n_samples), n_features(n_features), depweight(depweight),
prelearned(false), labels_ti(deps.size()), rng(42) {
for (auto& tree : forest)
tree = new DecisionTree;
}
RandomForest::~RandomForest() {
for (auto& tree : forest)
delete tree;
}
void RandomForest::import_data(string dirname) {
for (unsigned i = 0; i < forest.size(); i++) {
delete forest[i];
forest[i] = new DecisionTree(dirname + "/tree" + to_string(i) + ".dot",
*names, *features);
}
prelearned = true;
}
void RandomForest::export_data(string dirname) const {
for (unsigned i = 0; i < forest.size(); i++)
forest[i]->write_to_file(dirname + "/tree" + to_string(i) + ".dot",
*names, *features);
}
void RandomForest::learn(long from, long to) {
// update TF-IDF information for labels
for (long i = from; i < to; i++)
labels_ti.add(deps[i]);
if (prelearned)
return;
// by how many trees will a sample be learnt
const long sampling_frequency = 1;
// determine which tree should learn which samples
LVecVec tree_samples(forest.size());
uniform_int_distribution<> tree_distr(0, forest.size() - 1);
for (long s = from; s < to; s++)
for (long n = 0; n < sampling_frequency; n++)
tree_samples[tree_distr(rng)].push_back(s);
for (unsigned t = 0; t < forest.size(); t++)
update_tree(forest[t], tree_samples[t]);
/*
// probability of sampling from the range [from, to), when we
// draw from [0, to)
double prob = (to - from) / double(to);
binomial_distribution<long> bin_dist(n_samples, prob);
uniform_int_distribution<long> uni_dist_old(0, from - 1);
uniform_int_distribution<long> uni_dist_new(from, to - 1);
for (auto& tree : forest) {
long n_new_samples = bin_dist(rng);
// update tree if we need to consider new samples
if (n_new_samples > 0) {
LVec samples_old(n_samples - n_new_samples);
LVec samples_new(n_new_samples);
for (auto& sample : samples_old) sample = uni_dist_old(rng);
for (auto& sample : samples_new) sample = uni_dist_new(rng);
samples_new.insert(samples_new.end(),
samples_old.begin(), samples_old.end());
// regrow
delete tree;
tree = grow_tree(samples_new);
}
}
*/
}
LDPairVec RandomForest::predict(const LVec& csyms, long maxth, long no_adv)
const {
LDPairVec ans = LDPairVec(maxth, make_pair(0, 0));
for (long i = 0; i < maxth; ++i) {
ans[i].first = i;
ans[i].second = 0;
}
LDMap labels;
for (const auto& tree : forest)
tree->query(csyms, labels);
/*
double tfidf_d = 1;
for (const auto& feature : positives)
// is a low TF-IDF better or worse?
// if low was better, we should probably divide here!
tfidf_d *= tfidf.get(feature);
long tfidf_l = tfidf_d * 1000.0;
//cout << tfidf_l << endl;
*/
for (const auto& label : labels) {
// this might be the case if we use a prelearned tree, and to prevent
// suggesting theorems "from the future", we discard them
if (!visible(label.first, maxth))
continue;
ans[label.first].second += label.second; // / pow(labels_ti.get(label), 1);
const Row ds = deps[label.first];
for (const auto& dep : ds) {
//cerr << dw / pow(labels_ti.get(dep), 3) << endl;
if (!visible(dep, maxth)) // a dependency from the future or out of scope
continue;
ans[dep].second += depweight * label.second; // / pow(labels_ti.get(dep), 4);
}
}
sort_prediction(ans, keep_visible(ans, no_adv));
return ans;
}
long RandomForest::n_of_samples_with_label(const LVec& samples, long label)
const {
long sum = 0;
for (const auto& sample : samples) {
const Row ds = deps[sample];
if (sample == label || find(ds.begin(), ds.end(), label) != ds.end())
sum++;
}
return sum;
}
pair<LUMap, long> RandomForest::labels_of_samples(const LVec& samples) const {
LUMap labels;
long n_labels = 0;
for (const auto& sample : samples) {
labels[sample]++;
n_labels++;
for (const auto& dep : deps[sample]) {
labels[dep]++;
n_labels++;
}
}
return make_pair(labels, n_labels);
}
double RandomForest::gini_part(const LVec& samples) const {
auto l = labels_of_samples(samples);
LUMap labels = l.first;
double n_labels = l.second;
double sum = 0.0;
for (const auto& label : labels) {
double p = n_of_samples_with_label(samples, label.first) / n_labels;
sum += (p - p*p) * label.second;
}
return samples.size() * sum;
}
double RandomForest::gini_index(const LVec& samples, long feature) const {
LVec yes, no;
for (const auto& sample : samples) {
const Row features = syms[sample];
if (find(features.begin(), features.end(), feature) != features.end())
yes.push_back(sample);
else
no.push_back(sample);
}
return gini_part(yes) + gini_part(no);
}
LUMap RandomForest::features_frequency(const LVec& samples) const {
LUMap features_freq;
for (const auto& sample : samples)
for (const auto& feature : syms[sample])
features_freq[feature]++;
return features_freq;
}
long RandomForest::feature_minlabels(const LVec& samples, long feature)
const {
LVec left, right;
for (const auto& sample : samples) {
const Row csyms = syms[sample];
if (find(csyms.begin(), csyms.end(), feature) != csyms.end())
left.push_back(sample);
else
right.push_back(sample);
}
return min(labels_of_samples(left ).second,
labels_of_samples(right).second);
}
template <class Container, class Generator> Container
sample_with_replacement(const Container& c, unsigned n, Generator& g) {
// generate sorted vector of container indices
vector<unsigned> indices(n);
uniform_int_distribution<> distr(0, c.size() - 1);
for (auto& i : indices) i = distr(g);
sort(indices.begin(), indices.end());
Container result;
auto citr = c.cbegin();
unsigned prev_i = 0;
for (const auto& i : indices) {
advance(citr, i - prev_i);
prev_i = i;
copy_n(citr, 1, inserter(result, result.end()));
}
return result;
}
long RandomForest::best_feature_gini(const LVec& samples, unsigned min_labels,
const LUMap& features_freq) const {
long best_f = -1;
double best_gini = 0;
// iterate through unique list of features
for (const auto& f : features_freq) {
// check if a feature even has a chance to provide a valid split
if (feature_minlabels(samples, f.first) >= (long)min_labels) {
double gini = gini_index(samples, f.first);
if (gini < best_gini || best_f == -1) {
best_f = f.first;
best_gini = gini;
}
}
}
return best_f;
}
long RandomForest::best_feature_naive(const LVec& samples) const {
LUMap ff = features_frequency(samples);
long optimal_n_samples = samples.size() / 2;
long best_f = -1;
long best_diff = 0;
for (const auto& f : ff) {
long diff = abs((long)(f.second - optimal_n_samples));
if (diff < best_diff || best_f == -1) {
best_f = f.first;
best_diff = diff;
}
}
return best_f;
}
void RandomForest::update_tree(DecisionTree *tree, const LVec& new_samples) {
if (new_samples.empty())
return;
for (const auto& sample : new_samples)
for (const auto& feature : syms[sample])
tree->features_freq[feature]++;
tree->n_samples += new_samples.size();
long optimal_n_samples = tree->n_samples / 2;
long best_f = -1;
long best_diff = 0;
// we have to consider all features present in the tree at this point,
// because it might be that a feature that was previously bad, now has
// become a good splitting feature, even if it did not appear at all
// in the new samples
for (const auto& f : tree->features_freq) {
long diff = abs((long)(f.second - optimal_n_samples));
if (diff < best_diff || best_f == -1) {
best_f = f.first;
best_diff = diff;
}
}
LVec update_samples = new_samples;
// no sample in the tree has a feature to split on, so the tree is a leaf
if (best_f == -1) {
tree->add_labels_recursively(update_samples);
delete tree->left;
delete tree->right;
tree->left = NULL;
tree->right = NULL;
tree->labels = update_samples;
tree->feature = -1;
return;
}
if (best_f != tree->feature) {
tree->add_labels_recursively(update_samples);
delete tree->left;
delete tree->right;
tree->left = new DecisionTree;
tree->right = new DecisionTree;
}
const Row best = sym_ths[best_f];
LVec left, right;
// divide samples into those which have the best feature and those who do not
for (const auto& sample : update_samples)
if (find(best.begin(), best.end(), sample) != best.end())
left.push_back(sample);
else
right.push_back(sample);
if (min(left .size() + tree->left ->n_samples,
right.size() + tree->right->n_samples) < 1) {
tree->labels = update_samples;
tree->feature = -1;
delete tree->left;
delete tree->right;
tree->left = NULL;
tree->right = NULL;
}
else {
tree->labels = LVec();
tree->feature = best_f;
update_tree(tree->left , left);
update_tree(tree->right, right);
}
}
DecisionTree* RandomForest::grow_tree(const LVec& samples) {
LUMap ff = features_frequency(samples);
// remove too seldomly occuring features
/*for (auto fi = ff.begin(); fi != ff.end(); )
if (fi->second <= 3) fi = ff.erase(fi);
else fi++;*/
LUMap fs = sample_with_replacement(ff, n_features, rng);
return grow_tree(samples, 1/*2*log(labels_of_samples(samples).second)*/, fs);
}
DecisionTree* RandomForest::grow_tree(const LVec& samples,
unsigned min_labels, const LUMap& features_freq) {
long best_f = best_feature_naive(samples);
//long best_f = best_feature_gini(samples, min_labels, features_freq);
if (best_f == -1)
return new DecisionTree(samples);
const Row best = sym_ths[best_f];
LVec left, right;
// divide samples into those which have the best feature and those who do not
for (const auto& sample : samples)
if (find(best.begin(), best.end(), sample) != best.end())
left.push_back(sample);
else
right.push_back(sample);
// stop growing tree if one of its children would be too small
if (min(labels_of_samples(left ).second,
labels_of_samples(right).second) < (long)min_labels)
return new DecisionTree(samples);
else {
DecisionTree *t_left = grow_tree(left , min_labels, features_freq);
DecisionTree *t_right = grow_tree(right, min_labels, features_freq);
return new DecisionTree(t_left, t_right, best_f);
}
}
// What rforest learns from a view: the forest a process started on the
// view's theorems grows, from tables of those theorems in the view's order,
// with features numbered by rank (View::ranks) as that process numbers them,
// so that the trees draw the same samples and split on the same features.
class RandomForestView : public ViewPredictor {
public:
RandomForestView(const View& view, long sym_num, long n_trees,
long n_samples, long n_features, double depweight);
LDPairVec predict_weighted(const LDPairVec& query,
const vector<char>* in_scope, long no_adv) const;
private:
const View& view;
Rows deps, syms, sym_ths; // as a process reads them, by rank
unique_ptr<RandomForest> forest;
};
RandomForestView::RandomForestView(const View& view, long sym_num,
long n_trees, long n_samples, long n_features, double depweight)
: view(view) {
const LVec table = view.rank_table(sym_num), ids = view.id_table();
sym_ths.resize(view.features());
deps.resize(view.size());
syms.resize(view.size());
long i = 0;
for (const auto v : view.versions)
for (const auto& s : v->syms) {
for (const auto d : view.deps_of(i, ids)) deps.push(i, d);
for (const auto f : ranks_in(s, table)) {
syms.push(i, f);
sym_ths.push(f, i);
}
++i;
}
forest.reset(new RandomForest(deps, syms, sym_ths, view.features(),
n_trees, n_samples, n_features, depweight));
forest->learn_all();
}
LDPairVec RandomForestView::predict_weighted(const LDPairVec& query,
const vector<char>* in_scope, long no_adv) const {
LVec csyms;
for (const auto& fw : query) csyms.push_back(view.rank_of(fw.first));
forest->set_scope(in_scope);
LDPairVec ans = forest->predict(csyms, view.size(), no_adv);
forest->set_scope(nullptr);
return ans;
}
#endif