-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathisolation_forest.cpp
More file actions
514 lines (430 loc) · 14.4 KB
/
Copy pathisolation_forest.cpp
File metadata and controls
514 lines (430 loc) · 14.4 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#include <vector>
#include <string>
#include <random>
#include <memory>
#include <unordered_map>
#include <cmath>
#include <Rcpp.h>
// #include <RcppParallel.h>
using namespace Rcpp;
// using namespace RcppParallel;
const double EM_CONSTANT = 0.5772156649; // Euler-Mascheroni constant
std::mt19937 gen(42); // Fixed random seed for reproducibility
// Define a structure for an Isolation Tree Node
struct IsolationTreeNode {
bool is_leaf;
int size;
std::string feature;
double value;
bool is_missing_split;
std::unique_ptr<IsolationTreeNode> left;
std::unique_ptr<IsolationTreeNode> right;
IsolationTreeNode(int s) : is_leaf(true), size(s), value(0), is_missing_split(false) {}
IsolationTreeNode(
std::string feat,
double val,
bool missing_split,
std::unique_ptr<IsolationTreeNode> l,
std::unique_ptr<IsolationTreeNode> r)
: is_leaf(false), size(0),
feature(std::move(feat)),
value(val), is_missing_split(missing_split),
left(std::move(l)), right(std::move(r)) {}
};
// Convert R DataFrame to C++ data structure
std::vector<std::unordered_map<std::string, double>> convert_dataframe(const DataFrame& df) {
std::vector<std::unordered_map<std::string, double>> data;
int n_rows = df.nrows();
CharacterVector col_names = df.names();
int n_cols = col_names.size();
for (int i = 0; i < n_rows; ++i) {
std::unordered_map<std::string, double> row;
for (int j = 0; j < n_cols; ++j) {
NumericVector col = df[j];
row[as<std::string>(col_names[j])] = col[i];
}
data.push_back(row);
}
return data;
}
// Function to create an isolation tree
std::unique_ptr<IsolationTreeNode> isolation_tree(
const std::vector<std::unordered_map<std::string, double>>& data,
int depth = 0, int max_depth = -1) {
int n = data.size();
if (max_depth == -1) {
max_depth = static_cast<int>(log2(n));
}
if (n <= 1 || depth >= max_depth) {
return std::make_unique<IsolationTreeNode>(n);
}
// Create vector of features to split on
std::vector<std::string> features;
for (const auto& [key, _] : data[0]) {
features.push_back(key);
}
std::uniform_int_distribution<> feature_dist(0, features.size() - 1);
std::string split_feature = features[feature_dist(gen)];
// Can split on numeric or missing value
double min_val = 0.0;
double max_val = 0.0;
bool has_missing = false;
bool has_valid = false;
for (const auto& row : data) {
double val = row.at(split_feature);
if (std::isnan(val)) {
has_missing = true;
continue;
}
if (!has_valid) {
min_val = val;
max_val = val;
has_valid = true;
} else {
min_val = std::min(min_val, val);
max_val = std::max(max_val, val);
}
}
if (!has_valid || (min_val == max_val && !has_missing)) {
return std::make_unique<IsolationTreeNode>(n);
}
// TODO: Chance to chose missing is 50/50. Could make less likely. Test
bool is_missing_split = false;
double split_value = 0.0;
if (has_missing && (std::bernoulli_distribution(0.5)(gen) || min_val == max_val)) {
is_missing_split = true;
} else {
std::uniform_real_distribution<> split_dist(min_val, max_val);
split_value = split_dist(gen);
}
std::vector<std::unordered_map<std::string, double>> left_data, right_data;
for (const auto& row : data) {
if (is_missing_split) {
if (std::isnan(row.at(split_feature))) {
left_data.push_back(row);
} else {
right_data.push_back(row);
}
} else {
if (row.at(split_feature) < split_value) {
left_data.push_back(row);
} else {
right_data.push_back(row);
}
}
}
return std::make_unique<IsolationTreeNode>(
split_feature, split_value, is_missing_split,
isolation_tree(left_data, depth + 1, max_depth),
isolation_tree(right_data, depth + 1, max_depth)
);
}
// Train an isolation forest
std::vector<std::unique_ptr<IsolationTreeNode>> isolation_forest(
const std::vector<std::unordered_map<std::string, double>>& data,
int n_trees,
int max_depth
) {
std::vector<std::unique_ptr<IsolationTreeNode>> forest;
forest.reserve(n_trees);
for (int i = 0; i < n_trees; ++i) {
forest.push_back(isolation_tree(data, 0, max_depth));
}
return forest;
}
// Compute path length of a single observation in a tree
int path_length(const IsolationTreeNode* node, const std::unordered_map<std::string, double>& obs, int depth = 0) {
if (node->is_leaf) {
return depth + node->size;
}
auto it = obs.find(node->feature);
if (it == obs.end()) {
return depth; // If feature is missing, return current depth
}
if (it->second < node->value) {
return path_length(node->left.get(), obs, depth + 1);
} else {
return path_length(node->right.get(), obs, depth + 1);
}
}
// Compute anomaly scores for data
// [[Rcpp::export]]
DataFrame calculate_anomaly_score(
DataFrame df,
int n_trees,
int max_depth
) {
std::vector<std::unordered_map<std::string, double>> data = convert_dataframe(df);
int n = data.size();
// Generate the forest
auto forest = isolation_forest(data, n_trees, max_depth);
// Compute average path lengths
std::vector<double> avg_path_length(n, 0.0);
for (int i = 0; i < n; ++i) {
double total_path_length = 0.0;
for (const auto& tree : forest) {
total_path_length += path_length(tree.get(), data[i]);
}
avg_path_length[i] = total_path_length / n_trees;
}
// Compute anomaly scores
double c_n = 2 * (log(n - 1) + EM_CONSTANT) - (2 * (n - 1) / n);
std::vector<double> scores(n);
for (int i = 0; i < n; ++i) {
scores[i] = std::pow(2, -(avg_path_length[i] / c_n));
}
// Return DataFrame with results
return DataFrame::create(
_["avg_depth"] = avg_path_length,
_["anomaly_score"] = scores
);
}
// #include <vector>
// #include <string>
// #include <random>
// #include <memory>
// #include <unordered_map>
// #include <cmath>
// #include <Rcpp.h>
// using namespace Rcpp;
// const double EM_CONSTANT = 0.5772156649; // Euler-Mascheroni constant
// std::mt19937 gen(42); // Fixed random seed for reproducibility
// struct IsolationTreeNode {
// bool is_leaf;
// int size;
// std::string feature;
// double value;
// bool is_missing_split;
// std::unique_ptr<IsolationTreeNode> left;
// std::unique_ptr<IsolationTreeNode> right;
// IsolationTreeNode(int s)
// : is_leaf(true),
// size(s),
// feature(""),
// value(0.0),
// is_missing_split(false),
// left(nullptr),
// right(nullptr) {}
// IsolationTreeNode(
// std::string feat,
// double val,
// bool missing_split,
// std::unique_ptr<IsolationTreeNode> l,
// std::unique_ptr<IsolationTreeNode> r
// )
// : is_leaf(false),
// size(0),
// feature(std::move(feat)),
// value(val),
// is_missing_split(missing_split),
// left(std::move(l)),
// right(std::move(r)) {}
// };
// std::vector<std::unordered_map<std::string, double>>
// convert_dataframe(const DataFrame& df) {
// std::vector<std::unordered_map<std::string, double>> data;
// int n_rows = df.nrows();
// CharacterVector col_names = df.names();
// int n_cols = col_names.size();
// data.reserve(n_rows);
// for (int i = 0; i < n_rows; ++i) {
// std::unordered_map<std::string, double> row;
// row.reserve(n_cols);
// for (int j = 0; j < n_cols; ++j) {
// NumericVector col = df[j];
// row[as<std::string>(col_names[j])] = col[i];
// }
// data.push_back(std::move(row));
// }
// return data;
// }
// std::unique_ptr<IsolationTreeNode>
// isolation_tree(
// const std::vector<std::unordered_map<std::string, double>>& data,
// int depth = 0,
// int max_depth = -1
// ) {
// int n = static_cast<int>(data.size());
// if (max_depth == -1) {
// max_depth = static_cast<int>(std::log2(n));
// }
// if (n <= 1 || depth >= max_depth) {
// return std::make_unique<IsolationTreeNode>(n);
// }
// std::vector<std::string> features;
// features.reserve(data[0].size());
// for (const auto& kv : data[0]) {
// features.push_back(kv.first);
// }
// std::uniform_int_distribution<> feat_dist(0, features.size() - 1);
// std::string split_feature = features[feat_dist(gen)];
// double min_val = data[0].at(split_feature);
// double max_val = min_val;
// int missing_count = 0;
// for (const auto& row : data) {
// double val = row.at(split_feature);
// if (std::isnan(val)) {
// missing_count++;
// continue;
// }
// min_val = std::min(min_val, val);
// max_val = std::max(max_val, val);
// }
// bool has_missing = (missing_count > 0);
// double missing_fraction =
// static_cast<double>(missing_count) / static_cast<double>(n);
// if (min_val == max_val && !has_missing) {
// return std::make_unique<IsolationTreeNode>(n);
// }
// // Calibrated missing split probability:
// // - rare missing -> rare split (more anomalous)
// // - common missing -> more missing splits (less anomalous)
// double p_miss = std::min(0.5, missing_fraction);
// bool is_missing_split = false;
// double split_value = 0.0;
// if (has_missing &&
// (std::bernoulli_distribution(p_miss)(gen) || min_val == max_val)) {
// is_missing_split = true;
// } else {
// std::uniform_real_distribution<> split_dist(min_val, max_val);
// split_value = split_dist(gen);
// }
// std::vector<std::unordered_map<std::string, double>> left_data;
// std::vector<std::unordered_map<std::string, double>> right_data;
// left_data.reserve(n);
// right_data.reserve(n);
// for (const auto& row : data) {
// double v = row.at(split_feature);
// if (is_missing_split) {
// if (std::isnan(v)) {
// left_data.push_back(row);
// } else {
// right_data.push_back(row);
// }
// } else {
// if (v < split_value) {
// left_data.push_back(row);
// } else {
// right_data.push_back(row);
// }
// }
// }
// return std::make_unique<IsolationTreeNode>(
// split_feature,
// split_value,
// is_missing_split,
// isolation_tree(left_data, depth + 1, max_depth),
// isolation_tree(right_data, depth + 1, max_depth)
// );
// }
// std::vector<std::unique_ptr<IsolationTreeNode>>
// isolation_forest(
// const std::vector<std::unordered_map<std::string, double>>& data,
// int n_trees,
// int max_depth
// ) {
// std::vector<std::unique_ptr<IsolationTreeNode>> forest;
// forest.reserve(n_trees);
// for (int i = 0; i < n_trees; ++i) {
// forest.push_back(isolation_tree(data, 0, max_depth));
// }
// return forest;
// }
// // IMPORTANT FIX: respect is_missing_split during traversal
// int path_length(
// const IsolationTreeNode* node,
// const std::unordered_map<std::string, double>& obs,
// int depth = 0
// ) {
// if (node->is_leaf) {
// return depth + node->size;
// }
// auto it = obs.find(node->feature);
// if (it == obs.end()) {
// // Feature absent from obs map. Fall back: stop at current depth.
// return depth;
// }
// double x = it->second;
// if (node->is_missing_split) {
// if (std::isnan(x)) {
// return path_length(node->left.get(), obs, depth + 1);
// }
// return path_length(node->right.get(), obs, depth + 1);
// }
// if (std::isnan(x)) {
// // Numeric split but x missing: choose a side deterministically.
// // Here: treat missing as going left.
// return path_length(node->left.get(), obs, depth + 1);
// }
// if (x < node->value) {
// return path_length(node->left.get(), obs, depth + 1);
// }
// return path_length(node->right.get(), obs, depth + 1);
// }
// // [[Rcpp::export]]
// DataFrame calculate_anomaly_score(DataFrame df, int n_trees, int max_depth) {
// std::vector<std::unordered_map<std::string, double>> data =
// convert_dataframe(df);
// int n = static_cast<int>(data.size());
// auto forest = isolation_forest(data, n_trees, max_depth);
// std::vector<double> avg_path_length(n, 0.0);
// for (int i = 0; i < n; ++i) {
// double total_path_length = 0.0;
// for (const auto& tree : forest) {
// total_path_length += path_length(tree.get(), data[i]);
// }
// avg_path_length[i] = total_path_length / static_cast<double>(n_trees);
// }
// double c_n = 2.0 * (std::log(n - 1.0) + EM_CONSTANT) -
// (2.0 * (n - 1.0) / n);
// std::vector<double> scores(n, 0.0);
// for (int i = 0; i < n; ++i) {
// scores[i] = std::pow(2.0, -(avg_path_length[i] / c_n));
// }
// return DataFrame::create(
// _["avg_depth"] = avg_path_length,
// _["anomaly_score"] = scores
// );
// }
// TODO: Parallelization would be faster within RcppParallel framework
// but requires setup and testing.
// Parallel task struct to process each data frame
// struct ParallelTask : public Worker {
// // Input list of data frames
// const List& df_list;
// int n_trees;
// int max_depth;
// // Output list to store results
// List& result;
//
// // Constructor to initialize the worker
// ParallelTask(const Rcpp::List& df_list, int n_trees, int max_depth, Rcpp::List& result)
// : df_list(df_list), n_trees(n_trees), max_depth(max_depth), result(result) {}
//
//
// // Function to process each individual task in parallel
// void operator()(std::size_t begin, std::size_t end) {
// for (std::size_t i = begin; i < end; ++i) {
// DataFrame df = Rcpp::as<DataFrame>(df_list[i]);
// std::vector<std::unordered_map<std::string, double>> data = convert_dataframe(df);
// Rcpp::DataFrame scores = calculate_anomaly_score(data,
// n_trees,
// max_depth);
// result[i] = scores;
// }
// }
// };
// Parallelized function to process a vector of data frames
// List train_anomaly_model(List df_list, int n_trees = 100,
// int max_depth = -1, int n_cores = 1) {
// int n = df_list.size();
// List result(n);
//
// // Create the ParallelTask object
// ParallelTask task(df_list, n_trees, max_depth, result);
//
// // Run the parallel task using parallelFor
// parallelFor(0, n, task);
//
// return result;
// }