Brush C++ API
A flexible interpretable machine learning framework
Loading...
Searching...
No Matches
engine.cpp
Go to the documentation of this file.
1#include "engine.h"
2
3#include <iostream>
4#include <fstream>
5#include <cmath>
6#include <chrono>
7#include <cstdio>
8#include <ctime>
9#include <random>
10
11namespace Brush{
12
13using namespace Pop;
14using namespace Sel;
15using namespace Eval;
16using namespace Var;
17using namespace MAB;
18
20template <ProgramType T>
22{
23 r.set_seed(params.get_random_state());
24
25 set_is_fitted(false);
26
27 this->pop = Population<T>();
28 this->evaluator = Evaluation<T>();
29 this->selector = Selection<T>(params.sel, false);
30 this->survivor = Selection<T>(params.surv, true);
31
32 this->archive.set_objectives(params.get_objectives());
33
34 timer.Reset();
35
36 // reset statistics
37 this->stats = Log_Stats();
38}
39
40template <ProgramType T>
41void Engine<T>::print_progress(float percentage)
42{
43 int val = (int) (percentage * 100);
44 int lpad = (int) (percentage * PBWIDTH);
45 int rpad = PBWIDTH - lpad;
46
47 printf ("\rCompleted %3d%% [%.*s%*s]", val, lpad, PBSTR.c_str(), rpad, "");
48
49 fflush (stdout);
50
51 if(val == 100)
52 cout << "\n";
53}
54
55
56template <ProgramType T>
57typename Engine<T>::PopSummary Engine<T>::summarize(const vector<size_t>& indices) const
58{
59 const size_t n = indices.size();
60
61 ArrayXf scores(n);
62 ArrayXf scores_v(n);
63 ArrayXi sizes(n);
64 ArrayXi complexities(n);
65
66 int index = 0; // counter for population size of valid individuals
67 for (const size_t population_index : indices)
68 {
69 if (population_index >= this->pop.individuals.size()) {
71 "Invalid population index " + to_string(population_index)
72 + " (individuals size=" + to_string(this->pop.individuals.size()) + ")");
73 }
74
75 const auto& p = this->pop.individuals.at(population_index);
76
77 // Skip nullptr individuals (offspring slots not yet filled)
78 if (!p)
79 continue;
80
81 float fitness_loss = 0.0f;
82 float fitness_loss_v = 0.0f;
83 unsigned individual_size = 0;
84 unsigned individual_complexity = 0;
85
86 // If the logger fails, it is easier to catch what have gone wrong
87 try {
88 fitness_loss = p->fitness.get_loss();
89 fitness_loss_v = p->fitness.get_loss_v();
90 individual_size = p->get_size();
91 individual_complexity = p->get_complexity();
92
93 } catch (const std::exception& e) {
95 "Failed to get fitness/size/complexity from individual at population index "
96 + to_string(population_index) + ": " + e.what());
97
98 } catch (...) {
100 "Failed to get fitness/size/complexity from individual at population index "
101 + to_string(population_index) + ": unknown error");
102
103 }
104
105 if (!std::isfinite(fitness_loss) || !std::isfinite(fitness_loss_v)) {
107 "Invalid non-finite fitness values at population index "
108 + to_string(population_index));
109 }
110
111 scores(index) = fitness_loss;
112 scores_v(index) = fitness_loss_v;
113 sizes(index) = individual_size;
114 complexities(index) = individual_complexity;
115 ++index;
116 }
117
118 // index now contains the actual count of non-null individuals
119 // Resize arrays to only include valid individuals
120 scores.conservativeResize(index);
121 scores_v.conservativeResize(index);
122 sizes.conservativeResize(index);
123 complexities.conservativeResize(index);
124
125 PopSummary s;
126 s.n_individuals = index;
127 if (index == 0)
128 return s;
129
130 // Multiply by weight to make it a maximization problem.
131 // Then, multiply again to get rid of signal
132 float error_weight = Individual<T>::weightsMap[params.scorer];
133
134 s.best_score = (scores*error_weight).maxCoeff()*error_weight;
135 s.best_score_v = (scores_v*error_weight).maxCoeff()*error_weight;
136 s.med_score = median(scores);
137 s.med_score_v = median(scores_v);
138 s.med_size = median(sizes);
139 s.med_complexity = median(complexities);
140 s.max_size = sizes.maxCoeff();
141 s.max_complexity = complexities.maxCoeff();
142
143 return s;
144}
145
146template <ProgramType T>
148{
149 if (params.num_islands < 0) {
150 HANDLE_ERROR_THROW("Invalid params.num_islands: cannot be negative");
151 }
152 if (static_cast<size_t>(params.num_islands) > pop.island_indexes.size()) {
154 "params.num_islands is greater than pop.island_indexes size in calculate_stats");
155 }
156
157 vector<size_t> indices;
158 for (int island=0; island<params.num_islands; ++island)
159 {
160 const auto& island_indices = pop.island_indexes.at(island);
161 indices.insert(indices.end(), island_indices.begin(), island_indices.end());
162 }
163
164 PopSummary s = summarize(indices);
165
166 // the best validation score is the one of the best individual, which is
167 // not necessarily the smallest validation loss in the population
168 float best_score_v = this->best_ind.fitness.get_loss_v();
169
170 if (!std::isfinite(best_score_v)) {
171 HANDLE_ERROR_THROW("Invalid non-finite validation loss in best_ind while calculating stats");
172 }
173
174 // update stats
175 stats.update(params.current_gen,
176 timer.Elapsed().count(),
177 s.best_score,
178 best_score_v,
179 s.med_score,
180 s.med_score_v,
181 s.med_size,
183 s.max_size,
185}
186
187namespace {
190 string make_run_id()
191 {
192 auto now = std::chrono::system_clock::now();
193 std::time_t t = std::chrono::system_clock::to_time_t(now);
194 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
195 now.time_since_epoch()).count() % 1000;
196
197 std::tm tm{};
198 localtime_r(&t, &tm);
199
200 std::random_device rd;
201 char buf[48];
202 std::snprintf(buf, sizeof(buf), "%04d%02d%02dT%02d%02d%02d.%03d-%04x",
203 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
204 tm.tm_hour, tm.tm_min, tm.tm_sec, static_cast<int>(ms),
205 static_cast<unsigned>(rd() & 0xffff));
206 return buf;
207 }
208}
209
210template <ProgramType T>
212{
213 run_id = make_run_id();
214
215 // run metadata: one json object per line, one line per call to fit
216 {
217 std::ofstream runs(params.logfile + "_runs.jsonl", std::ofstream::app);
218 if (!runs.is_open())
219 HANDLE_ERROR_THROW("Failed to open logfile: " + params.logfile + "_runs.jsonl");
220
221 json j;
222 j["run_id"] = run_id;
223 j["random_state"] = params.random_state;
224 j["params"] = params;
225 runs << j.dump() << "\n";
226 }
227
228 log_generations.open(params.logfile, {
229 "run_id", "random_state", "generation", "time",
230 "best_score", "best_score_val", "med_score", "med_score_val",
231 "med_size", "med_complexity", "max_size", "max_complexity",
232 "best_size", "best_complexity",
233 "stall_count", "archive_size", "n_evaluations",
234 "best_model"});
235
236 log_islands.open(params.logfile + "_islands.csv", {
237 "run_id", "generation", "island", "n_individuals",
238 "best_score", "best_score_val", "med_score", "med_score_val",
239 "med_size", "med_complexity", "max_size", "max_complexity"});
240
241 log_simplifications.open(params.logfile + "_simplifications.csv", {
242 "run_id", "generation", "individual_id", "simplifier", "ret_type",
243 "original", "replacement", "distance"});
244}
245
246template <ProgramType T>
247void Engine<T>::log_stats(unsigned stall_count, const SimplificationRecords& simplifications)
248{
249 using F = Util::CsvWriter;
250
252 run_id,
253 F::field(params.random_state),
254 F::field(params.current_gen),
255 F::field(timer.Elapsed().count()),
256 F::field(stats.best_score.back()),
257 F::field(stats.best_score_v.back()),
258 F::field(stats.med_score.back()),
259 F::field(stats.med_score_v.back()),
260 F::field(stats.med_size.back()),
261 F::field(stats.med_complexity.back()),
262 F::field(stats.max_size.back()),
263 F::field(stats.max_complexity.back()),
264 F::field(best_ind.get_size()),
265 F::field(best_ind.get_complexity()),
266 F::field(stall_count),
267 F::field(archive.individuals.size()),
268 F::field(evaluator.n_evaluations),
269 best_ind.program.get_model()
270 });
271
272 for (int island = 0; island < params.num_islands; ++island)
273 {
274 PopSummary s = summarize(pop.get_island_indexes(island));
275 log_islands.write_row({
276 run_id,
277 F::field(params.current_gen),
278 F::field(island),
279 F::field(s.n_individuals),
280 F::field(s.best_score),
281 F::field(s.best_score_v),
282 F::field(s.med_score),
283 F::field(s.med_score_v),
284 F::field(s.med_size),
285 F::field(s.med_complexity),
286 F::field(s.max_size),
287 F::field(s.max_complexity)
288 });
289 }
290
291 for (const auto& rec : simplifications)
292 {
293 log_simplifications.write_row({
294 run_id,
295 F::field(rec.generation),
296 F::field(rec.individual_id),
297 rec.simplifier,
298 rec.ret_type,
299 rec.original,
300 rec.replacement,
301 F::field(rec.distance)
302 });
303 }
304}
305
306template <ProgramType T>
308{
309 log_generations.close();
310 log_islands.close();
311 log_simplifications.close();
312}
313
314template <ProgramType T>
315void Engine<T>::print_stats(float fraction)
316{
317 // progress bar
318 string bar, space = "";
319 for (unsigned int i = 0; i<50; ++i)
320 {
321 if (i <= 50*fraction) bar += "/";
322 else space += " ";
323 }
324
325 std::cout.precision(5);
326 std::cout << std::scientific;
327
328 if(params.max_time == -1)
329 std::cout << "Generation " << params.current_gen+1 << "/"
330 << params.max_gens << " [" + bar + space + "]\n";
331 else
332 std::cout << std::fixed << "Time elapsed "<< timer
333 << "/" << params.max_time
334 << " seconds (Generation "<< params.current_gen+1
335 << ") [" + bar + space + "]\n";
336
337 std::cout << std::fixed
338 << "Best model on Val:" << best_ind.program.get_model() << "\n"
339 << "Train Loss (Med): " << stats.best_score.back() << " (" << stats.med_score.back() << ")\n"
340 << "Val Loss (Med): " << stats.best_score_v.back() << " (" << stats.med_score_v.back() << ")\n"
341 << "Median Size (Max): " << stats.med_size.back() << " (" << stats.max_size.back() << ")\n"
342 << "Median complexity (Max): " << stats.med_complexity.back() << " (" << stats.max_complexity.back() << ")\n"
343 << "Time (s): " << timer
344 <<"\n\n";
345}
346
347template <ProgramType T>
349{
350 vector<json> archive_vector;
351 for (const auto& ind : archive.individuals) {
352 json j;
353 to_json(j, ind);
354 archive_vector.push_back(j);
355 }
356
357 return archive_vector;
358}
359
360// TODO: dont have a get_pop and get_serialized_pop --> make them the same name but overloaded.
361// Also fix this in the pybind wrapper
362template <ProgramType T>
364{
365 vector<json> pop_vector;
366 for (const auto& ind : pop.individuals) {
367 if (ind == nullptr) {
368 // HANDLE_ERROR_THROW("get_population found a nullptr individual");
369 continue;
370 }
371
372 json j;
373 to_json(j, *ind);
374 pop_vector.push_back(j);
375 }
376
377 // Note: pop_vector.size() may be less than pop_size during evolution
378 // when offspring slots (nullptrs) haven't been filled by variation yet.
379 // This is a valid transient state and should not throw an error.
380
381 return pop_vector;
382}
383
384template <ProgramType T>
385vector<Individual<T>> Engine<T>::get_archive()
386{
387 vector<Individual<T>> archive_vector;
388 for (const auto& ind : archive.individuals) {
389 archive_vector.push_back(ind);
390 }
391
392 return archive_vector;
393}
394
395template <ProgramType T>
396vector<Individual<T>> Engine<T>::get_population()
397{
398 vector<Individual<T>> pop_vector;
399 for (const auto& ind : pop.individuals) {
400 if (ind == nullptr) {
401 continue;
402 }
403 pop_vector.push_back(*ind);
404 }
405
406 // Note: pop_vector.size() may be less than pop_size during evolution
407 // when offspring slots (nullptrs) haven't been filled by variation yet.
408 // This is a valid transient state and should not throw an error.
409
410 return pop_vector;
411}
412
413template <ProgramType T>
414void Engine<T>::set_population_from_json(vector<json> pop_vector)
415{
416 vector<Individual<T>> new_pop;
417
418 // load serialized individuals
419 for (const auto& ind_j : pop_vector) {
420 Individual<T> ind;
421
422 // deserialize individual
423 from_json(ind_j, ind);
424
425 // set reference to search space
427
428 new_pop.push_back(ind);
429 }
430
431 // check if size matches
432 if(new_pop.size() != params.pop_size)
433 HANDLE_ERROR_THROW("set_population size is different from params.pop_size");
434
435 // re-initialize population
436 this->pop.init(new_pop, params);
437}
438
439template <ProgramType T>
441{
442 vector<Individual<T>> new_pop;
443 for (const auto& ind_j : pop_vector) {
444 Individual<T> ind;
445 ind.program = ind_j.program;
446 ind.set_objectives(ind_j.get_objectives());
447
448 new_pop.push_back(ind);
449 }
450
451 if(new_pop.size() != params.pop_size)
452 HANDLE_ERROR_THROW("set_population size is different from params.pop_size");
453
454 this->pop.init(new_pop, params);
455}
456
457
458template <ProgramType T>
459void Engine<T>::lock_nodes(int end_depth, bool keep_leaves_unlocked, bool keep_current_weights)
460{
461 // iterate over the population, locking the program's tree nodes
462 for (int island=0; island<pop.num_islands; ++island) {
463 auto indices = pop.get_island_indexes(island);
464
465 for (unsigned i = 0; i<indices.size(); ++i)
466 {
467 const auto& ind = pop.individuals.at(indices.at(i));
468
469 // Skip nullptr individuals (offspring slots not yet filled)
470 if (!ind)
471 continue;
472
473 ind->program.lock_nodes(end_depth, keep_leaves_unlocked, keep_current_weights);
474 }
475 }
476}
477
478template <ProgramType T>
480{
481 bool updated = false;
482 bool passed;
483
484 vector<size_t> merged_islands(0);
485 for (int j=0;j<pop.num_islands; ++j)
486 {
487 auto indices = pop.island_indexes.at(j);
488 for (int i=0; i<indices.size(); ++i)
489 {
490 merged_islands.push_back(indices.at(i));
491 }
492 }
493
494 for (int i=0; i < merged_islands.size(); ++i)
495 {
496 const auto& ind_ptr = pop.individuals.at(merged_islands[i]);
497
498 // Skip nullptr individuals (offspring slots not yet filled)
499 if (!ind_ptr)
500 continue;
501
502 const auto& ind = *ind_ptr;
503
504 // TODO: use intermediary variables for wvalues
505 // Iterate over the weighted values to compare (everything is a maximization problem here)
506 passed = false;
507 for (size_t j = 0; j < ind.fitness.get_wvalues().size(); ++j) {
508 if (ind.fitness.get_wvalues()[j] > this->best_ind.fitness.get_wvalues()[j]) {
509 passed = true;
510 break;
511 }
512 if (ind.fitness.get_wvalues()[j] < this->best_ind.fitness.get_wvalues()[j]) {
513 // it is not better, and it is also not equal. So, it is worse. Stop here.
514 break;
515 }
516 // if no break, then its equal, so we keep going
517 }
518
519 if (passed)
520 {
521 this->best_ind = ind;
522 updated = true;
523 }
524 }
525
526 return updated;
527}
528
529
530template <ProgramType T>
532{
533 // All learning-time state is derived from the training partition. The
534 // original dataset remains the source of the fixed validation partition.
535 Dataset training = data.get_training_data();
536 training.set_batch_size(params.batch_size);
537 Dataset validation = data.get_validation_data();
538
539 // avoid re-initializing stuff so we can perform partial fits
540 if (!this->is_fitted){
541 //TODO: i need to make sure i initialize everything (pybind needs to have constructors
542 // without arguments to work, and i need to handle correcting these values before running)
543
544 // initializing classes that need data references
545 this->ss.init(training, params.functions, params.weights_init);
546
547 // TODO: make init to take necessary arguments and perform all initializations inside that function
548 this->init();
549
550 if (params.load_population != "") {
551 this->pop.load(params.load_population);
552 }
553 else if (this->pop.individuals.size() == 0)
554 {
555 // This only works because the Population constructor resizes individuals to zero.
556 this->pop.init(this->ss, this->params);
557 }
558 }
559
560 // TODO: Should I refit them? or use the values at it is? (the fitness WILL BE recalculated regardless)
561 // invalidating all individuals (so they are fitted with current data)
562 // for (auto& individual : this->pop.individuals) {
563 // if (individual != nullptr) {
564 // // will force re-fit and calc all fitness information
565 // individual->set_is_fitted(false);
566 // }
567 // }
568
569 // This is data dependent so we initialize it everytime, regardless of partial fit
570 // TODO: make variator have a default constructor and make it an attribute of engine
571 Variation<T> variator = Variation<T>(this->params, this->ss, training);
572
573 if (!params.logfile.empty())
574 open_logs();
575
576 evaluator.set_scorer(params.scorer);
577
578 // Batch samples are drawn from training data only. Keep the hold-out set
579 // separate so it stays fixed for validation throughout the run.
580 Dataset batch = training;
581 Dataset* fixed_validation = data.use_validation ? &validation : nullptr;
582
583 int threads;
584 if (params.n_jobs == -1)
585 threads = std::thread::hardware_concurrency();
586 else if (params.n_jobs == 0)
587 threads = params.num_islands;
588 else
589 threads = params.n_jobs;
590
591 tf::Executor executor(threads);
592
593 assert( (executor.num_workers() > 0) && "Invalid number of workers");
594
595 tf::Taskflow taskflow;
596
597 // stop criteria
598 unsigned generation = 0;
599 unsigned stall_count = 0;
600 float fraction = 0;
601
602 auto stop = [&]() {
603 bool condition = ( (generation == params.max_gens)
604 || (params.max_stall != 0 && stall_count > params.max_stall)
605 || (params.max_time != -1 && timer.Elapsed().count() > params.max_time)
606 );
607
608 return condition;
609 };
610
611 // TODO: check that I dont use pop.size() (or I use correctly, because it will return the size with the slots for the offspring)
612 // vectors to store each island separatedly
613 vector<vector<size_t>> island_parents;
614
615 island_parents.clear();
616 island_parents.resize(pop.num_islands);
617
618 for (int i=0; i< params.num_islands; i++){
619 size_t idx_start = std::floor(i*params.pop_size/params.num_islands);
620 size_t idx_end = std::floor((i+1)*params.pop_size/params.num_islands);
621
622 auto delta = idx_end - idx_start;
623
624 island_parents.at(i).clear();
625 island_parents.at(i).resize(delta);
626 }
627
628 // heavily inspired in https://github.com/heal-research/operon/blob/main/source/algorithms/nsga2.cpp
629 auto [init, cond, body, back, done] = taskflow.emplace(
630 [&](tf::Subflow& subflow) {
631 // Fitting an island mutates program weights. Keep that phase in
632 // a stable order as well, so the first selection sees identical
633 // fitness values for repeated seeded runs.
634 auto fit_init_pop = subflow.emplace([&]() {
635 // The initial population has no fitted weights. Use the first
636 // representative batch rather than fitting every program on
637 // the whole training partition before evolution starts.
638 batch = training.get_batch();
639 for (int island = 0; island < this->params.num_islands; ++island) {
640 evaluator.update_fitness(this->pop, island, batch, params,
641 true, true, true, fixed_validation);
642 }
643 });
644 auto find_init_best = subflow.emplace([&]() {
645 // Make sure we initialize it. We do this update here because we need to
646 // have the individuals fitted before we can compare them. When update_best
647 // is called, we are garanteed that the individuals are fitted and have valid
648 // fitnesses.
649 this->best_ind = *pop.individuals.at(0);
650 this->update_best(); // at this moment we dont care about update_best return value
651 });
652 fit_init_pop.precede(find_init_best);
653 }, // init (entry point for taskflow)
654
655 stop, // loop condition
656
657 [&](tf::Subflow& subflow) { // loop body (evolutionary main loop)
658 auto prepare_gen = subflow.emplace([&]() {
659 params.set_current_gen(generation);
660 batch = training.get_batch(); // returns all training data when batching is disabled
661 }).name("prepare generation");// set generation in params, get batch
662
663 // Selection consumes the process-wide random stream. Keep island
664 // selection ordered: Taskflow workers are not OpenMP workers, so
665 // using their scheduling order would otherwise make a fixed seed
666 // nondeterministic. Initial fitness evaluation is ordered too,
667 // so the complete seeded evolutionary path is scheduler-neutral.
668 auto run_generation = subflow.emplace([&]() {
669 // Lexicase samples case indices from the score dataset. Its
670 // sample weights must therefore have the same length as the
671 // current batch, not the full training partition.
672 Parameters selection_params = params;
673 if (params.classification)
674 selection_params.set_sample_weights(batch.y);
675
676 for (int island = 0; island < this->params.num_islands; ++island) {
677
678 // Refit each surviving program on this generation's batch.
679 // Parent selection uses batch fitness while validation always
680 // uses the original, fixed hold-out partition.
681 evaluator.update_fitness(this->pop, island, batch, params,
682 true, false, true, fixed_validation);
683
684 vector<size_t> parents = selector.select(
685 this->pop, island, selection_params);
686 island_parents.at(island) = std::move(parents);
687
688 this->pop.add_offspring_indexes(island);
689 }
690 }).name("runs one generation at each island in deterministic order");
691
692 auto update_pop = subflow.emplace([&]() { // sync point
693 // Variation is not thread safe.
694 // TODO: optimize this and make it work with multiple islands in parallel.
695 for (int island = 0; island < this->params.num_islands; ++island) {
696
697 // TODO: do I have to pass data as an argument here? or can I use the instance reference.
698 // OBS: this function already calls fit internally!
699 variator.vary_and_update(this->pop, island, island_parents.at(island),
700 batch, evaluator,
701
702 // conditions to apply simplification.
703 // It starts only on the second half of generations.
704 // Also, we garantee that the final generation
705 // will be simplified.
706 (generation>=params.max_gens/2) || (stall_count == params.max_stall) || (generation==params.max_gens-1),
707 fixed_validation
708 );
709 }
710
711 // select survivors from combined pool of parents and offspring.
712 // if the same individual exists in different islands, then it will be selected several times and the pareto front will have less diversity.
713 // to avoid this, survive should be unified
714 // TODO: survivor should still take params?
715 // TODO: RETURN SINGLE VECTOR and stop wrapping it into a single-element vector
716
717 auto survivor_indices = survivor.survive(this->pop, 0, params);
718
719 // TODO: do i need these next this-> pointers?
720 variator.update_ss();
721 this->pop.update({survivor_indices});
722 this->pop.migrate();
723 }).name("update, migrate and disentangle indexes between islands");
724
725 auto finish_gen = subflow.emplace([&]() {
726 // Set validation loss before calling update best
727 for (int island = 0; island < this->params.num_islands; ++island) {
728 // Keep batch fitness for evolution but replace the fitness
729 // values used by the archive and best-model selection with
730 // scores from the fixed, complete validation partition.
731 evaluator.update_fitness(this->pop, island, batch, params,
732 false, true, false, fixed_validation);
733 }
734
735 archive.update(pop, params);
736
737 bool updated_best = this->update_best();
738
739 fraction = params.max_time == -1 ? ((generation+1)*1.0)/params.max_gens :
740 timer.Elapsed().count()/params.max_time;
741
742 if ( params.verbosity>1 || !params.logfile.empty()) {
744 }
745
746 if(params.verbosity>1)
747 print_stats(fraction);
748 else if(params.verbosity == 1)
749 print_progress(fraction);
750
751 if (generation == 0 || updated_best )
752 stall_count = 0;
753 else
754 ++stall_count;
755
756 if (!params.logfile.empty())
757 log_stats(stall_count, variator.pop_simplification_records());
758
759 ++generation;
760
761 }).name("update best, update ss, log, archive, stall");
762
763 // set-up subflow graph
764 prepare_gen.precede(run_generation);
765 run_generation.precede(update_pop);
766 update_pop.precede(finish_gen);
767 },
768
769 [&]() { return 0; }, // jump back to the next iteration
770
771 [&](tf::Subflow& subflow) {
772 // Keep the final batch-fitted weights and fixed validation scores;
773 // do not add a full-training pass after evolution ends.
774 for (int island = 0; island < this->params.num_islands; ++island) {
775 evaluator.update_fitness(this->pop, island, batch, params,
776 false, true, false, fixed_validation);
777 }
778
779 archive.update(pop, params);
780 // calculate_stats();
781
782 if (params.save_population != "")
783 this->pop.save(params.save_population);
784
785 set_is_fitted(true);
786
787 // dump the expressions stored by the inexact simplifier
788 if (!params.logfile.empty() && params.inexact_simplification) {
789 Util::CsvWriter log_simplification_table(
790 params.logfile+"_simplification_table",
792 variator.log_simplification_table(log_simplification_table, run_id);
793 }
794
795 if (!params.logfile.empty())
796 close_logs();
797
798 // getting the updated versions
799 this->ss = variator.search_space;
800 this->params = variator.parameters;
801
802 } // work done, report last gen and stop
803 ); // evolutionary loop
804
805 init.name("init");
806 cond.name("termination");
807 body.name("main loop");
808 back.name("back");
809 done.name("done");
810 taskflow.name("island_gp");
811
812 init.precede(cond);
813 cond.precede(body, done);
814 body.precede(back);
815 back.precede(cond);
816
817 executor.run(taskflow);
818 executor.wait_for_all();
819
820 //When you have tasks that are created at runtime (e.g., subflow,
821 // cudaFlow), you need to execute the graph first to spawn these tasks and dump the entire graph.
822}
823}
824
holds variable type data.
Definition data.h:51
Dataset get_validation_data() const
Definition data.cpp:384
Dataset get_batch() const
Select the next batch without replacement. Classification batches preserve the prevalence of the rema...
Definition data.cpp:185
bool use_validation
Definition data.h:98
ArrayXf y
length N array, the target label
Definition data.h:90
Dataset get_training_data() const
Definition data.cpp:383
void set_batch_size(float new_size)
Definition data.cpp:550
The Engine class represents the core engine of the brush library.
Definition engine.h:44
string run_id
identifies the rows of one call to fit
Definition engine.h:170
Selection< T > selector
selection algorithm
Definition engine.h:147
Timer timer
start time of training
Definition engine.h:153
bool is_fitted
keeps track of whether fit was called
Definition engine.h:145
void calculate_stats()
Definition engine.cpp:147
Individual< T > best_ind
best individual found during training
Definition engine.h:141
void print_progress(float percentage)
Definition engine.cpp:41
void run(Dataset &d)
train the model
Definition engine.cpp:531
void close_logs()
Definition engine.cpp:307
Log_Stats stats
runtime stats
Definition engine.h:151
Archive< T > archive
pareto front archive
Definition engine.h:142
Population< T > pop
population of programs
Definition engine.h:143
void set_population(vector< Individual< T > > pop_vector)
Definition engine.cpp:440
Util::CsvWriter log_islands
<logfile>_islands.csv
Definition engine.h:172
Selection< T > survivor
survival algorithm
Definition engine.h:149
void print_stats(float fraction)
Definition engine.cpp:315
void log_stats(unsigned stall_count, const SimplificationRecords &simplifications)
Definition engine.cpp:247
Util::CsvWriter log_generations
<logfile>
Definition engine.h:171
void set_is_fitted(bool f)
set flag indicating whether fit has been called
Definition engine.h:182
PopSummary summarize(const vector< size_t > &indices) const
Definition engine.cpp:57
vector< json > get_archive_as_json()
return archive/population as strings
Definition engine.cpp:348
Util::CsvWriter log_simplifications
<logfile>_simplifications.csv
Definition engine.h:173
void lock_nodes(int end_depth=0, bool keep_leaves_unlocked=true, bool keep_current_weights=false)
Definition engine.cpp:459
Evaluation< T > evaluator
evaluation code
Definition engine.h:148
void open_logs()
Definition engine.cpp:211
Parameters params
hyperparameters of brush, which the user can interact
Definition engine.h:138
vector< Individual< T > > get_population()
Definition engine.cpp:396
void init()
initialize Feat object for fitting.
Definition engine.cpp:21
vector< json > get_population_as_json()
Definition engine.cpp:363
vector< Individual< T > > get_archive()
return archive/popularion as individuals ready to use
Definition engine.cpp:385
bool update_best()
updates best score by searching in the population for the individual that best fits the given data
Definition engine.cpp:479
SearchSpace ss
Definition engine.h:139
void set_population_from_json(vector< json > pop_vector)
Definition engine.cpp:414
Evaluation()
Constructor for Evaluation class.
Definition evaluation.h:34
static std::map< std::string, float > weightsMap
set parent ids using id values
Definition individual.h:163
void set_objectives(vector< string > objs)
Definition individual.h:180
Program< T > program
executable data structure
Definition individual.h:17
static const vector< string > simplification_table_header
Definition inexact.h:289
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
Class representing the variation operators in Brush.
Definition variation.h:44
Variation()=default
Default constructor.
void log_simplification_table(Util::CsvWriter &log, const string &run_id)
Definition variation.h:616
SearchSpace search_space
Definition variation.h:634
void vary_and_update(Population< T > &pop, int island, const vector< size_t > &parents, const Dataset &data, Evaluation< T > &evaluator, bool do_simplification, Dataset *validation_data=nullptr)
Varies a population and updates the selection strategy based on rewards.
Definition variation.h:223
SimplificationRecords pop_simplification_records()
returns the simplifications performed since the last call, and clears them. Records are only collecte...
Definition variation.h:622
Parameters parameters
Definition variation.h:636
#define HANDLE_ERROR_THROW(err)
Definition error.h:27
std::vector< SimplificationRecord > SimplificationRecords
Definition record.h:22
Scalar median(const T &v)
calculate median
Definition utils.h:202
string to_string(const T &value)
template function to convert objects to string for logging
Definition utils.h:369
string PBSTR
Definition utils.cpp:13
int PBWIDTH
Definition utils.cpp:14
< nsga2 selection operator for getting the front
Definition bandit.cpp:3
void from_json(const json &j, Fitness &f)
Definition fitness.cpp:31
void to_json(json &j, const Fitness &f)
Definition fitness.cpp:6
Eigen::Array< int, Eigen::Dynamic, 1 > ArrayXi
Definition types.h:40
summary statistics of a subset of the population (e.g. an island)
Definition engine.h:156
float best_score
best train loss
Definition engine.h:158
float best_score_v
best validation loss (may be another individual)
Definition engine.h:159
void set_sample_weights(const ArrayXf &y)
Definition params.h:220
void set_search_space(const std::reference_wrapper< SearchSpace > s)
Definition program.h:86