20template <ProgramType T>
23 r.set_seed(
params.get_random_state());
40template <ProgramType T>
43 int val = (int) (percentage * 100);
44 int lpad = (int) (percentage *
PBWIDTH);
47 printf (
"\rCompleted %3d%% [%.*s%*s]", val, lpad,
PBSTR.c_str(), rpad,
"");
56template <ProgramType T>
59 const size_t n = indices.size();
67 for (
const size_t population_index : indices)
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()) +
")");
75 const auto& p = this->
pop.individuals.at(population_index);
81 float fitness_loss = 0.0f;
82 float fitness_loss_v = 0.0f;
83 unsigned individual_size = 0;
84 unsigned individual_complexity = 0;
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();
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());
100 "Failed to get fitness/size/complexity from individual at population index "
101 +
to_string(population_index) +
": unknown error");
105 if (!std::isfinite(fitness_loss) || !std::isfinite(fitness_loss_v)) {
107 "Invalid non-finite fitness values at population index "
111 scores(index) = fitness_loss;
112 scores_v(index) = fitness_loss_v;
113 sizes(index) = individual_size;
114 complexities(index) = individual_complexity;
120 scores.conservativeResize(index);
121 scores_v.conservativeResize(index);
122 sizes.conservativeResize(index);
123 complexities.conservativeResize(index);
134 s.
best_score = (scores*error_weight).maxCoeff()*error_weight;
135 s.
best_score_v = (scores_v*error_weight).maxCoeff()*error_weight;
146template <ProgramType T>
149 if (
params.num_islands < 0) {
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");
157 vector<size_t> indices;
158 for (
int island=0; island<
params.num_islands; ++island)
160 const auto& island_indices =
pop.island_indexes.at(island);
161 indices.insert(indices.end(), island_indices.begin(), island_indices.end());
168 float best_score_v = this->
best_ind.fitness.get_loss_v();
170 if (!std::isfinite(best_score_v)) {
171 HANDLE_ERROR_THROW(
"Invalid non-finite validation loss in best_ind while calculating stats");
176 timer.Elapsed().count(),
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;
198 localtime_r(&t, &tm);
200 std::random_device rd;
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));
210template <ProgramType T>
217 std::ofstream runs(
params.logfile +
"_runs.jsonl", std::ofstream::app);
223 j[
"random_state"] =
params.random_state;
225 runs << j.dump() <<
"\n";
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",
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"});
242 "run_id",
"generation",
"individual_id",
"simplifier",
"ret_type",
243 "original",
"replacement",
"distance"});
246template <ProgramType T>
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()),
265 F::field(
best_ind.get_complexity()),
266 F::field(stall_count),
267 F::field(
archive.individuals.size()),
272 for (
int island = 0; island <
params.num_islands; ++island)
277 F::field(
params.current_gen),
291 for (
const auto& rec : simplifications)
295 F::field(rec.generation),
296 F::field(rec.individual_id),
301 F::field(rec.distance)
306template <ProgramType T>
314template <ProgramType T>
318 string bar, space =
"";
319 for (
unsigned int i = 0; i<50; ++i)
321 if (i <= 50*fraction) bar +=
"/";
325 std::cout.precision(5);
326 std::cout << std::scientific;
329 std::cout <<
"Generation " <<
params.current_gen+1 <<
"/"
330 <<
params.max_gens <<
" [" + bar + space +
"]\n";
332 std::cout << std::fixed <<
"Time elapsed "<<
timer
334 <<
" seconds (Generation "<<
params.current_gen+1
335 <<
") [" + bar + space +
"]\n";
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
347template <ProgramType T>
350 vector<json> archive_vector;
351 for (
const auto& ind :
archive.individuals) {
354 archive_vector.push_back(j);
357 return archive_vector;
362template <ProgramType T>
365 vector<json> pop_vector;
366 for (
const auto& ind :
pop.individuals) {
367 if (ind ==
nullptr) {
374 pop_vector.push_back(j);
384template <ProgramType T>
387 vector<Individual<T>> archive_vector;
388 for (
const auto& ind :
archive.individuals) {
389 archive_vector.push_back(ind);
392 return archive_vector;
395template <ProgramType T>
398 vector<Individual<T>> pop_vector;
399 for (
const auto& ind :
pop.individuals) {
400 if (ind ==
nullptr) {
403 pop_vector.push_back(*ind);
413template <ProgramType T>
416 vector<Individual<T>> new_pop;
419 for (
const auto& ind_j : pop_vector) {
428 new_pop.push_back(ind);
432 if(new_pop.size() !=
params.pop_size)
439template <ProgramType T>
442 vector<Individual<T>> new_pop;
443 for (
const auto& ind_j : pop_vector) {
448 new_pop.push_back(ind);
451 if(new_pop.size() !=
params.pop_size)
458template <ProgramType T>
462 for (
int island=0; island<
pop.num_islands; ++island) {
463 auto indices =
pop.get_island_indexes(island);
465 for (
unsigned i = 0; i<indices.size(); ++i)
467 const auto& ind =
pop.individuals.at(indices.at(i));
473 ind->program.lock_nodes(end_depth, keep_leaves_unlocked, keep_current_weights);
478template <ProgramType T>
481 bool updated =
false;
484 vector<size_t> merged_islands(0);
485 for (
int j=0;j<
pop.num_islands; ++j)
487 auto indices =
pop.island_indexes.at(j);
488 for (
int i=0; i<indices.size(); ++i)
490 merged_islands.push_back(indices.at(i));
494 for (
int i=0; i < merged_islands.size(); ++i)
496 const auto& ind_ptr =
pop.individuals.at(merged_islands[i]);
502 const auto& ind = *ind_ptr;
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]) {
512 if (ind.fitness.get_wvalues()[j] < this->best_ind.fitness.get_wvalues()[j]) {
530template <ProgramType T>
550 if (
params.load_population !=
"") {
553 else if (this->
pop.individuals.size() == 0)
573 if (!
params.logfile.empty())
585 threads = std::thread::hardware_concurrency();
586 else if (
params.n_jobs == 0)
587 threads =
params.num_islands;
591 tf::Executor executor(threads);
593 assert( (executor.num_workers() > 0) &&
"Invalid number of workers");
595 tf::Taskflow taskflow;
598 unsigned generation = 0;
599 unsigned stall_count = 0;
603 bool condition = ( (generation ==
params.max_gens)
604 || (
params.max_stall != 0 && stall_count >
params.max_stall)
613 vector<vector<size_t>> island_parents;
615 island_parents.clear();
616 island_parents.resize(
pop.num_islands);
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);
622 auto delta = idx_end - idx_start;
624 island_parents.at(i).clear();
625 island_parents.at(i).resize(
delta);
629 auto [
init, cond, body, back, done] = taskflow.emplace(
630 [&](tf::Subflow& subflow) {
634 auto fit_init_pop = subflow.emplace([&]() {
639 for (
int island = 0; island < this->
params.num_islands; ++island) {
641 true,
true,
true, fixed_validation);
644 auto find_init_best = subflow.emplace([&]() {
652 fit_init_pop.precede(find_init_best);
657 [&](tf::Subflow& subflow) {
658 auto prepare_gen = subflow.emplace([&]() {
659 params.set_current_gen(generation);
661 }).name(
"prepare generation");
668 auto run_generation = subflow.emplace([&]() {
673 if (
params.classification)
676 for (
int island = 0; island < this->
params.num_islands; ++island) {
682 true,
false,
true, fixed_validation);
684 vector<size_t> parents =
selector.select(
685 this->
pop, island, selection_params);
686 island_parents.at(island) = std::move(parents);
688 this->
pop.add_offspring_indexes(island);
690 }).name(
"runs one generation at each island in deterministic order");
692 auto update_pop = subflow.emplace([&]() {
695 for (
int island = 0; island < this->
params.num_islands; ++island) {
706 (generation>=
params.max_gens/2) || (stall_count ==
params.max_stall) || (generation==
params.max_gens-1),
721 this->
pop.update({survivor_indices});
723 }).name(
"update, migrate and disentangle indexes between islands");
725 auto finish_gen = subflow.emplace([&]() {
727 for (
int island = 0; island < this->
params.num_islands; ++island) {
732 false,
true,
false, fixed_validation);
739 fraction =
params.max_time == -1 ? ((generation+1)*1.0)/
params.max_gens :
748 else if(
params.verbosity == 1)
751 if (generation == 0 || updated_best )
756 if (!
params.logfile.empty())
761 }).name(
"update best, update ss, log, archive, stall");
764 prepare_gen.precede(run_generation);
765 run_generation.precede(update_pop);
766 update_pop.precede(finish_gen);
771 [&](tf::Subflow& subflow) {
774 for (
int island = 0; island < this->
params.num_islands; ++island) {
776 false,
true,
false, fixed_validation);
782 if (
params.save_population !=
"")
788 if (!
params.logfile.empty() &&
params.inexact_simplification) {
790 params.logfile+
"_simplification_table",
795 if (!
params.logfile.empty())
806 cond.name(
"termination");
807 body.name(
"main loop");
810 taskflow.name(
"island_gp");
813 cond.precede(body, done);
817 executor.run(taskflow);
818 executor.wait_for_all();
holds variable type data.
Dataset get_validation_data() const
Dataset get_batch() const
Select the next batch without replacement. Classification batches preserve the prevalence of the rema...
ArrayXf y
length N array, the target label
Dataset get_training_data() const
void set_batch_size(float new_size)
The Engine class represents the core engine of the brush library.
string run_id
identifies the rows of one call to fit
Selection< T > selector
selection algorithm
Timer timer
start time of training
bool is_fitted
keeps track of whether fit was called
Individual< T > best_ind
best individual found during training
void print_progress(float percentage)
void run(Dataset &d)
train the model
Log_Stats stats
runtime stats
Archive< T > archive
pareto front archive
Population< T > pop
population of programs
void set_population(vector< Individual< T > > pop_vector)
Util::CsvWriter log_islands
<logfile>_islands.csv
Selection< T > survivor
survival algorithm
void print_stats(float fraction)
void log_stats(unsigned stall_count, const SimplificationRecords &simplifications)
Util::CsvWriter log_generations
<logfile>
void set_is_fitted(bool f)
set flag indicating whether fit has been called
PopSummary summarize(const vector< size_t > &indices) const
vector< json > get_archive_as_json()
return archive/population as strings
Util::CsvWriter log_simplifications
<logfile>_simplifications.csv
void lock_nodes(int end_depth=0, bool keep_leaves_unlocked=true, bool keep_current_weights=false)
Evaluation< T > evaluator
evaluation code
Parameters params
hyperparameters of brush, which the user can interact
vector< Individual< T > > get_population()
void init()
initialize Feat object for fitting.
vector< json > get_population_as_json()
vector< Individual< T > > get_archive()
return archive/popularion as individuals ready to use
bool update_best()
updates best score by searching in the population for the individual that best fits the given data
void set_population_from_json(vector< json > pop_vector)
Evaluation()
Constructor for Evaluation class.
static std::map< std::string, float > weightsMap
set parent ids using id values
void set_objectives(vector< string > objs)
Program< T > program
executable data structure
static const vector< string > simplification_table_header
Minimal RFC 4180 CSV writer used by the run logs.
void write_row(const std::vector< std::string > &fields)
Class representing the variation operators in Brush.
Variation()=default
Default constructor.
void log_simplification_table(Util::CsvWriter &log, const string &run_id)
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.
SimplificationRecords pop_simplification_records()
returns the simplifications performed since the last call, and clears them. Records are only collecte...
#define HANDLE_ERROR_THROW(err)
std::vector< SimplificationRecord > SimplificationRecords
Scalar median(const T &v)
calculate median
string to_string(const T &value)
template function to convert objects to string for logging
< nsga2 selection operator for getting the front
void from_json(const json &j, Fitness &f)
void to_json(json &j, const Fitness &f)
Eigen::Array< int, Eigen::Dynamic, 1 > ArrayXi
summary statistics of a subset of the population (e.g. an island)
float best_score
best train loss
float best_score_v
best validation loss (may be another individual)
void set_sample_weights(const ArrayXf &y)
void set_search_space(const std::reference_wrapper< SearchSpace > s)