Brush C++ API
A flexible interpretable machine learning framework
Loading...
Searching...
No Matches
inexact.h
Go to the documentation of this file.
1#ifndef INEXACT_H
2#define INEXACT_H
3
4#include "../init.h"
5#include "../types.h"
8#include "../util/utils.h"
9#include "../util/csv.h"
10#include "record.h"
11
12using namespace std;
13using Brush::Node;
14using Brush::DataType;
15
16namespace Brush { namespace Simpl{
17
19public:
20 HashStorage(int numPlanes=10) {
21 storage.clear();
22 storage.reserve(numPlanes);
23 for (int i = 0; i < numPlanes; ++i)
24 storage.push_back(map<size_t, vector<tree<Node>>>());
25 };
27
28 void append(const int& storage_n, const size_t& key, const tree<Brush::Node> Tree) {
29 // we initialize the list of equivalent vectors if it does not exist
30
31 if (storage[storage_n].find(key) == storage[storage_n].end())
32 storage[storage_n][key] = vector<tree<Node>>();
33
34 // if it is smaller we add to the front, otherwise we add to the back.
35 // This way we know the first element is the smallest one, and we don't care
36 // about the order of the rest of the elements.
37 auto& storage_it = storage[storage_n][key];
38
39 // calculating incoming tree's attributes to compare
40 size_t new_size = Tree.begin().node->get_size();
41
42 auto it = storage_it.begin();
43 for (; it != storage_it.end(); ++it) {
44 size_t curr_size = it->begin().node->get_size();
45
46 if (curr_size > new_size) {
47 // found insertion point, we dont need to look beyond this point
48 break;
49 } else if (curr_size == new_size) {
50 // Compare structure + contents
51 auto it1 = it->begin();
52 auto it2 = Tree.begin();
53
54 auto end1 = it->end();
55 auto end2 = Tree.end();
56
57 bool trees_equal = true;
58 for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
59 if (it1.node->data.get_node_hash(false)
60 != it2.node->data.get_node_hash(false) ){
61 trees_equal = false;
62 break;
63 }
64 }
65
66 if (trees_equal && it1 == end1 && it2 == end2) {
67 // both finished at same time and the look was not interrupted earlier.
68 // it means we already have the same exact tree (but maybe with a different coeff).
69 // lets pretend we inserted and just return
70 return;
71 }
72
73 // else keep scanning; insertion will be after last equal-size element
74 }
75 }
76
77 // Insert Tree in order by size, smallest first
78 storage_it.insert(it, Tree);
79 }
80
81 vector<tree<Node>> getList(const int& storage_n, const size_t& key) {
82 auto it = storage[storage_n].find(key);
83 if (it != storage[storage_n].end())
84 return it->second;
85
86 return {};
87 }
88
89 void clear() {
90 int numPlanes = storage.size();
91 storage.clear();
92 storage.resize(numPlanes);
93 }
94
95 vector<size_t> keys(const int& storage_n) {
96 vector<size_t> result;
97 for (const auto& pair : storage[storage_n])
98 result.push_back(pair.first);
99
100 return result;
101 }
102
104 void print(const vector<string>& prefix, Util::CsvWriter& log) const {
105 for (size_t plane_idx = 0; plane_idx < storage.size(); ++plane_idx) {
106 for (const auto& kv : storage[plane_idx]) {
107 size_t key = kv.first;
108 const auto& trees = kv.second;
109
110 for (const auto& t : trees) {
111 vector<string> row(prefix);
112 row.push_back(std::to_string(plane_idx));
113 row.push_back(std::to_string(key));
114 row.push_back(t.begin().node->get_model());
115 log.write_row(row);
116 }
117 }
118 }
119 }
120
121private:
122 // one storage instance for each plane
123 vector<map<size_t, vector<tree<Node>>>> storage;
124};
125
127{
128 public:
129 // static Inexact_simplifier* initSimplifier();
130 void init(int hashSize, const Dataset &data, int numPlanes);
131
132 // static void destroy();
133
134 // iterates through the tree, indexing it's nodes
135 template<ProgramType P>
137 const SearchSpace &ss, const Dataset &d)
138 {
139 // iterate over the tree, trying to replace each node with a constant, and keeping the change if the pred does not change.
140 TreeIter spot = program.Tree.begin_post();
141 while(spot != program.Tree.end_post())
142 {
143 // we dont index or simplify fixed stuff.
144 // non-wheightable nodes are not simplified. TODO: revisit this and see if they should (then implement it)
145 // This is avoiding using booleans.
146 if (spot.node->data.get_prob_change() > 0
147 // && IsWeighable(spot.node->data.ret_type) && IsWeighable(spot.node->data.node_type)
148 ) {
149 // indexing only small subtrees. We don't index constants (the constant simplifier will take
150 // care of them), but we index terminals, as they are weighted and may be added to different
151 // hash collections
152 if (program.size_at(spot, true) <= 30
154 {
155 index<P>(spot, d);
156 // terminals are already indexed on initialization
157 }
158 }
159 ++spot;
160 }
161 }
162
164 template<ProgramType P>
166 const SearchSpace &ss, const Dataset &d,
167 SimplificationRecords* records = nullptr)
168 {
169 // using RetType =
170 // typename // std::conditional_t<P == PT::Regressor, ArrayXf,
171 // // std::conditional_t<P == PT::Representer, ArrayXXf, ArrayXf
172 // >>;
173
174 analyze_tree(program, ss, d);
175
176 Program<P> simplified_program(program);
177
178 // prediction at the root already performs template cast and always returns a float
179 auto original_predictions = simplified_program.predict(d);
180
181 // iterate over the tree, trying to replace each node with a constant, and keeping the change if the pred does not change.
182 // notice it is a post order iterator.
183 TreeIter spot = simplified_program.Tree.begin_post();
184 while(spot != simplified_program.Tree.end_post())
185 {
186 // we dont index or simplify fixed stuff.
187 // non-wheightable nodes are not simplified. TODO: revisit this and see if they should (then implement it)
188 // This is avoiding using booleans.
189 // we do not simplify branches with fixed weights, because the simplification ignores the weight (it uses normalized predictions)
190 if (spot.node->data.get_prob_change() > 0 && !spot.node->data.weight_is_fixed
191 // && IsWeighable(spot.node->data.ret_type) && IsWeighable(spot.node->data.node_type)
192 ) {
193 // TODO: use IsLeaf here instead of checking for each possible nodetype. also search throughout the code and replace it
195
196 // res will return the closest within the threshold, so we dont have to check distance here
197
198 auto res = query<P>(spot, d); // optional<pair<int, size_T>>
199
200 if (res){
201 // for each res we replace the subtree and pick the one with the smallest error.
202 // we know they will be smaller because query only returns smaller trees. We also include
203 // the current node in the list of candidates so the model does not get worse.
204
205 float threshold = 1e-5;
206
207 float best_distance = threshold;
208 tree<Node> best_branch;
209 for (const auto& cand : res.value()) {
210
211 const tree<Node> original_branch(spot);
212 const tree<Node> simplified_branch(cand);
213
214 // auto original_predictions = simplified_program.predict(d);
215 // auto spot_pred = spot.node->template predict<spot.node->data.ret_type>(d);
216 // using RetType = decltype(spot_pred);
217
218 simplified_program.Tree.erase_children(spot);
219
220 spot = simplified_program.Tree.move_ontop(spot, simplified_branch.begin());
221
222 auto new_predictions = simplified_program.predict(d);
223
224 float diff = (original_predictions.template cast<float>() - new_predictions.template cast<float>()).square().mean();
225
226 if (diff < best_distance) {
227 best_distance = diff;
228 best_branch = cand;
229 }
230
231 // rollback
232 simplified_program.Tree.erase_children(spot);
233 spot = simplified_program.Tree.move_ontop(spot, original_branch.begin());
234 }
235 if (best_distance < threshold) {
236
237 string original;
238 if (records)
239 original = spot.node->get_model();
240
241 simplified_program.Tree.erase_children(spot);
242
243 const tree<Node> best_branch_copy(best_branch);
244
245 spot = simplified_program.Tree.move_ontop(spot, best_branch_copy.begin());
246
247 if (records)
248 records->push_back({0, 0, "inexact",
249 dt_to_string(spot.node->data.ret_type),
250 original, spot.node->get_model(),
251 best_distance});
252
253 // learning the simplifications made here
254 analyze_tree(simplified_program, ss, d);
255 }
256 }
257 }
258 }
259 ++spot;
260 }
261 program.Tree = simplified_program.Tree;
262
263 return simplified_program;
264 }
265
268
269 template<ProgramType P>
270 void index(TreeIter& spot, const Dataset &d)
271 {
272 const tree<Node> tree_copy(spot);
273
274 // cout << "indexing ...";
275 // cout << tree_copy.begin().node->get_model(true)
276 // << " with datatype " << static_cast<int>(tree_copy.begin().node->data.ret_type) << endl;
277
278 auto hashes = hash<P>(spot, d);
279
280 for (size_t i = 0; i < hashes.size(); ++i)
281 {
282 // hash() will clip the prediction to the inputDim, but here we store the full
283 // predictions so we can calculate the distance to the query point later in query()
284 equivalentExpressions[spot.node->data.ret_type].append(i, hashes[i], tree_copy);
285 }
286 }
287
288 // wrapper to print all equivalentExpressions
289 inline static const vector<string> simplification_table_header = {
290 "run_id", "DataType", "Plane", "Key", "Tree"};
291
294 inline void log_simplification_table(Util::CsvWriter& log, const string& run_id) {
295 for (const auto& kv : equivalentExpressions) {
296 DataType dt = kv.first;
297 const HashStorage& hs = kv.second;
298
299 hs.print({run_id, dt_to_string(dt)}, log);
300 }
301 }
302
303 int inputDim = 1000; // default value
304 private:
305 template<ProgramType P>
306 vector<size_t> hash(TreeIter& spot, const Dataset &d)
307 {
308 // returns one hash for each plane
309
310 using RetType =
311 typename std::conditional_t<P == PT::Regressor, ArrayXf,
312 std::conditional_t<P == PT::Representer, ArrayXXf, ArrayXf
313 >>;
314
315 // we cast to float because hash and query are based on matrix multiplications,
316 // but we will store the hash only on the corresponding storage instance
317 ArrayXf floatClippedInput;
318
319 if constexpr (P == PT::Representer) {
320 ArrayXXf inputPoint = (*spot.node).template predict<ArrayXXf>(d);
321 floatClippedInput = Eigen::Map<ArrayXf>(inputPoint.data(), inputPoint.size()).head(inputDim).template cast<float>();
322 } else {
323 if (spot.node->data.ret_type == DataType::ArrayB) {
324 ArrayXb inputPointB = (*spot.node).template predict<ArrayXb>(d);
325 floatClippedInput = inputPointB.template cast<float>();
326 }
327 else if (spot.node->data.ret_type == DataType::ArrayI) {
328 ArrayXi inputPointI = (*spot.node).template predict<ArrayXi>(d);
329 floatClippedInput = inputPointI.template cast<float>();
330 }
331 else {
332 floatClippedInput = (*spot.node).template predict<ArrayXf>(d);
333 }
334 }
335
336 // assert(floatClippedInput.size() >= inputDim &&
337 // "data must have at least inputDim elements");
338
339 // floatClippedInput = floatClippedInput.head(inputDim);
340
341 assert(floatClippedInput.size() == inputDim &&
342 "You need to pass a dataset with inputDim samples to the simplification.");
343
344 // Equalize floatClippedInput
345 float floatClippedInput_mean = floatClippedInput.mean();
346
347 // Check for NaN/Inf in mean - if present, skip simplification for this node.
348 // Otherwise, we are at changes of having wrong simplifications and terrible
349 // replacements due to numeric error.
350 if (std::isnan(floatClippedInput_mean) || std::isinf(floatClippedInput_mean)) {
351 return {}; // Return empty hashes to skip this node
352 }
353
354 floatClippedInput = floatClippedInput - floatClippedInput_mean;
355
356 // No need to check for NaN/Inf in the normalized predictions ---
357 // the mean is already a valid numeric value.
358
359 vector<size_t> hashes;
360 for (size_t planeIdx = 0; planeIdx < uniformPlanes.size(); ++planeIdx)
361 {
362 const auto& plane = uniformPlanes[planeIdx];
363 Eigen::ArrayXf projection = plane * floatClippedInput.matrix();
364 Eigen::Array<bool, Eigen::Dynamic, 1> comparison = (projection > 0);
365
366 size_t input_hash = 0;
367 for (int i = 0; i < comparison.size(); ++i) {
368 input_hash <<= 1;
369 input_hash |= comparison(i) ? 1 : 0;
370 }
371
372 hashes.push_back(input_hash);
373 }
374
375 return hashes;
376 }
377
378 template<ProgramType P>
379 optional<vector<tree<Node>>> query(TreeIter& spot, const Dataset &d)
380 {
381 // will return the hash and the distance to the queryPoint.
382
383 int spot_size = spot.node->get_size();
384
385 // first argument is the index of the plane, second is the hash
386 vector<tree<Node>> matches = {};
387
388 vector<size_t> hashes = hash<P>(spot, d);
389
390 for (int i = 0; i < hashes.size(); ++i){
391 // cout << "querying hashes index " << i
392 // << " with datatype " << static_cast<int>(spot.node->data.ret_type) << endl;
393
394 vector<tree<Node>> newCandidates = equivalentExpressions[spot.node->data.ret_type].getList(i, hashes[i]);
395
396 if (newCandidates.size() == 0)
397 continue;
398
399 int count = 0;
400 for (const auto& cand : newCandidates) {
401 if (cand.begin().node->get_size() < spot_size) {
402 matches.push_back(cand);
403 if (++count >= 25) break; // returning only top 10
404 } else {
405 // Since candidates are ordered by size, we can break early
406 break;
407 }
408 }
409 }
410
411 if (matches.size() > 0)
412 return matches;
413 return std::nullopt;
414 }
415
416 inline string dt_to_string(DataType dt) {
417 switch (dt) {
418 case DataType::ArrayB: return "ArrayB";
419 case DataType::ArrayI: return "ArrayI";
420 case DataType::ArrayF: return "ArrayF";
421 case DataType::MatrixB: return "MatrixB";
422 case DataType::MatrixI: return "MatrixI";
423 case DataType::MatrixF: return "MatrixF";
424 case DataType::TimeSeriesB: return "TimeSeriesB";
425 case DataType::TimeSeriesI: return "TimeSeriesI";
426 case DataType::TimeSeriesF: return "TimeSeriesF";
427 case DataType::ArrayBJet: return "ArrayBJet";
428 case DataType::ArrayIJet: return "ArrayIJet";
429 case DataType::ArrayFJet: return "ArrayFJet";
430 case DataType::MatrixBJet: return "MatrixBJet";
431 case DataType::MatrixIJet: return "MatrixIJet";
432 case DataType::MatrixFJet: return "MatrixFJet";
433 case DataType::TimeSeriesBJet: return "TimeSeriesBJet";
434 case DataType::TimeSeriesIJet: return "TimeSeriesIJet";
435 case DataType::TimeSeriesFJet: return "TimeSeriesFJet";
436 }
437 return "Unknown";
438 }
439
440 // one storage instance for each datatype/rettype.
441 // the storage will be used to calculate the hash and query the
442 // collection of hashes, returning the closest ones,
443 // and the list will contain equivalent expressions, ordered by size
444 // (or linear complexity). So we dont store pairs in the storage
445 std::unordered_map<DataType, HashStorage> equivalentExpressions;
446
447 vector<MatrixXf> uniformPlanes;
448};
449
450} // Simply
451} // Brush
452
453#endif
holds variable type data.
Definition data.h:51
vector< map< size_t, vector< tree< Node > > > > storage
Definition inexact.h:123
vector< tree< Node > > getList(const int &storage_n, const size_t &key)
Definition inexact.h:81
void append(const int &storage_n, const size_t &key, const tree< Brush::Node > Tree)
Definition inexact.h:28
vector< size_t > keys(const int &storage_n)
Definition inexact.h:95
HashStorage(int numPlanes=10)
Definition inexact.h:20
void print(const vector< string > &prefix, Util::CsvWriter &log) const
writes one row per stored tree: prefix..., plane, key, tree
Definition inexact.h:104
void log_simplification_table(Util::CsvWriter &log, const string &run_id)
dumps every stored expression. Expects a writer opened with simplification_table_header.
Definition inexact.h:294
string dt_to_string(DataType dt)
Definition inexact.h:416
optional< vector< tree< Node > > > query(TreeIter &spot, const Dataset &d)
Definition inexact.h:379
vector< size_t > hash(TreeIter &spot, const Dataset &d)
Definition inexact.h:306
vector< MatrixXf > uniformPlanes
Definition inexact.h:447
void index(TreeIter &spot, const Dataset &d)
Definition inexact.h:270
Program< P > simplify_tree(Program< P > &program, const SearchSpace &ss, const Dataset &d, SimplificationRecords *records=nullptr)
Definition inexact.h:165
void analyze_tree(Program< P > &program, const SearchSpace &ss, const Dataset &d)
Definition inexact.h:136
static const vector< string > simplification_table_header
Definition inexact.h:289
void init(int hashSize, const Dataset &data, int numPlanes)
Definition inexact.cpp:19
std::unordered_map< DataType, HashStorage > equivalentExpressions
Definition inexact.h:445
Minimal RFC 4180 CSV writer used by the run logs.
Definition csv.h:34
void write_row(const std::vector< std::string > &fields)
Definition csv.h:81
std::vector< SimplificationRecord > SimplificationRecords
Definition record.h:22
< nsga2 selection operator for getting the front
Definition bandit.cpp:3
auto Isnt(DataType dt) -> bool
Definition node.h:48
Eigen::Array< bool, Eigen::Dynamic, 1 > ArrayXb
Definition types.h:39
DataType
data types.
Definition types.h:143
tree< Node >::pre_order_iterator TreeIter
Eigen::Array< int, Eigen::Dynamic, 1 > ArrayXi
Definition types.h:40
STL namespace.
class holding the data for a node in a tree.
Definition node.h:89
An individual program, a.k.a. model.
Definition program.h:49
TreeType predict(const Dataset &d)
the standard predict function. Returns the output of the Tree directly.
Definition program.h:221
tree< Node > Tree
fitness
Definition program.h:72
int size_at(Iter &top, bool include_weight=true) const
count the size of a given subtree, optionally including the weights in weighted nodes....
Definition program.h:121
Holds a search space, consisting of operations and terminals and functions, and methods to sample tha...