From c67350fb7db6183011dd56b2f2f4314f9fb304cf Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 13:48:58 -0500 Subject: [PATCH 01/25] improving AUPRC for tied scores. new test for 5 class multiclassification --- src/eval/metrics.cpp | 28 +++++------------- tests/cpp/test_evaluation.cpp | 53 ++++++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 22 deletions(-) diff --git a/src/eval/metrics.cpp b/src/eval/metrics.cpp index 7864c2d9..4bcd02ff 100644 --- a/src/eval/metrics.cpp +++ b/src/eval/metrics.cpp @@ -149,7 +149,8 @@ float binary_average_precision(const VectorXf& y, const VectorXf& predict_proba, const vector& w) { int num_instances = y.size(); - float eps = 1e-6f; + if (num_instances == 0) + return 0.0f; // get argsort of predict proba (descending) vector order(num_instances); @@ -172,23 +173,6 @@ float binary_average_precision(const VectorXf& y, const VectorXf& predict_proba, ysum += y_sorted[i] * w_sorted[i]; } - // when all scores are the same, the sort order is arbitrary, so the PR curve - // you integrate is a staircase instead of a flat line. Sklearn avoids this by - // treating ties as one threshold. - // however, this does not produce consistent results, so we will handle flat - // lines below - - // detect constant prediction case (all p_sorted equal within tolerance). - // because p_sorted is sorted, the first element is the maximum, and the last is the minimum, - if (fabs(p_sorted.back() - p_sorted.front()) <= eps) { - // All predictions are (effectively) constant. - float total_weight = std::accumulate(w_sorted.begin(), w_sorted.end(), 0.0f); - - // Return weighted positives / total weight, matching sklearn's result for constant scores - // (kinda weighted prevalence) - return total_weight == 0.0f ? 0.0f : ysum / total_weight; - } - // Find the indexes where prediction changes, so we can treat it as one block vector unique_indices = {}; // this one will be used to calculate the AUC set unique_probas = {}; // keep track of unique elements (this wont be used other than that) @@ -213,10 +197,12 @@ float binary_average_precision(const VectorXf& y, const VectorXf& predict_proba, tp += y_sorted.at(j) * w_sorted.at(j); fp += (1.0f - y_sorted.at(j)) * w_sorted.at(j); - float relevant = tp + fp; - precision.push_back(relevant == 0.0f ? 0.0f : tp / relevant); - recall.push_back(ysum == 0.0f ? 1.0f : tp / ysum); } + // A tied group is one threshold. Scoring each member separately makes + // fitness depend on their input order and penalizes piecewise models. + float relevant = tp + fp; + precision.push_back(relevant == 0.0f ? 0.0f : tp / relevant); + recall.push_back(ysum == 0.0f ? 0.0f : tp / ysum); } // integrate PR curve diff --git a/tests/cpp/test_evaluation.cpp b/tests/cpp/test_evaluation.cpp index 50c92bcf..c2c9a153 100644 --- a/tests/cpp/test_evaluation.cpp +++ b/tests/cpp/test_evaluation.cpp @@ -178,6 +178,20 @@ TEST_F(BinaryMetrics, RocAuc) EXPECT_NEAR(roc_auc_score(y, proba, loss, {1.0f, 2.0f}), 0.72f, 1e-6f); } +TEST_F(BinaryMetrics, AveragePrecisionTreatsTiesAsOneThreshold) +{ + VectorXf y(4), probabilities(4), loss; + y << 1, 0, 1, 0; + probabilities << 0.9f, 0.9f, 0.1f, 0.1f; + EXPECT_NEAR(average_precision_score(y, probabilities, loss), 0.5f, 1e-6f); + EXPECT_NEAR(average_precision_score(y, probabilities, loss, {1.0f, 2.0f}), 2.0f / 3.0f, 1e-6f); + + y.resize(2); probabilities.resize(2); + y << 1, 0; + probabilities << 0.5000001f, 0.5f; // testing brush precision handling + EXPECT_NEAR(average_precision_score(y, probabilities, loss), 1.0f, 1e-6f); +} + TEST_F(BinaryMetrics, RocAucTiedScores) { // tied scores are a single threshold (trapezoid, not a staircase) @@ -335,9 +349,12 @@ TEST(Evaluation, MulticlassSoftmaxHasOneOutputPerClass) y << 0.0f, 1.0f, 2.0f, 0.0f, 1.0f, 2.0f; Dataset data(X, y, {}, {}, {}, true); - SearchSpace search_space(data); + // Keep this softmax test independent of unrelated invalid-domain operators + // such as log or acos, and make its generated branches reproducible. + SearchSpace search_space(data, {{"Add", 1.0f}}, false); Parameters params; params.set_random_state(42); + Brush::Util::r.set_seed(42); params.classification = true; params.set_n_classes(y); params.max_depth = 3; @@ -369,6 +386,40 @@ TEST(Evaluation, MulticlassSoftmaxHasOneOutputPerClass) EXPECT_NEAR(simplified_probabilities.row(row).sum(), 1.0f, 1e-6f); } +TEST(Evaluation, FiveClassSoftmaxFitsAndPredicts) +{ + ArrayXXf X(10, 2); + ArrayXf y(10); + for (int i = 0; i < 10; ++i) { + X(i, 0) = static_cast(i); + X(i, 1) = static_cast(i % 2); + y(i) = static_cast(i % 5); // 5 class setting (maximum n of classes Brush supports) + } + + Dataset data(X, y, {}, {}, {"ArrayF", "ArrayB"}, true); + SearchSpace search_space(data, {{"Add", 1.0f}}, false); + Parameters params; + params.classification = true; + params.set_n_classes(y); + params.max_depth = 3; + params.max_size = 20; + Brush::Util::r.set_seed(42); + + auto program = search_space.make_multiclass_classifier(3, 20, params); + ASSERT_EQ(program.Tree.begin().node->data.arg_types.size(), 5U); + program.fit(data, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f}); + + const auto probabilities = program.predict_proba(data); + ASSERT_EQ(probabilities.rows(), X.rows()); + ASSERT_EQ(probabilities.cols(), 5); + ASSERT_TRUE(probabilities.isFinite().all()); + for (int row = 0; row < probabilities.rows(); ++row) + EXPECT_NEAR(probabilities.row(row).sum(), 1.0f, 1e-6f); + + MulticlassClassifierProgram restored = json(program); + EXPECT_TRUE(restored.predict_proba(data).isApprox(probabilities, 1e-6f)); +} + TEST(Evaluation, SplitThresholdsAreNotOptimizerParameters) { ArrayXXf X(6, 1); From 24fd15a2e6a453a8c7dbab52f0258a98d2056e79 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 13:52:55 -0500 Subject: [PATCH 02/25] update docs for max arity --- src/program/signatures.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/program/signatures.h b/src/program/signatures.h index 4fddfe7a..fc759dfe 100644 --- a/src/program/signatures.h +++ b/src/program/signatures.h @@ -157,13 +157,13 @@ template using NarySignature_t = typename NarySignature::type; /** - * @brief Makes a tuple of signatures with increasing arity up to `MaxArgCount`. + * @brief Makes a tuple of signatures with arity below `MaxArgCount`. * * Assumes the types of the arguments are identical. * * @tparam R return type of the signature. * @tparam Arg shared type of every argument. - * @tparam MaxArgCount maximum number of arguments. + * @tparam MaxArgCount exclusive upper bound on the number of arguments. */ template struct NarySignatures @@ -426,7 +426,8 @@ template <> struct Signatures { using unaryTuple = std::tuple< Signature >; - using naryTuple = NarySignatures_t; + // Include one logit for each class through the supported maximum. + using naryTuple = NarySignatures_t; using type = decltype(std::tuple_cat(unaryTuple(), naryTuple())); }; From 9b96a136a091d3339f84eecba5d0152af7c6deae Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:04:33 -0500 Subject: [PATCH 03/25] improved log. locking best_ind explicitly. validate n_classes before run --- src/engine.cpp | 217 ++++++++++++++++++++++++++++++++++++++++--------- src/engine.h | 8 +- 2 files changed, 184 insertions(+), 41 deletions(-) diff --git a/src/engine.cpp b/src/engine.cpp index a955232f..97054c79 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -1,4 +1,5 @@ #include "engine.h" +#include "util/progress.h" #include #include @@ -16,6 +17,19 @@ using namespace Eval; using namespace Var; using namespace MAB; +namespace { +string batch_progress_label(const Dataset& training) +{ + const auto progress = training.get_batch_progress(); + if (!progress) + return ""; + + const auto width = std::to_string(progress->batches).size(); + return fmt::format("epoch {}, batch {:0{}}/{}", progress->epoch, + progress->batch, width, progress->batches); +} +} + /// @brief initialize Feat object for fitting. template void Engine::init() @@ -38,13 +52,16 @@ void Engine::init() } template -void Engine::print_progress(float percentage) +void Engine::print_progress(float percentage, const string& batch_label) { int val = (int) (percentage * 100); int lpad = (int) (percentage * PBWIDTH); int rpad = PBWIDTH - lpad; printf ("\rCompleted %3d%% [%.*s%*s]", val, lpad, PBSTR.c_str(), rpad, ""); + if (!batch_label.empty()) + printf(" (%s)", batch_label.c_str()); + printf(" "); fflush (stdout); @@ -288,6 +305,13 @@ void Engine::log_stats(unsigned stall_count, const SimplificationRecords& sim }); } + log_simplification_records(simplifications); +} + +template +void Engine::log_simplification_records(const SimplificationRecords& simplifications) +{ + using F = Util::CsvWriter; for (const auto& rec : simplifications) { log_simplifications.write_row({ @@ -312,8 +336,10 @@ void Engine::close_logs() } template -void Engine::print_stats(float fraction) +void Engine::print_stats(float fraction, const string& batch_label, + std::optional estimated_remaining) { + const auto elapsed = Util::format_duration(timer.Elapsed().count()); // progress bar string bar, space = ""; for (unsigned int i = 0; i<50; ++i) @@ -327,21 +353,28 @@ void Engine::print_stats(float fraction) if(params.max_time == -1) std::cout << "Generation " << params.current_gen+1 << "/" - << params.max_gens << " [" + bar + space + "]\n"; + << params.max_gens << " [" + bar + space + "]"; else - std::cout << std::fixed << "Time elapsed "<< timer - << "/" << params.max_time - << " seconds (Generation "<< params.current_gen+1 - << ") [" + bar + space + "]\n"; + std::cout << "Time elapsed " << elapsed + << "/" << Util::format_duration(params.max_time) + << " (Generation " << params.current_gen+1 + << ") [" + bar + space + "]"; + + if (!batch_label.empty()) + std::cout << " (" << batch_label << ")"; + std::cout << "\n"; std::cout << std::fixed - << "Best model on Val:" << best_ind.program.get_model() << "\n" + << "Best model on Val (" << best_ind.program.Tree.size() << " nodes): " + << best_ind.program.get_model() << "\n" << "Train Loss (Med): " << stats.best_score.back() << " (" << stats.med_score.back() << ")\n" << "Val Loss (Med): " << stats.best_score_v.back() << " (" << stats.med_score_v.back() << ")\n" << "Median Size (Max): " << stats.med_size.back() << " (" << stats.max_size.back() << ")\n" << "Median complexity (Max): " << stats.med_complexity.back() << " (" << stats.max_complexity.back() << ")\n" - << "Time (s): " << timer - <<"\n\n"; + << "Elapsed: " << elapsed + << " | Estimated remaining: " + << (estimated_remaining ? Util::format_duration(*estimated_remaining) : "--:--:--") + << "\n\n" << std::flush; } template @@ -443,6 +476,7 @@ void Engine::set_population(vector> pop_vector) for (const auto& ind_j : pop_vector) { Individual ind; ind.program = ind_j.program; + ind.set_is_fitted(ind_j.get_is_fitted()); ind.set_objectives(ind_j.get_objectives()); new_pop.push_back(ind); @@ -454,6 +488,15 @@ void Engine::set_population(vector> pop_vector) this->pop.init(new_pop, params); } +template +void Engine::invalidate_population_fit() +{ + for (int island = 0; island < pop.num_islands; ++island) + for (auto index : pop.get_island_indexes(island)) + pop.individuals.at(index)->set_is_fitted(false); + best_ind.set_is_fitted(false); +} + template void Engine::lock_nodes(int end_depth, bool keep_leaves_unlocked, bool keep_current_weights) @@ -473,6 +516,8 @@ void Engine::lock_nodes(int end_depth, bool keep_leaves_unlocked, bool keep_c ind->program.lock_nodes(end_depth, keep_leaves_unlocked, keep_current_weights); } } + if (is_fitted) + best_ind.program.lock_nodes(end_depth, keep_leaves_unlocked, keep_current_weights); } template @@ -530,6 +575,21 @@ bool Engine::update_best() template void Engine::run(Dataset &data) { + const bool continuing = is_fitted; + if constexpr (T == PT::BinaryClassifier || T == PT::MulticlassClassifier) { + // Check the data as well as the configured count: callers of the + // native engine may supply inconsistent or incomplete parameters. + std::set observed_classes; + for (Eigen::Index i = 0; i < data.y.size(); ++i) + observed_classes.insert(data.y(i)); + const auto n_classes = std::max(static_cast(params.n_classes), + observed_classes.size()); + if (n_classes > MAX_ARGS) + HANDLE_ERROR_THROW(fmt::format( + "Brush supports at most {} classes; received {} classes. " + "Training cannot continue.", MAX_ARGS, n_classes)); + } + // All learning-time state is derived from the training partition. The // original dataset remains the source of the fixed validation partition. Dataset training = data.get_training_data(); @@ -556,6 +616,10 @@ void Engine::run(Dataset &data) this->pop.init(this->ss, this->params); } } + else { + // Each continued fit has its own elapsed time and time limit. + timer.Reset(); + } // TODO: Should I refit them? or use the values at it is? (the fitness WILL BE recalculated regardless) // invalidating all individuals (so they are fitted with current data) @@ -598,6 +662,8 @@ void Engine::run(Dataset &data) unsigned generation = 0; unsigned stall_count = 0; float fraction = 0; + Util::RecentGenerationTimes generation_times; + std::chrono::steady_clock::time_point last_generation_timing; auto stop = [&]() { bool condition = ( (generation == params.max_gens) @@ -625,6 +691,21 @@ void Engine::run(Dataset &data) island_parents.at(i).resize(delta); } + // make sure we have an updated reference to the best individual in the population + // when resuming the evolution due to a call to partial_fit + std::optional selected_in_population; + if (continuing && params.max_gens == 0) { + const json selected_program = best_ind.program; + for (int island = 0; island < pop.num_islands && !selected_in_population; ++island) + for (auto index : pop.get_island_indexes(island)) { + const auto& ind = *pop.individuals.at(index); + if (ind.id == best_ind.id && json(ind.program) == selected_program) { + selected_in_population = index; + break; + } + } + } + // heavily inspired in https://github.com/heal-research/operon/blob/main/source/algorithms/nsga2.cpp auto [init, cond, body, back, done] = taskflow.emplace( [&](tf::Subflow& subflow) { @@ -632,22 +713,60 @@ void Engine::run(Dataset &data) // a stable order as well, so the first selection sees identical // fitness values for repeated seeded runs. auto fit_init_pop = subflow.emplace([&]() { - // The initial population has no fitted weights. Use the first - // representative batch rather than fitting every program on - // the whole training partition before evolution starts. + // Fit new programs on the first representative batch; loaded + // or continued programs retain their previously fitted weights. batch = training.get_batch(); - for (int island = 0; island < this->params.num_islands; ++island) { - evaluator.update_fitness(this->pop, island, batch, params, - true, true, true, fixed_validation); + if (params.verbosity > 0) { + // This message shows that brush started to run and it is performing the first evaluation + const auto label = batch_progress_label(training); + if (!label.empty()) + std::cout << "Initializing population (" << label << ")\n" << std::flush; + } + if (continuing && params.max_gens == 0 && // this is how we force it to just reevaluate and simplify but skip the evolutionary loop when calling partial_fit + (params.constants_simplification || params.inexact_simplification)) { + for (int island = 0; island < this->params.num_islands; ++island) { + for (auto index : pop.get_island_indexes(island)) { + auto& ind = *pop.individuals.at(index); + + // OBS: when we call partial_fit, the python side invokes + // engine_.invalidate_population_fit(), so they will all be invalid + if (!ind.get_is_fitted() || !ind.program.is_fitted_) { + ind.program.fit(batch, params.class_weights); + ind.set_is_fitted(true); + } + variator.simplify_individual(ind, batch, true); + evaluator.assign_fit(ind, batch, params, true, fixed_validation); + } + } + } else { + for (int island = 0; island < this->params.num_islands; ++island) + evaluator.update_fitness(this->pop, island, batch, params, + true, true, false, fixed_validation); } }); + // this block below runs independently of the previous one auto find_init_best = subflow.emplace([&]() { - // Make sure we initialize it. We do this update here because we need to - // have the individuals fitted before we can compare them. When update_best - // is called, we are garanteed that the individuals are fitted and have valid - // fitnesses. - this->best_ind = *pop.individuals.at(0); - this->update_best(); // at this moment we dont care about update_best return value + if (selected_in_population) { + // Reuse the already refitted and simplified member. + best_ind = *pop.individuals.at(*selected_in_population); + } else if (continuing) { + // The previously selected model can be outside the final + // population. Rescore it on the same data before comparing. + if (!best_ind.get_is_fitted() || !best_ind.program.is_fitted_) { + best_ind.program.fit(batch, params.class_weights); + best_ind.set_is_fitted(true); + } + if (params.max_gens == 0 && + (params.constants_simplification || params.inexact_simplification)) + variator.simplify_individual(best_ind, batch, true); + evaluator.assign_fit(best_ind, batch, params, true, fixed_validation); + } else { + this->best_ind = *pop.individuals.at(0); + } + // A zero-generation continuation only reevaluates existing + // candidates; preserve the user's selected model. + if (!continuing || params.max_gens != 0) + this->update_best(); }); fit_init_pop.precede(find_init_best); }, // init (entry point for taskflow) @@ -656,6 +775,8 @@ void Engine::run(Dataset &data) [&](tf::Subflow& subflow) { // loop body (evolutionary main loop) auto prepare_gen = subflow.emplace([&]() { + if (params.verbosity > 1 && generation == 0) + last_generation_timing = std::chrono::steady_clock::now(); params.set_current_gen(generation); batch = training.get_batch(); // returns all training data when batching is disabled }).name("prepare generation");// set generation in params, get batch @@ -675,11 +796,10 @@ void Engine::run(Dataset &data) for (int island = 0; island < this->params.num_islands; ++island) { - // Refit each surviving program on this generation's batch. - // Parent selection uses batch fitness while validation always - // uses the original, fixed hold-out partition. + // Reevaluate survivors on the new batch without changing their + // fitted weights or split thresholds. evaluator.update_fitness(this->pop, island, batch, params, - true, false, true, fixed_validation); + false, false, false, fixed_validation); vector parents = selector.select( this->pop, island, selection_params); @@ -743,16 +863,32 @@ void Engine::run(Dataset &data) calculate_stats(); } - if(params.verbosity>1) - print_stats(fraction); - else if(params.verbosity == 1) - print_progress(fraction); - if (generation == 0 || updated_best ) stall_count = 0; else ++stall_count; + if (params.verbosity > 0) { + // do the necessary calculations and log the info + const auto label = batch_progress_label(training); + if (params.verbosity > 1) { + const auto now = std::chrono::steady_clock::now(); + const auto duration = std::chrono::duration( + now - last_generation_timing).count(); + last_generation_timing = now; + generation_times.record(duration); + const bool stalled = params.max_stall != 0 && stall_count > params.max_stall; + const auto remaining_generations = stalled ? 0 : + std::max(0LL, static_cast(params.max_gens) - generation - 1); + std::optional time_limit_remaining; + if (params.max_time != -1) + time_limit_remaining = params.max_time - timer.Elapsed().count(); + print_stats(fraction, label, + generation_times.remaining(remaining_generations, time_limit_remaining)); + } else + print_progress(fraction, label); + } + if (!params.logfile.empty()) log_stats(stall_count, variator.pop_simplification_records()); @@ -769,12 +905,12 @@ void Engine::run(Dataset &data) [&]() { return 0; }, // jump back to the next iteration [&](tf::Subflow& subflow) { - // Keep the final batch-fitted weights and fixed validation scores; + // Keep the fitted weights and fixed validation scores; // do not add a full-training pass after evolution ends. - for (int island = 0; island < this->params.num_islands; ++island) { - evaluator.update_fitness(this->pop, island, batch, params, - false, true, false, fixed_validation); - } + if (params.max_gens != 0) + for (int island = 0; island < this->params.num_islands; ++island) + evaluator.update_fitness(this->pop, island, batch, params, + false, true, false, fixed_validation); archive.update(pop, params); // calculate_stats(); @@ -792,8 +928,10 @@ void Engine::run(Dataset &data) variator.log_simplification_table(log_simplification_table, run_id); } - if (!params.logfile.empty()) + if (!params.logfile.empty()) { + log_simplification_records(variator.pop_simplification_records()); close_logs(); + } // getting the updated versions this->ss = variator.search_space; @@ -814,8 +952,9 @@ void Engine::run(Dataset &data) body.precede(back); back.precede(cond); - executor.run(taskflow); - executor.wait_for_all(); + // Propagate failures from the task graph instead of returning an unfitted + // engine when an evaluation throws on a worker. + executor.run(taskflow).get(); //When you have tasks that are created at runtime (e.g., subflow, // cudaFlow), you need to execute the graph first to spawn these tasks and dump the entire graph. diff --git a/src/engine.h b/src/engine.h index a6e4f74b..37b19e7d 100644 --- a/src/engine.h +++ b/src/engine.h @@ -60,9 +60,10 @@ class Engine{ ~Engine(){}; // outputs a progress bar, filled according to @param percentage. - void print_progress(float percentage); + void print_progress(float percentage, const string& batch_label = ""); void calculate_stats(); - void print_stats(float fraction); + void print_stats(float fraction, const string& batch_label = "", + std::optional estimated_remaining = std::nullopt); // all hyperparameters are controlled by the parameter class. please refer to that to change something inline Parameters& get_params(){return params;} @@ -77,6 +78,7 @@ class Engine{ bool update_best(); Individual& get_best_ind(){return best_ind;}; + void set_best_ind(const Individual& individual) { best_ind = individual; } Engine &fit(Dataset& data) { run(data); @@ -126,6 +128,7 @@ class Engine{ vector> get_archive(); vector> get_population(); void set_population(vector> pop_vector); + void invalidate_population_fit(); // locking and unlocking parts of the solutions void lock_nodes(int end_depth=0, bool keep_leaves_unlocked=true, bool keep_current_weights=false); @@ -174,6 +177,7 @@ class Engine{ void open_logs(); void log_stats(unsigned stall_count, const SimplificationRecords& simplifications); + void log_simplification_records(const SimplificationRecords& simplifications); void close_logs(); void init(); From 72ee6407eea2066c2618c82e914aad464c594dcc Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:05:20 -0500 Subject: [PATCH 04/25] softmax takes 5 arguments. fixed splitBest size calculation --- src/program/tree_node.cpp | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/program/tree_node.cpp b/src/program/tree_node.cpp index 05ac6dc7..73e7c157 100644 --- a/src/program/tree_node.cpp +++ b/src/program/tree_node.cpp @@ -41,8 +41,12 @@ string TreeNode::get_tree_model(bool pretty, string offset) const child_outputs += "\n"; } if (Is(data.node_type)){ + if (data.get_feature_type() == DataType::ArrayI && !data.split_categories.empty()) + return fmt::format("If({} in {{{}}})", data.get_feature(), + fmt::join(data.split_categories, ",")) + child_outputs; if (data.get_feature_type() != DataType::ArrayB) { - return fmt::format("If({}>={:.2f})", data.get_feature(), data.W) + child_outputs; + const char* op = data.get_feature_type() == DataType::ArrayI ? "==" : ">="; + return fmt::format("If({}{}{:.2f})", data.get_feature(), op, data.W) + child_outputs; } else { return fmt::format("If({})", data.get_feature()) + child_outputs; @@ -136,7 +140,7 @@ unordered_map operator_complexities = { {NodeType::Prod , 4}, // Transformers - {NodeType::Softmax, 5}, + {NodeType::Softmax, 5}, // This is used only in multiclassification. Change here to allow brush to work with more classes // Binary {NodeType::Add, 3}, @@ -153,6 +157,8 @@ unordered_map operator_complexities = { {NodeType::And, 3}, {NodeType::Or , 3}, {NodeType::Not, 3}, + {NodeType::Geq, 3}, + {NodeType::Equals, 3}, // leaves {NodeType::MeanLabel, 1}, @@ -179,7 +185,7 @@ int TreeNode::get_linear_complexity() const } // include the `w` and `*` if the node is weighted (and it is not a constant or mean label) - if (data.get_is_weighted() + if (data.get_is_weighted() && IsWeighable(data.node_type) && Isnt(data.node_type) ) { // ignoring weight if it has the value of neutral element of operation @@ -207,7 +213,7 @@ int TreeNode::get_complexity() const children_complexity_sum = max(children_complexity_sum, 1); // include the `w` and `*` if the node is weighted (and it is not a constant or mean label) - if (data.get_is_weighted() + if (data.get_is_weighted() && IsWeighable(data.node_type) && Isnt(data.node_type) ) { // complexity for offsetsum or weighted nodes. @@ -227,17 +233,18 @@ int TreeNode::get_size(bool include_weight) const { int acc = 1; // the node operator or terminal - // SplitBest has an optimizable decision tree consisting of 3 nodes - // (terminal, arithmetic comparison, value) that needs to be taken - // into account. Split on will have an random decision tree that can - // have different sizes, but will also have the arithmetic comparison - // and a value. - if (Is(data.node_type)) - acc += 3; - else if (Is(data.node_type)) - acc += 2; - + // SplitBest contains an implicit feature, comparison, and threshold. + // SplitOn's boolean condition is already represented by its first child. + if (Is(data.node_type)) { + if (data.get_feature_type() == DataType::ArrayB) + acc += 1; + else if (data.get_feature_type() == DataType::ArrayI && !data.split_categories.empty()) + acc += 2 + static_cast(data.split_categories.size()); + else + acc += 3; + } if ( (include_weight && data.get_is_weighted()==true) + && IsWeighable(data.node_type) && Isnt(data.node_type) ) // Taking into account the weight and multiplication, if enabled. // weighted constants still count as 1 (simpler than constant terminals) From e107a7d839217416dd21af7c6f52631679899a93 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:06:45 -0500 Subject: [PATCH 05/25] implemented get_batch_progress, used when verbosity>1 to print batch information --- src/data/data.cpp | 2 ++ src/data/data.h | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/data/data.cpp b/src/data/data.cpp index 11463cc2..feffcd78 100644 --- a/src/data/data.cpp +++ b/src/data/data.cpp @@ -359,6 +359,7 @@ Dataset Dataset::get_batch() const batch_cycle_sizes.push_back(batch_indices.size()); } } + ++batch_epoch; } // get the indices and move the two cursors @@ -554,6 +555,7 @@ void Dataset::set_batch_size(float new_size) { batch_cycle_sizes.clear(); batch_cycle_cursor = 0; batch_cycle_batch_cursor = 0; + batch_epoch = 0; } /// turns input data into a feature map diff --git a/src/data/data.h b/src/data/data.h index c891d560..7cc72d30 100644 --- a/src/data/data.h +++ b/src/data/data.h @@ -64,10 +64,17 @@ class Dataset mutable vector batch_cycle_sizes; mutable size_t batch_cycle_cursor = 0; mutable size_t batch_cycle_batch_cursor = 0; + mutable size_t batch_epoch = 0; /// @brief stores the original feature name order before map sorting vector feature_name_order_; public: + struct BatchProgress { + size_t epoch; + size_t batch; + size_t batches; + }; + /// @brief keeps track of the unique data types in the dataset. std::vector unique_data_types; @@ -241,6 +248,14 @@ class Dataset /// preserve the prevalence of the remaining class-specific queues. Dataset get_batch() const; + /// Position of the most recently selected batch, if batching is active. + std::optional get_batch_progress() const { + if (!use_batch || batch_epoch == 0) + return std::nullopt; + return BatchProgress{batch_epoch, batch_cycle_batch_cursor, + batch_cycle_sizes.size()}; + } + float get_batch_size(); void set_batch_size(float new_size); From 4593e4d272f25a7f40cdb6d648221f4c78b892d5 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:16:05 -0500 Subject: [PATCH 06/25] updating individual is_fitted_, not only individual.program.is_fitted_ --- src/ind/individual.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ind/individual.h b/src/ind/individual.h index 78a35fbd..9bf87e2d 100644 --- a/src/ind/individual.h +++ b/src/ind/individual.h @@ -47,11 +47,13 @@ class Individual{ Individual(Program& prg) : Individual() { program = prg; + is_fitted_ = program.is_fitted_; }; void init(SearchSpace& ss, const Parameters& params) { program = ss.make_program>(params, 0, 0); + is_fitted_ = false; // overriding the objectives with the ones from params (to replace // the generic "scorer" by the actual scorer set in the params object) From 41b08b2d7dd173ce36c30a0230e4f5b06f58b39b Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:17:25 -0500 Subject: [PATCH 07/25] update_fitness also sets is_fitted_ flag to true --- src/eval/evaluation.cpp | 3 ++- src/eval/evaluation.h | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/eval/evaluation.cpp b/src/eval/evaluation.cpp index 56d8e55d..9f6487d6 100644 --- a/src/eval/evaluation.cpp +++ b/src/eval/evaluation.cpp @@ -42,9 +42,10 @@ void Evaluation::update_fitness(Population& pop, else { // assign weights to individual - if (fit && (force_fit || ind.get_is_fitted() == false)) + if (fit && (force_fit || !ind.get_is_fitted() || !ind.program.is_fitted_)) { ind.program.fit(data.get_training_data(), params.class_weights); + ind.set_is_fitted(true); } assign_fit(ind, data, params, validation, validation_data); diff --git a/src/eval/evaluation.h b/src/eval/evaluation.h index 60481212..8c15abd1 100644 --- a/src/eval/evaluation.h +++ b/src/eval/evaluation.h @@ -66,8 +66,9 @@ class Evaluation { * @param island The island index. * @param data The dataset for evaluation. * @param params The parameters for evaluation. - * @param fit Flag indicating whether to update fitness. - * @param validation Flag indicating whether to perform validation. + * @param fit Fit individuals that have not yet been fitted. + * @param validation Use validation loss for the fitness objective. + * @param force_fit Refit even individuals that have already been fitted. */ void update_fitness(Population& pop, int island, From a3fb813b56dd7f052013d1d37fcf0186945af9c8 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:19:23 -0500 Subject: [PATCH 08/25] making Int weights also int (so they are not tuned in gradient optimizer. The weights are used as the comparison value for operators that works with integers (because in Brush integers correspond to classes). For example, in the node Equals(category, 2), the 2 is data.W --- src/program/operator.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/program/operator.h b/src/program/operator.h index 2d9e2a3f..c8d94fcb 100644 --- a/src/program/operator.h +++ b/src/program/operator.h @@ -20,8 +20,12 @@ namespace util{ Scalar get_weight(const TreeNode& tn, const W** weights=nullptr) { Scalar w; + // Integer constants are discrete values, not optimizer parameters. + if constexpr (is_one_of_v) + return Scalar(static_cast(tn.data.W)); + // Prediction case: weight is stored in the node data. - if (weights == nullptr) + if (weights == nullptr || tn.data.weight_is_fixed) { if constexpr (std::is_floating_point_v || std::is_integral_v) { if (std::isnan(tn.data.W) || tn.data.W == std::numeric_limits::lowest()) { @@ -75,7 +79,7 @@ namespace util{ "it should not be\n")); // std::cout << "Returning weight: Scalar(true) for a boolean node tn " << tn.data.name << std::endl; - return Scalar(true); + return Scalar(static_cast(tn.data.W)); }; } //////////////////////////////////////////////////////////////////////////////// From 5eb10db6cb5b4c7e7ca01276d9b0279c8b84d0ca Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:23:32 -0500 Subject: [PATCH 09/25] simplifying subtrees with integer rettypes --- src/simplification/constants.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/simplification/constants.h b/src/simplification/constants.h index 835608d3..81a34cb7 100644 --- a/src/simplification/constants.h +++ b/src/simplification/constants.h @@ -40,13 +40,17 @@ namespace Brush { namespace Simpl{ // non-wheightable nodes are not simplified. TODO: revisit this and see if they should (then implement it) if (Isnt(n.node_type) && n.get_prob_change()>0 - && IsWeighable(n.ret_type) + && (IsWeighable(n.ret_type) || n.ret_type == DataType::ArrayI) ) { // TODO: check if holds alternative and use this information, instead of making it templated. Also, return void. // get new_pred with predictions after simplification VectorXf branch_pred; - if constexpr (P==ProgramType::Regressor || P==ProgramType::BinaryClassifier) + if (n.ret_type == DataType::ArrayI) + { + branch_pred = (*spot.node).template predict(d).template cast(); + } + else if constexpr (P==ProgramType::Regressor || P==ProgramType::BinaryClassifier) { RetType pred = (*spot.node).predict(d); branch_pred = pred.template cast(); From f430233f5dc059e111eea65c67592705503c8032 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:26:33 -0500 Subject: [PATCH 10/25] better printing of split nodes --- src/program/node.h | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/program/node.h b/src/program/node.h index 62b36277..239c6a51 100644 --- a/src/program/node.h +++ b/src/program/node.h @@ -50,18 +50,32 @@ inline auto Isnt(DataType dt) -> bool { return !((dt == T) || ...); } template inline auto IsWeighable() noexcept -> bool { return Isnt(DT); } inline auto IsWeighable(DataType dt) noexcept -> bool { return Isnt(dt); } @@ -221,7 +235,7 @@ struct Node { size_t get_node_hash(bool include_const=true) const { // we ignore the constant only on simplification, because it will be tuned anyways - return std::hash{}(HashTuple{ + auto hash = std::hash{}(HashTuple{ NodeTypes::GetIndex(node_type), sig_hash, get_is_weighted(), @@ -233,6 +247,9 @@ struct Node { // just so we differentiate whether the weight exists or is ignored include_const ? int(W * 100) : (get_is_weighted() ? 1 : 0) }); + for (int category : split_categories) + hash ^= std::hash{}(category) + 0x9e3779b9 + (hash << 6) + (hash >> 2); + return hash; } //////////////////////////////////////////////////////////////////////////////// //comparison operators @@ -309,6 +326,10 @@ struct Node { /// @brief feature type for terminals or splitting nodes DataType feature_type = DataType::ArrayF; + // For categorical SplitBest nodes, the values routed to the first branch. + // Empty preserves the historical single-category threshold representation. + vector split_categories; + /// @brief fix the SplitBest feature when the node is fixed bool keep_split_feature = false; // TODO: unittests for keep_split_feature }; @@ -382,6 +403,18 @@ inline auto IsWeighable(NodeType nt) noexcept -> bool { >(nt); } +// Keep parameter enumeration and evaluation in agreement. Constants always +// use their value; integer and boolean values are not optimized by Ceres. +inline bool HasOptimizableWeight(const Node& node) noexcept { + if (node.weight_is_fixed || !IsWeighable(node.ret_type)) + return false; + if (Is(node.node_type)) + return true; + if (Is(node.node_type)) + return node.get_is_weighted(); + return node.get_is_weighted() && IsWeighable(node.node_type); +} + ostream& operator<<(ostream& os, const Node& n); ostream& operator<<(ostream& os, const NodeType& nt); From 7e1f7e3f5db6f561b0e414baa45c8f480609d6d0 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:27:37 -0500 Subject: [PATCH 11/25] better print of split nodes --- src/program/node.cpp | 26 +++++++++++++++++--------- src/program/program.h | 42 +++++++++++++++--------------------------- 2 files changed, 32 insertions(+), 36 deletions(-) diff --git a/src/program/node.cpp b/src/program/node.cpp index dd53e42e..4c403e7f 100644 --- a/src/program/node.cpp +++ b/src/program/node.cpp @@ -24,7 +24,7 @@ auto Node::get_name(bool include_weight) const noexcept -> std::string if (Is(node_type)) { - if (is_weighted && !weight_is_one && include_weight) + if (get_is_weighted() && !weight_is_one && include_weight) return fmt::format("{:.2f}*{}", W, feature); else return feature; @@ -46,7 +46,7 @@ auto Node::get_name(bool include_weight) const noexcept -> std::string return "Sum"; } - else if (is_weighted && !weight_is_one && include_weight) + else if (get_is_weighted() && IsWeighable(node_type) && !weight_is_one && include_weight) { return fmt::format("{:.2f}*{}", W, name); } @@ -60,12 +60,14 @@ string Node::get_model(const vector& children) const noexcept if (children.empty()) return get_name(); else if (Is(node_type)){ - return fmt::format("If({}>={:.2f},{},{})", - feature, - W, - children.at(0), - children.at(1) - ); + if (feature_type == DataType::ArrayB) + return fmt::format("If({},{},{})", feature, children.at(0), children.at(1)); + if (feature_type == DataType::ArrayI && !split_categories.empty()) + return fmt::format("If({} in {{{}}},{},{})", feature, + fmt::join(split_categories, ","), children.at(0), children.at(1)); + const char* op = feature_type == DataType::ArrayI ? "==" : ">="; + return fmt::format("If({}{}{:.2f},{},{})", feature, op, W, + children.at(0), children.at(1)); } else if (Is(node_type)){ if (arg_types.at(0) == DataType::ArrayB) @@ -134,7 +136,8 @@ void to_json(json& j, const Node& p) {"ret_type", p.ret_type}, {"arg_types", p.arg_types}, {"feature", p.get_feature()}, - {"feature_type", p.get_feature_type()} + {"feature_type", p.get_feature_type()}, + {"split_categories", p.split_categories} // {"node_hash", p.get_node_hash()} }; } @@ -331,6 +334,11 @@ void from_json(const json &j, Node& p) j.at("feature_type").get_to(p.feature_type); } + if (j.contains("split_categories")) + j.at("split_categories").get_to(p.split_categories); + else + p.split_categories.clear(); + // if node has a ret_type and arg_types, get them. if not we need to make // a signature bool make_signature=false; diff --git a/src/program/program.h b/src/program/program.h index 73ee6c76..93be8551 100644 --- a/src/program/program.h +++ b/src/program/program.h @@ -317,15 +317,7 @@ template struct Program // get_n_weights, get_weights, and set_weights, are functions used in // parameter optimization --- we can simply make weights invisible to parameter // optimization, and they will not be changed (so they remain fixed). - if (node.weight_is_fixed) - continue; - - // some nodes cannot have their weights optimized, others must have. - // It is important that this condition also matches the condition in - // the methods get_weights and set_weights. - if (Is(node.node_type) - || (node.get_is_weighted() && IsWeighable(node.ret_type) - && IsWeighable(node.node_type)) ) + if (HasOptimizableWeight(node)) ++count; } return count; @@ -344,13 +336,7 @@ template struct Program { const auto& node = t.node->data; - // skip fixed weights (this also avoid changing offsetSum weight if is locked) - if (node.weight_is_fixed) - continue; - - if ( Is(node.node_type) - || (node.get_is_weighted() && IsWeighable(node.ret_type) - && IsWeighable(node.node_type)) ) + if (HasOptimizableWeight(node)) { weights(i) = node.W; ++i; @@ -377,13 +363,7 @@ template struct Program { auto& node = i.node->data; - // skip fixed weights (this also avoid changing offsetSum weight if is locked) - if (node.weight_is_fixed) - continue; - - if ( Is(node.node_type) - || (node.get_is_weighted() && IsWeighable(node.ret_type) - && IsWeighable(node.node_type)) ) + if (HasOptimizableWeight(node)) { node.W = weights(j); ++j; @@ -531,7 +511,7 @@ template struct Program // This is for the root -------------------------------------------- // if the first node is weighted, make a dummy output node so that the // first node's weight can be shown - if (i==0 && parent->data.get_is_weighted()) + if (i==0 && parent->data.get_is_weighted() && IsWeighable(parent->data.node_type)) { // making the weight red if fixed string font_color = ""; @@ -562,7 +542,15 @@ template struct Program if (parent->data.weight_is_fixed) threshold += "*"; // split weight fixed - node_label = fmt::format("{} >= {}?", feature, threshold); + if (parent->data.get_feature_type() == DataType::ArrayB) + node_label = fmt::format("{}?", feature); + else if (parent->data.get_feature_type() == DataType::ArrayI + && !parent->data.split_categories.empty()) + node_label = fmt::format("{} in {{{}}}?", feature, + fmt::join(parent->data.split_categories, ",")); + else + node_label = fmt::format("{} {} {}?", feature, + parent->data.get_feature_type() == DataType::ArrayI ? "==" : ">=", threshold); } if (Is(parent->data.node_type)){ node_label = fmt::format("Add"); @@ -584,7 +572,7 @@ template struct Program // string kid_id = fmt::format("{}",fmt::ptr(kid)); // kid_id = kid_id.substr(2); - if (kid->data.get_is_weighted() + if (kid->data.get_is_weighted() && IsWeighable(kid->data.node_type) && Isnt(kid->data.node_type)) { @@ -594,7 +582,7 @@ template struct Program if (Is(parent->data.node_type)){ use_head_tail_labels=true; if (j == 0) - tail_label = fmt::format(">= {:.2f}",parent->data.W); + tail_label = "condition"; else if (j==1) tail_label = "Y"; else From e84d38799053ab968ebacea889626fcb08202b8d Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 14:28:20 -0500 Subject: [PATCH 12/25] using protected div during jet optimization --- src/program/functions.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/program/functions.h b/src/program/functions.h index 7019d704..548ce93c 100644 --- a/src/program/functions.h +++ b/src/program/functions.h @@ -77,7 +77,29 @@ namespace Brush struct Function { template + requires (!is_one_of_v) inline auto operator()(const T1& t1, const T2& t2) { return t1 / t2 ; } + + template + requires is_one_of_v + inline auto operator()(const T1& t1, const T2& t2) { + auto result = t1.eval(); + for (Eigen::Index i = 0; i < t1.size(); ++i) { + int numerator, denominator; + if constexpr (std::is_same_v) { + numerator = t1(i).a; + denominator = t2(i).a; + } else { + numerator = t1(i); + denominator = t2(i); + } + int value = denominator == 0 ? 0 + : numerator == std::numeric_limits::min() && denominator == -1 + ? std::numeric_limits::max() : numerator / denominator; + result(i) = typename T1::Scalar(value); + } + return result; + } }; From 06d782b4f75861eb3562c849174594c4a8cff75a Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:00:02 -0500 Subject: [PATCH 13/25] bandit updates on all sampled nodes, not just one. Avoid fitting offspring identical to parent --- src/vary/variation.cpp | 91 +++++++++++++++++++++++++++++------------- 1 file changed, 64 insertions(+), 27 deletions(-) diff --git a/src/vary/variation.cpp b/src/vary/variation.cpp index f36b21aa..1752e090 100644 --- a/src/vary/variation.cpp +++ b/src/vary/variation.cpp @@ -9,6 +9,38 @@ using namespace Pop; using namespace MAB; namespace { +// A successful operator can still reproduce its parent exactly. Compare the +// complete node state, including unrounded weights and split thresholds, so an +// unchanged copy keeps its fitted parameters. +template +bool same_fitted_expression(const Individual& parent, const Program& child) +{ + // fast checks first. then we do the node-by-node check. Idea here is to avoid + // fitting expressions unnecessarily, because for large datasets it becomes + // a huge burden + if (!parent.get_is_fitted() || !parent.program.is_fitted_ || !child.is_fitted_ + || parent.program.Tree.size() != child.Tree.size()) + return false; + + auto left = parent.program.Tree.begin(); + auto right = child.Tree.begin(); + for (; left != parent.program.Tree.end(); ++left, ++right) { + const Node& a = *left; + const Node& b = *right; + // TODO: should I overload the comparison operator instead of this ugly thing? + if (a.name != b.name || a.node_type != b.node_type || a.ret_type != b.ret_type + || a.arg_types != b.arg_types || a.sig_hash != b.sig_hash + || a.sig_dual_hash != b.sig_dual_hash || a.node_is_fixed != b.node_is_fixed + || a.weight_is_fixed != b.weight_is_fixed || a.is_weighted != b.is_weighted + || a.prob_change != b.prob_change || a.W != b.W || a.center_op != b.center_op + || a.get_feature() != b.get_feature() || a.get_feature_type() != b.get_feature_type() + || a.get_keep_split_feature() != b.get_keep_split_feature() + || a.split_categories != b.split_categories) + return false; + } + return true; +} + enum class MutationType { Point, Insert, @@ -73,7 +105,7 @@ class PointMutation : public MutationBase public: template static auto mutate(Program& program, Iter spot, Variation& variator, - const Parameters& params) + const Parameters& params, vector& sampled) { // get_node_like will sample a similar node based on node_map_weights or // terminal_weights, and maybe will return a Node. @@ -94,6 +126,7 @@ class PointMutation : public MutationBase } // if optional contains a Node, we access its contained value as an address + sampled.push_back(*newNode); program.Tree.replace(spot, *newNode); return true; @@ -143,7 +176,7 @@ class InsertMutation : public MutationBase template static auto mutate(Program& program, Iter spot, Variation& variator, - const Parameters& params) + const Parameters& params, vector& sampled) { auto spot_type = spot.node->data.ret_type; @@ -161,6 +194,8 @@ class InsertMutation : public MutationBase if (!n) // there is no operator with compatible arguments return false; + sampled.push_back(*n); + // moving the fixed weight to the new inserted node // (this should be done before Tree.wrap, because that function affects the spot reference) if (IsWeighable(spot.node->data.node_type) && spot.node->data.weight_is_fixed){ @@ -193,6 +228,7 @@ class InsertMutation : public MutationBase if (!opt) return false; + sampled.push_back(*opt); program.Tree.append_child(parent_node, opt.value()); } // if types match, treat this spot as filled by the spot node @@ -205,6 +241,7 @@ class InsertMutation : public MutationBase if (!opt) return false; + sampled.push_back(*opt); program.Tree.insert(spot, opt.value()); } } @@ -247,7 +284,7 @@ class DeleteMutation : public MutationBase template static auto mutate(Program& program, Iter spot, Variation& variator, - const Parameters& params) + const Parameters& params, vector& sampled) { // sample_terminal will sample based on terminal_weights. If it succeeds, // then the new terminal will be in `opt.value()` @@ -257,6 +294,8 @@ class DeleteMutation : public MutationBase if (!opt) // there is no terminal with compatible arguments return false; + sampled.push_back(*opt); + program.Tree.erase_children(spot); program.Tree.replace(spot, opt.value()); @@ -290,7 +329,8 @@ class ToggleWeightOnMutation : public MutationBase // only weighted nodes can be toggled off if ((!n.get_is_weighted()) && (!n.weight_is_fixed) - && IsWeighable(n.node_type)) + && IsWeighable(n.node_type) + && IsWeighable(n.ret_type)) { return n.get_prob_change(); } @@ -311,7 +351,8 @@ class ToggleWeightOnMutation : public MutationBase const Parameters& params) { if (spot.node->data.get_is_weighted()==true // cant turn on whats already on - || !IsWeighable(spot.node->data.node_type)) // does not accept weights (e.g. boolean) + || !IsWeighable(spot.node->data.node_type) + || !IsWeighable(spot.node->data.ret_type)) // discrete values have no optimizer weights return false; // false indicates that mutation failed and should return std::nullopt spot.node->data.set_is_weighted(true); @@ -378,8 +419,6 @@ class SubtreeMutation : public MutationBase { vector weights; - auto node_map = variator.search_space.node_map; - // The minimal size increment would be 2 - replacing a constant with a weighted terminal. // we dont check for size constraints because the replacement can shrink the tree. Iter iter = program.Tree.begin(); @@ -390,8 +429,7 @@ class SubtreeMutation : public MutationBase std::advance(iter, 1); // we need to make sure there's some node to start the subtree - if ((d >= params.max_depth) - || (node_map.find(n.ret_type) == node_map.end()) ) + if (d >= params.max_depth) return 0.0f; else return n.get_prob_change(); @@ -581,6 +619,7 @@ std::optional> Variation::cross( // fmt::print("other_spot : {}\n",other_spot.node->data); // swap subtrees at child_spot and other_spot child.Tree.move_ontop(child_spot, other_spot); + child.is_fitted_ = same_fitted_expression(mom, child); Individual ind(child); ind.set_variation(mutation_type_to_string(MutationType::Crossover)); @@ -711,15 +750,16 @@ std::optional> Variation::mutate( // program tree. Here we call the mutation function and return the result bool success; + vector sampled; switch (mutation_choice) { case MutationType::Point: - success = PointMutation::mutate(child, spot, (*this), parameters); + success = PointMutation::mutate(child, spot, (*this), parameters, sampled); break; case MutationType::Insert: - success = InsertMutation::mutate(child, spot, (*this), parameters); + success = InsertMutation::mutate(child, spot, (*this), parameters, sampled); break; case MutationType::Delete: - success = DeleteMutation::mutate(child, spot, (*this), parameters); + success = DeleteMutation::mutate(child, spot, (*this), parameters, sampled); break; case MutationType::Subtree: success = SubtreeMutation::mutate(child, spot, (*this), parameters); @@ -745,6 +785,7 @@ std::optional> Variation::mutate( // loose mutation --- it will try its best, but may return something slightly larger. // || attempts==3 // this is the final attempt, return whatever we got. ){ + child.is_fitted_ = same_fitted_expression(parent, child); Individual ind(child); ind.set_variation(choice); @@ -760,7 +801,7 @@ std::optional> Variation::mutate( || choice.compare("insert") == 0 || choice.compare("delete") == 0 ) { - ind.set_sampled_nodes({spot.node->data}); + ind.set_sampled_nodes(sampled); } return ind; @@ -832,7 +873,6 @@ void Variation::vary(Population& pop, int island, ind.set_objectives(mom.get_objectives()); // it will have an invalid fitness - ind.is_fitted_ = false; ind.set_id(id); // TODO: smarter way of copying the entire fitness @@ -880,20 +920,17 @@ void Variation::update_ss() auto terminal_probs = bandit.second.sample_probs(true); for (auto& [terminal_name, terminal_prob] : terminal_probs) { - // Search for the index that matches the terminal name - auto it = std::find_if( - search_space.terminal_map.at(datatype).begin(), - search_space.terminal_map.at(datatype).end(), - [&](auto& node) { return node.get_feature() == terminal_name; }); - - if (it == search_space.terminal_map.at(datatype).end()) { + const auto& nodes = search_space.terminal_map.at(datatype); + auto& weights = search_space.terminal_weights.at(datatype); + float total = 0.0f; + for (size_t i = 0; i < nodes.size(); ++i) + if (terminal_arm(nodes[i]) == terminal_name) + total += weights[i]; + if (total <= 0.0f) continue; - } - - auto index = std::distance(search_space.terminal_map.at(datatype).begin(), it); - - // Update the terminal weights with the second value - search_space.terminal_weights.at(datatype)[index] = terminal_prob; + for (size_t i = 0; i < nodes.size(); ++i) + if (terminal_arm(nodes[i]) == terminal_name) + weights[i] = terminal_prob * weights[i] / total; } } From b7c55da9b23455b6d746a55f0e8cd02592fe03b1 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:02:19 -0500 Subject: [PATCH 14/25] utility to track progress and measure remaining time --- src/util/progress.h | 54 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/util/progress.h diff --git a/src/util/progress.h b/src/util/progress.h new file mode 100644 index 00000000..efcced6d --- /dev/null +++ b/src/util/progress.h @@ -0,0 +1,54 @@ +#ifndef BRUSH_UTIL_PROGRESS_H +#define BRUSH_UTIL_PROGRESS_H + +#include +#include +#include +#include +#include +#include +#include + +namespace Brush::Util { + +inline std::string format_duration(double seconds) +{ + const auto total = static_cast(std::round(std::max(0.0, seconds))); + return fmt::format("{:02}:{:02}:{:02}", total / 3600, (total / 60) % 60, total % 60); +} + +class RecentGenerationTimes { +public: + void record(double seconds) + { + if (durations.size() == window_size) + durations.pop_front(); + durations.push_back(seconds); + } + + // Time limits are checked between generations, so a generation started + // before the deadline can finish after it. + std::optional remaining(size_t generations, + std::optional time_limit_remaining = std::nullopt) const + { + if (generations == 0 || (time_limit_remaining && *time_limit_remaining <= 0)) + return 0.0; + if (durations.empty()) + return std::nullopt; + + const double average = std::accumulate(durations.begin(), durations.end(), 0.0) + / durations.size(); + double estimate = average * generations; + if (time_limit_remaining && average > 0) + estimate = std::min(estimate, average * std::ceil(*time_limit_remaining / average)); + return estimate; + } + +private: + static constexpr size_t window_size = 10; + std::deque durations; +}; + +} // namespace Brush::Util + +#endif From f802e3860fe04bb76fa10de2490d4f508879f842 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:03:28 -0500 Subject: [PATCH 15/25] bandit updates all sampled nodes. better bandit code, also learns when constants are useful. --- src/vary/variation.h | 175 +++++++++++++++++++++++-------------------- 1 file changed, 93 insertions(+), 82 deletions(-) diff --git a/src/vary/variation.h b/src/vary/variation.h index fb8722bd..0219358c 100644 --- a/src/vary/variation.h +++ b/src/vary/variation.h @@ -67,6 +67,14 @@ class Variation { */ ~Variation() {}; + static string terminal_arm(const Node& node) { + if (node.node_type == NodeType::Constant) { + if (node.ret_type == DataType::ArrayI) return "Constant:ArrayI"; + if (node.ret_type == DataType::ArrayB) return "Constant:ArrayB"; + } + return NodeTypeName.at(node.node_type) + ":" + node.get_feature(); + } + /** * @brief Initializes the Variation object with parameters and search space. * @@ -103,8 +111,8 @@ class Variation { // TODO: do not insert if coefficient is smaller than zero. Fix bandits to work with that if (entry.second[i] > 0.0) { - auto node_name = search_space.terminal_map.at(entry.first).at(i).get_feature(); - terminal_probs[node_name] = entry.second[i]; + auto node_name = terminal_arm(search_space.terminal_map.at(entry.first).at(i)); + terminal_probs[node_name] += entry.second[i]; } if (terminal_probs.size()>0) @@ -154,7 +162,18 @@ class Variation { // ensuring all terminals exists as a simplification option // Only initialize simplification tables if inexact_simplification is enabled if (parameters.inexact_simplification) { - inexact_simplifier.init(256, data, 1); + // All hashes must use the same rows and fit the simplifier's + // 1000-row limit, including when training uses smaller batches. + Dataset training = data.get_training_data(); + const auto count = std::min(1000, training.get_n_samples()); + vector indices(training.get_n_samples()); + std::iota(indices.begin(), indices.end(), 0); + if (indices.size() > static_cast(count)) { + r.shuffle(indices.begin(), indices.end()); + indices.resize(count); + } + simplification_data = training(indices); + inexact_simplifier.init(256, *simplification_data, 1); for (const auto& entry : this->search_space.terminal_weights) { map terminal_probs; for (int i = 0; i < entry.second.size(); i++) @@ -165,7 +184,7 @@ class Variation { tree dummy_tree; dummy_tree.insert(dummy_tree.begin(), node); auto it = dummy_tree.begin(); - inexact_simplifier.index(it, data.get_training_data()); + inexact_simplifier.index(it, *simplification_data); } } } @@ -210,6 +229,54 @@ class Variation { */ void update_ss(); + void reward_variation(const string& choice, const Individual& ind, float reward) + { + if (choice.empty()) + return; + const bool succeeded = ind.get_variation() == choice; + variation_bandit.update(choice, succeeded ? reward : 0.0f); + if (!succeeded) + return; + for (const auto& node : ind.get_sampled_nodes()) { + if (node.get_arg_count() == 0) { + auto it = terminal_bandits.find(node.get_ret_type()); + if (it != terminal_bandits.end()) + it->second.update(terminal_arm(node), reward); + } else { + auto ret = op_bandits.find(node.get_ret_type()); + if (ret != op_bandits.end()) { + auto args = ret->second.find(node.args_type()); + if (args != ret->second.end()) + args->second.update(node.name, reward); + } + } + } + } + + /// Apply the configured simplifiers to an already fitted expression. + void simplify_individual(Individual& ind, const Dataset& score_data, + bool do_simplification) + { + SimplificationRecords records; + SimplificationRecords* records_ptr = parameters.logfile.empty() ? nullptr : &records; + if (parameters.constants_simplification && do_simplification) + constants_simplifier.simplify_tree(ind.program, search_space, + score_data.get_training_data(), records_ptr); + if (parameters.inexact_simplification) { + if (do_simplification) + inexact_simplifier.simplify_tree(ind.program, search_space, + *simplification_data, records_ptr); + else + inexact_simplifier.analyze_tree(ind.program, search_space, + *simplification_data); + } + for (auto& rec : records) { + rec.generation = parameters.current_gen; + rec.individual_id = ind.get_id(); + simplification_records.push_back(std::move(rec)); + } + } + /** * @brief Varies a population and updates the selection strategy based on rewards. * @@ -265,10 +332,10 @@ class Variation { ind = Individual(); ind.init(search_space, parameters); - // Alternative: keep it as it is, and just re-fit the constants - // (comment out just the line below to disable, but keep ind.init) + // Keep the fitted program when variation cannot change it. Program copy(mom.program); ind.program = copy; + ind.set_is_fitted(mom.get_is_fitted()); ind.variation = "clone"; } else @@ -320,6 +387,7 @@ class Variation { // fallback: mark as a subtree attempt that failed to produce a new individual Program copy(mom.program); ind.program = copy; + ind.set_is_fitted(mom.get_is_fitted()); ind.variation = "clone"; } } @@ -344,44 +412,13 @@ class Variation { assert(ind.program.size() > 0); assert(ind.fitness.valid() == false); - ind.program.fit(data.get_training_data(), parameters.class_weights); - - // simplify before calculating fitness (order matters, as they are not refitted and constants simplifier does not replace with the right value.) - // simplify constants first to avoid letting the lsh simplifier to visit redundant branches - - // replacements are only recorded when they are going to be logged - SimplificationRecords records; - SimplificationRecords* records_ptr = parameters.logfile.empty() ? nullptr : &records; - - if (parameters.constants_simplification && do_simplification) - { - constants_simplifier.simplify_tree(ind.program, search_space, data.get_training_data(), records_ptr); + if (!ind.get_is_fitted() || !ind.program.is_fitted_) { + ind.program.fit(data.get_training_data(), parameters.class_weights); + ind.set_is_fitted(true); } - if (parameters.inexact_simplification) - { - auto inputDim = std::min(inexact_simplifier.inputDim, data.get_training_data().get_n_samples()); - - vector idx(inputDim); - std::iota(idx.begin(), idx.end(), 0); - Dataset data_simp = data(idx); - - if (do_simplification) - { - inexact_simplifier.simplify_tree(ind.program, search_space, data_simp, records_ptr); - } - else - { - inexact_simplifier.analyze_tree(ind.program, search_space, data_simp); - } - } - - for (auto& rec : records) - { - rec.generation = parameters.current_gen; - rec.individual_id = id; - simplification_records.push_back(std::move(rec)); - } + // Simplify constants first, then look for inexact replacements. + simplify_individual(ind, data, do_simplification); evaluator.assign_fit(ind, data, parameters, false, validation_data); @@ -440,35 +477,7 @@ class Variation { if (allPositive && !allNegative) r = 1.0; - if (!ind.get_variation().compare("born") - && !ind.get_variation().compare("cx") - && !ind.get_variation().compare("subtree") // TODO: handle subtree - ) - { - this->variation_bandit.update(ind.get_variation(), r); - - if (ind.get_sampled_nodes().size() > 0) { - const auto& changed_nodes = ind.get_sampled_nodes(); - for (auto& node : changed_nodes) { - if (node.get_arg_count() == 0) { - auto datatype = node.get_ret_type(); - - this->terminal_bandits[datatype].update(node.get_feature(), r); - } - else { - auto ret_type = node.get_ret_type(); - auto args_type = node.args_type(); - auto name = node.name; - - this->op_bandits[ret_type][args_type].update(name, r); - } - } - } - } - else - { // giving zero reward if the variation failed - this->variation_bandit.update(choice, 0.0); - } + reward_variation(choice, ind, r); // aux_individuals.push_back(std::make_shared>(ind)); pop.individuals.at(indices.at(i)) = std::make_shared>(ind); @@ -500,18 +509,19 @@ class Variation { auto& bandit = terminal_bandits.at(R); string terminal_name = bandit.choose(); - auto it = std::find_if( - search_space.terminal_map.at(R).begin(), - search_space.terminal_map.at(R).end(), - [&](auto& node) { return node.get_feature() == terminal_name; }); - - if (it != search_space.terminal_map.at(R).end()) { - auto index = std::distance(search_space.terminal_map.at(R).begin(), it); - - return search_space.terminal_map.at(R).at(index); + vector matches; + vector weights; + const auto& nodes = search_space.terminal_map.at(R); + const auto& node_weights = search_space.terminal_weights.at(R); + for (size_t i = 0; i < nodes.size(); ++i) { + if (terminal_arm(nodes[i]) == terminal_name && node_weights[i] > 0.0f) { + matches.push_back(nodes[i]); + weights.push_back(node_weights[i]); + } } - - return std::nullopt; + if (matches.empty()) + return std::nullopt; + return *r.select_randomly(matches.begin(), matches.end(), weights.begin(), weights.end()); }; // bandit_get_node_like @@ -645,6 +655,7 @@ class Variation { // simplification methods Constants_simplifier constants_simplifier; Inexact_simplifier inexact_simplifier; + std::optional simplification_data; SimplificationRecords simplification_records; ///< replacements not yet logged }; From 594729c82e532b1d47c702f9ed32031e495190a0 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:09:55 -0500 Subject: [PATCH 16/25] sample op first, then one of its signatures --- src/vary/search_space.h | 55 ++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/src/vary/search_space.h b/src/vary/search_space.h index 7ac85c38..ad9d56f0 100644 --- a/src/vary/search_space.h +++ b/src/vary/search_space.h @@ -383,7 +383,10 @@ struct SearchSpace /// @return `std::optional` that may contain a terminal Node of type `R`. std::optional sample_terminal(DataType R, bool force_return=false) const { - // should I keep doing this check? + if (terminal_map.find(R) == terminal_map.end() + || terminal_weights.find(R) == terminal_weights.end()) + return std::nullopt; + // TODO: should I keep doing this check? // if (terminal_map.find(R) == terminal_map.end()){ // auto msg = fmt::format("{} not in terminal_map\n",R); // HANDLE_ERROR_THROW(msg); @@ -426,32 +429,36 @@ struct SearchSpace /// @return `std::optional` that may contain a randomly chosen operator matching return type `ret` std::optional sample_op(DataType ret) const { - check(ret); if (node_map.find(ret) == node_map.end()) return std::nullopt; - - //TODO: match terminal args_type (probably '{}' or something?) - auto ret_match = node_map.at(ret); - - vector args_w = get_weights(ret); - - if (!has_solution_space(args_w.begin(), args_w.end())) - return std::nullopt; - - auto arg_match = *r.select_randomly(ret_match.begin(), - ret_match.end(), - args_w.begin(), - args_w.end()); - - vector name_w = get_weights(ret, arg_match.first); - - if (!has_solution_space(name_w.begin(), name_w.end())) + // User weights describe operators, not the number of signatures an + // operator happens to expose. Pick a node type first, then a signature. + // The idea is to avoid giving higher probabilities to an operator that + // has more signatures. + map>> by_type; + for (const auto& [signature, nodes] : node_map.at(ret)) + for (const auto& [type, node] : nodes) { + float weight = node_map_weights.at(ret).at(signature).at(type); + if (weight > 0.0f) + by_type[type].emplace_back(node, weight); + } + if (by_type.empty()) return std::nullopt; - return (*r.select_randomly(arg_match.second.begin(), - arg_match.second.end(), - name_w.begin(), - name_w.end())).second; + vector type_weights; + for (const auto& [type, entries] : by_type) { + float total = 0.0f; + for (const auto& entry : entries) + total += entry.second; + type_weights.push_back(total / entries.size()); + } + auto chosen = r.select_randomly(by_type.begin(), by_type.end(), + type_weights.begin(), type_weights.end()); + vector signature_weights; + for (const auto& entry : chosen->second) + signature_weights.push_back(entry.second); + return r.select_randomly(chosen->second.begin(), chosen->second.end(), + signature_weights.begin(), signature_weights.end())->first; }; /// @brief Get a specific node type that matches a return value. @@ -460,7 +467,6 @@ struct SearchSpace /// @return `std::optional` that may contain a Node of type `type` with return type `R`. std::optional sample_op(NodeType type, DataType R, bool force_return=false) const { - check(R); if (node_map.find(R) == node_map.end()) return std::nullopt; @@ -499,7 +505,6 @@ struct SearchSpace size_t arg_count, bool force_return=false) const { - check(R); if (node_map.find(R) == node_map.end()) return std::nullopt; From 7f4bf5247a4def2e6c1fddd152298a242fe16033 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:12:35 -0500 Subject: [PATCH 17/25] add int constants from observed categories, and False constant as well. Because we want to use Int as categories, we also need to make sure each category exists in the data, so they can be sampled as terminals. weights_init should help prioritize some of them, and bandits should learn their utilities --- src/vary/search_space.cpp | 100 ++++++++++++++++++++++++++++---------- 1 file changed, 73 insertions(+), 27 deletions(-) diff --git a/src/vary/search_space.cpp b/src/vary/search_space.cpp index 85c8ce42..ce2f0fd3 100644 --- a/src/vary/search_space.cpp +++ b/src/vary/search_space.cpp @@ -66,6 +66,7 @@ vector generate_terminals(const Dataset& d, const bool weights_init) weighted, feature_name ); + n.set_feature_type(DataTypeEnum::value); float prob_change = 1.0; // default value @@ -148,16 +149,38 @@ vector generate_terminals(const Dataset& d, const bool weights_init) cXf.set_prob_change(signature_avg(cXf.ret_type)); terminals.push_back(cXf); - // Reminder: Integers are used to represent categorical variables + // Integer values are discrete, so make observed category values available + // to mutation instead of expecting gradient descent to learn them. + std::set category_values; + for (const auto& [name, value] : d.features) { + if (const auto* column = std::get_if(&value)) + for (int category : *column) + category_values.insert(category); + } auto cXi = Node(NodeType::Constant, Signature(), true, "constI"); - cXi.set_prob_change(signature_avg(cXi.ret_type)); + const size_t n_integer_constants = 1 + category_values.size() - category_values.count(1); + const float integer_constant_weight = signature_avg(cXi.ret_type) / n_integer_constants; + cXi.set_prob_change(integer_constant_weight); terminals.push_back(cXi); + for (int category : category_values) { + if (category == 1) + continue; + auto constant = Node(NodeType::Constant, Signature(), true, + fmt::format("const{}I", category)); + constant.W = static_cast(category); + constant.set_prob_change(integer_constant_weight); + terminals.push_back(constant); + } // Boolean constants are needed to prevent crashes when logical operators (And, Or, Not, Geq, Equals) // appear in programs and need boolean terminals as arguments, even in regression problems auto cXb = Node(NodeType::Constant, Signature(), true, "constB"); - cXb.set_prob_change(signature_avg(cXb.ret_type)); + cXb.set_prob_change(signature_avg(cXb.ret_type) / 2.0f); terminals.push_back(cXb); + auto false_constant = Node(NodeType::Constant, Signature(), false, "constFalseB"); + false_constant.W = 0.0f; + false_constant.set_prob_change(signature_avg(false_constant.ret_type) / 2.0f); + terminals.push_back(false_constant); // mean label node. Does not need to be part of symbols. works only for classification if (d.classification) @@ -204,8 +227,33 @@ void SearchSpace::init(const Dataset& d, const unordered_map& user // create nodes based on data types terminal_types = d.unique_data_types; + // Scalar constants are terminals even when the dataset has no feature of + // that type. In particular, comparisons can produce boolean conditions + // for SplitOn without requiring a boolean input column. + Util::unique_insert(terminal_types, DataType::ArrayF); + Util::unique_insert(terminal_types, DataType::ArrayI); + Util::unique_insert(terminal_types, DataType::ArrayB); vector terminals = generate_terminals(d, weights_init); + + // Float and boolean constants can close ordinary prediction trees. Only + // introduce integer operators when integers are present or can be produced + // by another available operator; otherwise they create constant-only + // categorical expressions on wholly continuous datasets. + vector operator_types = d.unique_data_types; + Util::unique_insert(operator_types, DataType::ArrayF); + Util::unique_insert(operator_types, DataType::ArrayB); + auto generate_operators = [&](const unordered_map& ops) { + bool changed; + do { + GenerateNodeMap(ops, operator_types, + std::make_index_sequence()); + changed = node_map.find(DataType::ArrayI) != node_map.end() + && !in(operator_types, DataType::ArrayI); + if (changed) + operator_types.push_back(DataType::ArrayI); + } while (changed); + }; // If it is a classification problem, we need to add the fixed root nodes // (logistic for binary classification, softmax for multiclassification). @@ -256,13 +304,11 @@ void SearchSpace::init(const Dataset& d, const unordered_map& user } // fmt::print("generate nodetype\n"); - GenerateNodeMap(extended_user_ops, terminal_types, - std::make_index_sequence()); + generate_operators(extended_user_ops); } else { - GenerateNodeMap(user_ops, terminal_types, - std::make_index_sequence()); + generate_operators(user_ops); } // map terminals @@ -283,23 +329,20 @@ std::optional> SearchSpace::sample_subtree(Node root, int max_d, int { // public interface to use PTC2 algorithm - // PTC is designed to not fail (it will persistently try to find nodes with - // sampling functions). In pop initialization, this shoudnt be a problem, but - // during evolution, due to dynamic changes in node weights by the learners, - // it now may fail. We need to check, before calling it, that it has elements - // in search space to sample - auto ret_match = node_map.at(root.ret_type); - - vector args_w = get_weights(root.ret_type); - - // at least one operator that matches the weight must have positive probability - if (!has_solution_space(args_w.begin(), args_w.end())) + // Sample a new root of the required type. Retaining the old root made a + // subtree mutation on a terminal a successful no-op. + // because we initialize the search space with constants, there will always be + // one available terminal to fill the leaves. + std::optional replacement; + if (max_d > 1 && max_size > 1) + replacement = sample_op(root.ret_type); + if (!replacement) + replacement = sample_terminal(root.ret_type); + if (!replacement) return std::nullopt; - // it will always have a terminal (because we create constants). - auto Tree = tree(); - auto spot = Tree.insert(Tree.begin(), root); + auto spot = Tree.insert(Tree.begin(), *replacement); // we should notice the difference between size of a PROGRAM and a TREE. // program count weights in its size, while the TREE structure dont. Wenever @@ -330,11 +373,14 @@ tree& SearchSpace::PTC2(tree& Tree, Node root = spot.node->data; - // updating size accordingly to root node - if (Is(root.node_type) || Is(root.node_type)){ - s += 2; + // updating size accordingly to root node. This doesnt need to be + // exact calculations, just proxys. We just dont want huge trees + // being generated in the initial population. + if (Is(root.node_type)){ + s += 3; } else if ( root.get_is_weighted()==true + && IsWeighable(root.node_type) && Isnt(root.node_type) ) s += 2; @@ -434,11 +480,11 @@ tree& SearchSpace::PTC2(tree& Tree, // increment is different based on node weights ++s; - if (Is(n.node_type) || Is(n.node_type)){ - // cout << "sampled split on node/n"; - s += 2; + if (Is(n.node_type)){ + s += 3; } else if ( n.get_is_weighted()==true + && IsWeighable(n.node_type) && Isnt(n.node_type) ) s += 2; } From 47a0d6166b3e4b91eaf1a7de97420fb46e70b61a Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:15:25 -0500 Subject: [PATCH 18/25] better clamp of values in log loss --- src/eval/metrics.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/eval/metrics.cpp b/src/eval/metrics.cpp index 4bcd02ff..b3b1ed58 100644 --- a/src/eval/metrics.cpp +++ b/src/eval/metrics.cpp @@ -28,11 +28,10 @@ VectorXf log_loss(const VectorXf& y, const VectorXf& predict_proba, loss.resize(y.rows()); for (unsigned i = 0; i < y.rows(); ++i) { - if (predict_proba(i) < eps || 1 - predict_proba(i) < eps) - // clip probabilities since log loss is undefined for predict_proba=0 or predict_proba=1 - loss(i) = -(y(i)*log(eps) + (1-y(i))*log(1-eps)); - else - loss(i) = -(y(i)*log(predict_proba(i)) + (1-y(i))*log(1-predict_proba(i))); + // Clip either end independently: a prediction close to one must not + // be scored as if the positive-class probability were close to zero. + const float probability = std::clamp(predict_proba(i), eps, 1.0f - eps); + loss(i) = -(y(i)*log(probability) + (1-y(i))*log(1-probability)); if (loss(i)<0) std::runtime_error("loss(i)= " + to_string(loss(i)) From 90504b932a77a909fe9a74fb1718b74bcd38cf8f Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:19:17 -0500 Subject: [PATCH 19/25] updated inexact simplification to deal with log loss previously it was looking only on the predicted classes, which could lead to a simplification that affects the log loss drastically. now it should word fine : --- src/simplification/inexact.h | 99 ++++++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 27 deletions(-) diff --git a/src/simplification/inexact.h b/src/simplification/inexact.h index 7623f51a..20094a1a 100644 --- a/src/simplification/inexact.h +++ b/src/simplification/inexact.h @@ -136,16 +136,14 @@ class Inexact_simplifier void analyze_tree(Program

& program, const SearchSpace &ss, const Dataset &d) { - // iterate over the tree, trying to replace each node with a constant, and keeping the change if the pred does not change. - TreeIter spot = program.Tree.begin_post(); - while(spot != program.Tree.end_post()) + // Index eligible subtrees in postorder. + PostIter post = program.Tree.begin_post(); + while(post != program.Tree.end_post()) { - // we dont index or simplify fixed stuff. - // non-wheightable nodes are not simplified. TODO: revisit this and see if they should (then implement it) - // This is avoiding using booleans. - if (spot.node->data.get_prob_change() > 0 - // && IsWeighable(spot.node->data.ret_type) && IsWeighable(spot.node->data.node_type) - ) { + TreeIter spot(post); + // Do not index subtrees containing locked nodes. + if (supports_subtree

(spot.node->data.ret_type) + && can_replace_subtree(spot.node)) { // indexing only small subtrees. We don't index constants (the constant simplifier will take // care of them), but we index terminals, as they are weighted and may be added to different // hash collections @@ -156,7 +154,7 @@ class Inexact_simplifier // terminals are already indexed on initialization } } - ++spot; + ++post; } } @@ -175,21 +173,23 @@ class Inexact_simplifier Program

simplified_program(program); - // prediction at the root already performs template cast and always returns a float - auto original_predictions = simplified_program.predict(d); + // Classification labels alone hide changes to probabilities and log loss. + auto predictions = [&](Program

& candidate) { + if constexpr (P == PT::BinaryClassifier || P == PT::MulticlassClassifier) + return candidate.predict_proba(d); + else + return candidate.predict(d); + }; + const auto original_predictions = predictions(simplified_program); - // iterate over the tree, trying to replace each node with a constant, and keeping the change if the pred does not change. - // notice it is a post order iterator. - TreeIter spot = simplified_program.Tree.begin_post(); - while(spot != simplified_program.Tree.end_post()) + // Consider replacements in postorder, keeping the root predictions close. + PostIter post = simplified_program.Tree.begin_post(); + while(post != simplified_program.Tree.end_post()) { - // we dont index or simplify fixed stuff. - // non-wheightable nodes are not simplified. TODO: revisit this and see if they should (then implement it) - // This is avoiding using booleans. - // we do not simplify branches with fixed weights, because the simplification ignores the weight (it uses normalized predictions) - if (spot.node->data.get_prob_change() > 0 && !spot.node->data.weight_is_fixed - // && IsWeighable(spot.node->data.ret_type) && IsWeighable(spot.node->data.node_type) - ) { + TreeIter spot(post); + // Do not replace subtrees containing locked nodes or weights. + if (supports_subtree

(spot.node->data.ret_type) + && can_replace_subtree(spot.node)) { // TODO: use IsLeaf here instead of checking for each possible nodetype. also search throughout the code and replace it if (Isnt(spot.node->data.node_type)){ @@ -219,11 +219,35 @@ class Inexact_simplifier spot = simplified_program.Tree.move_ontop(spot, simplified_branch.begin()); - auto new_predictions = simplified_program.predict(d); + auto new_predictions = predictions(simplified_program); float diff = (original_predictions.template cast() - new_predictions.template cast()).square().mean(); - - if (diff < best_distance) { + bool preserves_log_probabilities = true; + bool preserves_labels = true; + if constexpr (P == PT::BinaryClassifier || P == PT::MulticlassClassifier) { + // A small absolute probability change near zero can cause a + // large log-loss change. Bound the change for every class. + constexpr float epsilon = 1e-6f; + const auto original_log = original_predictions.max(epsilon).min(1.0f - epsilon).log().eval(); + const auto new_log = new_predictions.max(epsilon).min(1.0f - epsilon).log().eval(); + float max_log_change = (original_log - new_log).abs().maxCoeff(); + if constexpr (P == PT::BinaryClassifier) { + const auto original_negative_log = (1.0f - original_predictions).max(epsilon).min(1.0f - epsilon).log().eval(); + const auto new_negative_log = (1.0f - new_predictions).max(epsilon).min(1.0f - epsilon).log().eval(); + max_log_change = std::max(max_log_change, + (original_negative_log - new_negative_log).abs().maxCoeff()); + preserves_labels = ((original_predictions > 0.5f) + == (new_predictions > 0.5f)).all(); + } else { + auto argmax = Function{}; + preserves_labels = (argmax(original_predictions) + == argmax(new_predictions)).all(); + } + preserves_log_probabilities = std::isfinite(max_log_change) + && max_log_change < std::sqrt(threshold); + } + + if (preserves_labels && preserves_log_probabilities && diff < best_distance) { best_distance = diff; best_branch = cand; } @@ -256,7 +280,10 @@ class Inexact_simplifier } } } - ++spot; + // Replacements can move or erase the current node, so resume + // postorder traversal from the node that is now in its place. + post = PostIter(spot); + ++post; } program.Tree = simplified_program.Tree; @@ -302,6 +329,24 @@ class Inexact_simplifier int inputDim = 1000; // default value private: + static bool can_replace_subtree(const TreeNode* node) + { + if (node->data.get_prob_change() <= 0 || node->data.weight_is_fixed) + return false; + for (auto child = node->first_child; child != nullptr; child = child->next_sibling) + if (!can_replace_subtree(child)) + return false; + return true; + } + + template + static bool supports_subtree(DataType type) + { + if constexpr (P == PT::Representer) + return type == DataType::MatrixF; + return type == DataType::ArrayF || type == DataType::ArrayI || type == DataType::ArrayB; + } + template vector hash(TreeIter& spot, const Dataset &d) { From c79465f2ebb2331b35964565a306515f0f01b860 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:22:20 -0500 Subject: [PATCH 20/25] updated fit arguments to handle class_weights. Split nodes are ignoring user defined class weights when finding split thresholds, lets fix that --- src/ind/individual.h | 5 ++++- src/program/dispatch_table.h | 4 ++-- src/program/operator.h | 38 ++++++++++++++++++------------------ src/program/program.h | 2 +- src/program/tree_node.h | 6 +++--- 5 files changed, 29 insertions(+), 26 deletions(-) diff --git a/src/ind/individual.h b/src/ind/individual.h index 9bf87e2d..e1d6be16 100644 --- a/src/ind/individual.h +++ b/src/ind/individual.h @@ -67,7 +67,10 @@ class Individual{ }; Individual &fit(const Dataset& data) { - program.fit(data); + return fit(data, {}); + }; + Individual &fit(const Dataset& data, const vector& class_weights) { + program.fit(data, class_weights); this->is_fitted_ = true; return *this; }; diff --git a/src/program/dispatch_table.h b/src/program/dispatch_table.h index 8dd985b7..b0723b1b 100644 --- a/src/program/dispatch_table.h +++ b/src/program/dispatch_table.h @@ -28,7 +28,7 @@ namespace Brush{ template R DispatchOp( const Data::Dataset& d, TreeNode& tn, const W** weights); template -R DispatchOp( const Data::Dataset& d, TreeNode& tn); +R DispatchOp( const Data::Dataset& d, TreeNode& tn, const vector& class_weights); //////////////////////////////////////////////////////////////////////////////// // Dispatch Table @@ -37,7 +37,7 @@ struct DispatchTable { template using Callable = typename std::conditional_t, + std::function&)>, std::function::type**)> >; diff --git a/src/program/operator.h b/src/program/operator.h index c8d94fcb..5b1ed48c 100644 --- a/src/program/operator.h +++ b/src/program/operator.h @@ -132,7 +132,7 @@ struct Operator /// get a std::array or eigen array of kids template requires(is_std_array_v || is_eigen_array_v) - T get_kids(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + T get_kids(const Dataset& d, TreeNode& tn, const W** weights, const vector& class_weights) const { T child_outputs; using arg_type = std::conditional_t, @@ -147,9 +147,9 @@ struct Operator HANDLE_ERROR_THROW("bad sibling ptr in get kids"); if constexpr (Fit){ if constexpr(is_std_array_v) - child_outputs.at(i) = sib->fit(d); + child_outputs.at(i) = sib->fit(d, class_weights); else - child_outputs.col(i) = sib->fit(d); + child_outputs.col(i) = sib->fit(d, class_weights); } else{ if constexpr(is_std_array_v) @@ -164,7 +164,7 @@ struct Operator /// gets one kid for a tuple of kids template - NthType get_kid(const Dataset& d, TreeNode& tn, const W** weights ) const + NthType get_kid(const Dataset& d, TreeNode& tn, const W** weights, const vector& class_weights) const { TreeNode* sib = tn.first_child; for (int i = 0; i < I; ++i) @@ -172,7 +172,7 @@ struct Operator sib= sib->next_sibling; } if constexpr(Fit) - return sib->fit>(d); + return sib->fit>(d, class_weights); else return sib->predict>(d,weights); }; @@ -187,9 +187,9 @@ struct Operator * @return a tuple with elements corresponding to each child node */ template requires(is_tuple_v) - T get_kids_seq(const Dataset& d, TreeNode& tn, const W** weights, std::index_sequence) const + T get_kids_seq(const Dataset& d, TreeNode& tn, const W** weights, const vector& class_weights, std::index_sequence) const { - return std::make_tuple(get_kid(d,tn,weights)...); + return std::make_tuple(get_kid(d,tn,weights,class_weights)...); }; /// @brief get a std::tuple of kids. Used when child arguments are different types. @@ -199,9 +199,9 @@ struct Operator /// @param weights option pointer to a weight array, used in place of node weight /// @return a tuple of the child arguments template requires(is_tuple_v) - T get_kids(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + T get_kids(const Dataset& d, TreeNode& tn, const W** weights, const vector& class_weights) const { - return get_kids_seq(d, tn, weights, std::make_index_sequence{}); + return get_kids_seq(d, tn, weights, class_weights, std::make_index_sequence{}); }; /////////////////////////////////////////////////////////////////////////// @@ -234,9 +234,9 @@ struct Operator /// @param weights option pointer to a weight array, used in place of node weight /// @return output values from applying operator function template - RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { - auto inputs = get_kids(d, tn, weights); + auto inputs = get_kids(d, tn, weights, class_weights); if constexpr (is_one_of_v) { // Nodes like Floor and Ceil can have is_weighted set (it only @@ -255,9 +255,9 @@ struct Operator // overloaded version for offset sum template requires is_in_v - RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { - auto inputs = get_kids(d, tn, weights); + auto inputs = get_kids(d, tn, weights, class_weights); if constexpr (is_one_of_v) { if (tn.data.get_is_weighted()) @@ -281,7 +281,7 @@ struct Operator // Standard C++ types template requires (is_one_of_v) - RetType eval(const Dataset& d, const TreeNode& tn, const W** weights=nullptr) const + RetType eval(const Dataset& d, const TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { if constexpr (is_one_of_v) { @@ -297,7 +297,7 @@ struct Operator // Jet types template requires( is_one_of_v) - RetType eval(const Dataset &d, const TreeNode &tn, const W **weights = nullptr) const + RetType eval(const Dataset &d, const TreeNode &tn, const W **weights = nullptr, const vector& class_weights = {}) const { using nonJetType = UnJetify_t; if constexpr (is_one_of_v) @@ -337,7 +337,7 @@ struct Operator using W = typename S::WeightType; template - RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { // Scalar w = get_weight(tn, weights); Scalar w = util::get_weight(tn, weights); @@ -403,7 +403,7 @@ struct Operator return RetType::Constant(d.get_n_samples(), d.get_n_features(), w); }; - RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const { + RetType eval(const Dataset& d, TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { if constexpr (Fit) return fit(d,tn); else @@ -425,10 +425,10 @@ inline R DispatchOp(const Dataset& d, TreeNode& tn, const W** weights) }; template -inline R DispatchOp(const Dataset& d, TreeNode& tn) +inline R DispatchOp(const Dataset& d, TreeNode& tn, const vector& class_weights) { const auto op = Operator{}; - return op.eval(d, tn); + return op.eval(d, tn, nullptr, class_weights); }; } // Brush diff --git a/src/program/program.h b/src/program/program.h index 93be8551..9c7ef9fb 100644 --- a/src/program/program.h +++ b/src/program/program.h @@ -156,7 +156,7 @@ template struct Program Program& fit(const Dataset& d, const vector& class_weights) { - TreeType out = Tree.begin().node->fit(d); + TreeType out = Tree.begin().node->fit(d, class_weights); this->is_fitted_ = true; update_weights(d, class_weights); // this->valid = true; diff --git a/src/program/tree_node.h b/src/program/tree_node.h index 7ff6fbbb..c6a17dca 100644 --- a/src/program/tree_node.h +++ b/src/program/tree_node.h @@ -39,7 +39,7 @@ class tree_node_ { // size: 5*4=20 bytes (on 32 bit arch), can be reduced Node data; template - auto fit(const Dataset& d); + auto fit(const Dataset& d, const vector& class_weights = {}); template auto predict(const Dataset& d, const float** weights=nullptr); @@ -63,10 +63,10 @@ using TreeNode = class tree_node_; #include "dispatch_table.h" template -auto TreeNode::fit(const Dataset& d) +auto TreeNode::fit(const Dataset& d, const vector& class_weights) { auto F = dtable_fit.template Get(data.node_type, data.sig_hash); - return F(d, (*this)); + return F(d, (*this), class_weights); }; template From 8be174c5b3a7cb5550e0422e554242fb9bcad158 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Wed, 18 Nov 2026 16:29:53 -0500 Subject: [PATCH 21/25] =?UTF-8?q?thresholds=20for=20categories=20(int)=20a?= =?UTF-8?q?nd=20booleans=20as=20well.=20=C3=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/program/split.h | 180 ++++++++++++++++++++++++++------------------ 1 file changed, 105 insertions(+), 75 deletions(-) diff --git a/src/program/split.h b/src/program/split.h index 2553d1f5..822c4ba9 100644 --- a/src/program/split.h +++ b/src/program/split.h @@ -51,14 +51,24 @@ namespace Split{ return ret; } float gini_impurity_index(const ArrayXf& classes, const vector& uc); - float gain(const ArrayXf& lsplit, const ArrayXf& rsplit, bool classification, - vector unique_classes); + float gain(const ArrayXf& lsplit, const ArrayXf& rsplit, bool classification, + vector unique_classes, const vector& class_weights = {}); template vector get_thresholds(const T& x); - tuple get_best_variable_and_threshold(const Dataset& d, TreeNode& tn); + struct Candidate { + string feature; + float threshold = 0.0f; + float score = MAX_FLT; + vector categories; + }; + Candidate best_category_split(const ArrayXi& x, const ArrayXf& y, bool classification, + const vector& class_weights = {}); + Candidate get_best_split(const Dataset& d, const vector& class_weights = {}); + ArrayXb category_mask(const ArrayXi& x, const vector& categories); template - tuple best_threshold(const T& x, const ArrayXf& y, bool classification) + tuple best_threshold(const T& x, const ArrayXf& y, bool classification, + const vector& class_weights = {}) { /* for each unique value in x, calculate the reduction in the * heuristic brought about by @@ -72,8 +82,7 @@ namespace Split{ vector all_thresholds = get_thresholds(x); //////////////////// shared ////////////////////// - float best_thresh, best_score = MAX_FLT; - int i = 0 ; + float best_thresh = 0.0f, best_score = MAX_FLT; vector unique_classes; if (classification) @@ -96,14 +105,13 @@ namespace Split{ continue; //TODO: templatize gain for classification/regression - float score = gain(lhs, rhs, classification, unique_classes); + float score = gain(lhs, rhs, classification, unique_classes, class_weights); /* fmt::print("threshold={}; lhs={};rhs={}; score = {}\n",thresh,lhs,rhs,score); */ - if (score < best_score || i == 0) + if (std::isfinite(score) && score < best_score) { best_score = score; best_thresh = thresh; } - ++i; } best_thresh = std::isinf(best_thresh)? @@ -115,59 +123,54 @@ namespace Split{ } template - void get_best_threshold_by_type(const Dataset& d, auto& results) + void get_best_threshold_by_type(const Dataset& d, auto& results, + const vector& class_weights) { DataType DT = DataTypeEnum::value; /* fmt::print("get_best_threshold_by_type [T = {}]\n",DT); */ - vector keys; - float best_score = MAX_FLT; - string feature=""; - float threshold=0.0; - int i = 0; + if (d.features_of_type.find(DT) == d.features_of_type.end()) + return; - if (d.features_of_type.find(DT) != d.features_of_type.end()) - keys = d.features_of_type.at(DT); - else + for (const auto& key : d.features_of_type.at(DT)) { - /* fmt::print("didn't find features of type {} in data\n",DT); */ - return; // std::make_tuple(feature, threshold, best_score); + Candidate candidate; + if constexpr (std::is_same_v) + candidate = best_category_split(std::get(d[key]), d.y, d.classification, class_weights); + else + tie(candidate.threshold, candidate.score) = + best_threshold(std::get(d[key]), d.y, d.classification, class_weights); + candidate.feature = key; + if (std::isfinite(candidate.score) && candidate.score < MAX_FLT) + results.push_back(std::move(candidate)); } - - for (const auto& key : keys) - { - float tmp_thresh, score; - - tie(tmp_thresh, score) = best_threshold(std::get(d[key]), d.y, d.classification); - // fmt::print("best threshold for {} = {:.3f}, score = {:.3f}\n",key,tmp_thresh,score); - if (score < best_score | i == 0) - { - best_score = score; - feature = key; - threshold = tmp_thresh; - } - ++i; - } - auto tmp = std::make_tuple(feature, threshold, best_score); - results.push_back(std::make_tuple(feature, threshold, best_score)); } template - auto get_best_thresholds(const Dataset&d, std::index_sequence) + auto get_best_thresholds(const Dataset&d, const vector& class_weights, + std::index_sequence) { /* fmt::print("get_best_thresholds\n"); */ - using entry = tuple; - auto compare = [](const entry& a, const entry& b){ - return (std::get<2>(a) < std::get<2>(b)); - }; - - vector results; + vector results; /* fmt::print("get_best_thresholds::results size:{}\n",results.size()); */ - (..., (get_best_threshold_by_type>(d, results))); + (..., (get_best_threshold_by_type>(d, results, class_weights))); /* fmt::print("getting best\n"); */ - auto best = std::ranges::min_element(results, compare); - /* fmt::print("best: {}\n",(*best)); */ - return (*best); + if (results.empty()) + return Candidate{}; + Candidate best = results.front(); + int ties = 1; + for (size_t i = 1; i < results.size(); ++i) { + const float tolerance = 1e-7f * std::max(1.0f, std::abs(best.score)); + if (results[i].score < best.score - tolerance) { + best = results[i]; + ties = 1; + } else if (std::abs(results[i].score - best.score) <= tolerance) { + ++ties; + if (Util::r.rnd_int(1, ties) == 1) + best = results[i]; + } + } + return best; } /// Stitches together outputs from left or right child based on threshold @@ -202,7 +205,21 @@ struct Operator f{}; return f(args...); }; */ static constexpr Function F{}; - std::array get_kids(const std::array& d, TreeNode& tn, const W** weights=nullptr) const + // Optimizer parameters are laid out in postorder, including subtrees + // receiving no samples. Advance past those parameters without evaluating + // a branch on an empty dataset. + static size_t count_weights(const TreeNode* node) + { + size_t count = 0; + for (auto child = node->first_child; child != nullptr; child = child->next_sibling) + count += count_weights(child); + const auto& n = node->data; + if (HasOptimizableWeight(n)) + ++count; + return count; + } + + std::array get_kids(const std::array& d, TreeNode& tn, const W** weights, const vector& class_weights) const { using arg_type = NthType<1>; std::array child_outputs; @@ -216,27 +233,32 @@ struct Operator 0) { if constexpr (Fit) - child_outputs.at(i) = sib->fit(d.at(i)); + child_outputs.at(i) = sib->fit(d.at(i), class_weights); else child_outputs.at(i) = sib->predict(d.at(i), weights); } + else if constexpr (!Fit) + { + if (weights != nullptr) + *weights += count_weights(sib); + } sib = sib->next_sibling; } return child_outputs; }; - RetType fit(const Dataset& d, TreeNode& tn) const { + RetType fit(const Dataset& d, TreeNode& tn, const vector& class_weights) const { auto& threshold = tn.data.W; // set feature and threshold if constexpr (NT == NodeType::SplitOn) { // split on first child - FirstArg split_feature = tn.first_child->fit(d); + FirstArg split_feature = tn.first_child->fit(d, class_weights); // get the best splitting threshold if (!tn.data.weight_is_fixed) // avoid changing fixed weights - tie(threshold, ignore) = Split::best_threshold(split_feature, d.y, d.classification); + tie(threshold, ignore) = Split::best_threshold(split_feature, d.y, d.classification, class_weights); } else // splitbest { @@ -250,51 +272,59 @@ struct Operator(values)) - tie(threshold, ignore) = Split::best_threshold(std::get(values), d.y, d.classification); - else if (std::holds_alternative(values)) - tie(threshold, ignore) = Split::best_threshold(std::get(values), d.y, d.classification); + tie(threshold, ignore) = Split::best_threshold(std::get(values), d.y, d.classification, class_weights); + else if (std::holds_alternative(values)) { + auto best = Split::best_category_split(std::get(values), d.y, d.classification, class_weights); + threshold = best.threshold; + tn.data.split_categories = std::move(best.categories); + } else if (std::holds_alternative(values)) - tie(threshold, ignore) = Split::best_threshold(std::get(values), d.y, d.classification); + tie(threshold, ignore) = Split::best_threshold(std::get(values), d.y, d.classification, class_weights); } } else // keep_split_feature == false { if (!tn.data.weight_is_fixed){ - string feature = ""; - tie(feature, threshold) = Split::get_best_variable_and_threshold(d, tn); - - tn.data.set_feature(feature); - tn.data.set_feature_type(d.get_feature_type(feature)); + auto best = Split::get_best_split(d, class_weights); + threshold = best.threshold; + tn.data.set_feature(best.feature); + tn.data.split_categories = std::move(best.categories); + if (!best.feature.empty()) + tn.data.set_feature_type(d.get_feature_type(best.feature)); } } } - return predict(d, tn); + return predict(d, tn, nullptr, class_weights); } - RetType predict(const Dataset& d, TreeNode& tn, const W** weights=nullptr) const + RetType predict(const Dataset& d, TreeNode& tn, const W** weights=nullptr, const vector& class_weights = {}) const { const auto& threshold = tn.data.W; const auto& feature = tn.data.get_feature(); // split the data ArrayXb mask; - if (feature == "") - { - mask.resize(d.get_n_samples()); - mask.fill(true); - } - else if constexpr (NT==NodeType::SplitBest) - mask = Split::threshold_mask(d[feature], threshold); - else { + if constexpr (NT==NodeType::SplitBest) { + if (feature.empty()) { + mask.resize(d.get_n_samples()); + mask.fill(true); + } else { + const auto& value = d[feature]; + if (!tn.data.split_categories.empty() && std::holds_alternative(value)) + mask = Split::category_mask(std::get(value), tn.data.split_categories); + else + mask = Split::threshold_mask(value, threshold); + } + } else { auto split_feature = tn.first_child->predict(d, weights); mask = Split::threshold_mask(split_feature, threshold); } std::array data_splits = d.split(mask); - auto child_outputs = get_kids(data_splits, tn, weights); + auto child_outputs = get_kids(data_splits, tn, weights, class_weights); // stitch together outputs // fmt::print("stitching outputs\n"); @@ -304,9 +334,9 @@ struct Operator& class_weights = {}) const { if constexpr (Fit) - return fit(d,tn); + return fit(d,tn,class_weights); else return predict(d,tn,weights); } From 60e7de79bf4912805ae52262dcfa967363326bf4 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Fri, 20 Nov 2026 12:35:09 -0500 Subject: [PATCH 22/25] updated documentation. feature type extraction to handle categories with >10 samples from a pandas dataframe or used defined types --- pybrush/EstimatorInterface.py | 87 ++++++++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 2 deletions(-) diff --git a/pybrush/EstimatorInterface.py b/pybrush/EstimatorInterface.py index 39b82384..632061de 100644 --- a/pybrush/EstimatorInterface.py +++ b/pybrush/EstimatorInterface.py @@ -7,6 +7,7 @@ import numpy as np import pandas as pd +from pandas.api.types import is_float_dtype, is_bool_dtype, is_integer_dtype, is_string_dtype from pybrush import Parameters, Dataset from typing import Union, List, Dict from collections.abc import Callable @@ -31,6 +32,11 @@ class EstimatorInterface(): verbosity : int, default 0 Controls level of printouts. Set 0 to disable all printouts, 1 for basic information, and 2 or more for detailed information. + For the native Brush estimators, when batching is enabled, print the + current epoch and batch, including the first batch used to fit the + initial population. Detailed output includes elapsed time and an + estimate based on the last ten generations, the generation limit, and + any time limit. Early stopping can end a run sooner. max_depth : int, default 10 Maximum depth of GP trees in the GP program. Use 0 for no limit. max_size : int, default 100 @@ -63,6 +69,16 @@ class EstimatorInterface(): A dictionary with keys naming the function set and values giving the probability of sampling them, or a list of functions which will be weighted uniformly. If empty, all available functions are included in the search space. + feature_types : list or dict, optional + Explicit feature types (``ArrayF``, ``ArrayI``, or ``ArrayB``), either + in column order or keyed by DataFrame column name. Unspecified columns + are inferred: binary values become ``ArrayB``, integral columns with at + most ten distinct values become ``ArrayI``, and other numeric columns + become ``ArrayF``. Use ``ArrayI`` for encoded categories of any cardinality. + DataFrame string and categorical columns are encoded consistently at + prediction time. For ``SplitBest``, unseen categories follow the other + branch. It searches all category partitions up to ten values; for larger + sets it considers target-ordered partitions and individual categories. initialization : {"uniform", "max_size"}, default "uniform" Distribution of sizes on the initial population. If `max_size`, then every expression is created with `max_size` nodes. If `uniform`, size will be @@ -132,7 +148,10 @@ class EstimatorInterface(): least once per epoch; after a minority class has exhausted its unique rows, examples from that class are sampled again so it remains present while the other classes finish their pass. Validation rows are never - batched. The final batch of an epoch may be smaller than requested to + batched. In the native engine, new or changed expressions are fitted on + their first batch; surviving expressions are rescored on subsequent + batches without reoptimizing their weights or split thresholds. The + final batch of an epoch may be smaller than requested to avoid immediately repeating the last unseen row of another class. Very small values can improve execution time, but also lead to underfit. sel : str, default 'lexicase' @@ -164,6 +183,10 @@ class EstimatorInterface(): the confidence interval estimated with the inner validation partition of the data passed to `fit` or `partial_fit`; + A `partial_fit` with `max_gens=0` retains the previously selected model + and does not run final model selection. It still updates the population + fitness and Pareto archive. + If a custom function is passed, then it should hhave the signature `Callable[[List[Dict], List[Dict]], Dict]]`, which means that it takes as arguments two lists of dicts (the entire population and the @@ -244,6 +267,7 @@ def __init__(self, logfile: str = "", random_state: int = None, class_weights: Union[str, List[float]] = "support", + feature_types: Union[List[str], Dict[str, str]] = None, ) -> None: self.pop_size = pop_size self.max_gens = max_gens @@ -279,6 +303,62 @@ def __init__(self, self.weights_init = weights_init self.validation_size = validation_size self.class_weights = class_weights + self.feature_types = feature_types + + def _prepare_feature_types(self, X): + self.feature_names_ = [] + self.feature_types_ = [] + self.category_levels_ = {} + if isinstance(X, pd.DataFrame): + self.feature_names_ = X.columns.to_list() + for name, dtype in X.dtypes.items(): + if isinstance(dtype, pd.CategoricalDtype) or is_string_dtype(dtype): + if X[name].isna().any(): + raise ValueError(f"Missing values are not supported in feature {name!r}") + self.category_levels_[name] = list(pd.Categorical(X[name]).categories) + self.feature_types_.append('ArrayI') + elif is_bool_dtype(dtype) or is_integer_dtype(dtype) or is_float_dtype(dtype): + # Dataset applies the same value-based inference for both input forms. + self.feature_types_.append('') + else: + raise ValueError(f"Unsupported data type for feature {name!r}") + else: + self.feature_names_ = [f"x_{i}" for i in range(X.shape[1])] + + feature_types = getattr(self, "feature_types", None) + if feature_types is not None: + if isinstance(feature_types, dict): + unknown = set(feature_types) - set(self.feature_names_) + if unknown: + raise ValueError(f"Unknown feature names in feature_types: {unknown}") + defaults = self.feature_types_ or [''] * len(self.feature_names_) + self.feature_types_ = [feature_types.get(name, default) + for name, default in zip(self.feature_names_, defaults)] + else: + self.feature_types_ = list(feature_types) + if len(self.feature_types_) != len(self.feature_names_): + raise ValueError("feature_types must contain one entry per feature") + if any(t not in ('', 'ArrayF', 'ArrayI', 'ArrayB') for t in self.feature_types_): + raise ValueError("feature_types entries must be ArrayF, ArrayI, or ArrayB") + + def _encode_categories(self, X): + array_input = isinstance(X, np.ndarray) + category_levels = getattr(self, "category_levels_", {}) + if array_input and category_levels: + if X.ndim != 2 or X.shape[1] != len(self.feature_names_): + raise ValueError("Input must have the same number of features as the training data") + X = pd.DataFrame(X, columns=self.feature_names_) + if not isinstance(X, pd.DataFrame): + return X + if X.columns.to_list() != getattr(self, "feature_names_", X.columns.to_list()): + raise ValueError("Feature names and order must match the training data") + encoded = X.copy() + for name, levels in category_levels.items(): + if X[name].isna().any(): + raise ValueError(f"Missing values are not supported in feature {name!r}") + # Reserve -1 for categories not observed during fit. + encoded[name] = pd.Index(levels).get_indexer(X[name]).astype(np.int32) + return encoded.to_numpy() if array_input else encoded def _wrap_parameters(self, y, **extra_kwargs): """ @@ -364,6 +444,7 @@ def _wrap_parameters(self, y, **extra_kwargs): params.validation_size = self.validation_size params.batch_size = self.batch_size params.feature_names = self.feature_names_ + params.feature_types = self.feature_types_ # Scorer is the metric associated with "scorer" objective. To optimize # something else, set it in the objectives list. @@ -408,7 +489,7 @@ def _wrap_parameters(self, y, **extra_kwargs): def _make_data(self, X, y=None, feature_names=[], feature_types=[], - validation_size=0.0, shuffle_split=False): + validation_size=0.0, shuffle_split=False, _encoded=False): """ Prepare the data for training or prediction. @@ -435,6 +516,8 @@ def _make_data(self, X, y=None, # before calling `_make_data` (so predict can be made with np arrays or # pd dataframes). + if not _encoded: + X = self._encode_categories(X) if isinstance(y, pd.Series): y = y.values if isinstance(X, pd.DataFrame): From a5f2ae577401eb9afc0c3746c79459c4b496b3f9 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Fri, 20 Nov 2026 12:38:01 -0500 Subject: [PATCH 23/25] partial fit with max_gens = 0 --- pybrush/BrushEstimator.py | 147 +++++++++++++++++--------------------- 1 file changed, 64 insertions(+), 83 deletions(-) diff --git a/pybrush/BrushEstimator.py b/pybrush/BrushEstimator.py index 1521b68f..a2f4fffb 100644 --- a/pybrush/BrushEstimator.py +++ b/pybrush/BrushEstimator.py @@ -23,8 +23,6 @@ from pybrush.EstimatorInterface import EstimatorInterface from pybrush import RegressorEngine, ClassifierEngine, MultiClassifierEngine -from pandas.api.types import is_float_dtype, is_bool_dtype, is_integer_dtype - def _ovr_macro(binary_metric): """Macro one-vs-rest average of a binary ranking metric, skipping classes that are absent (or the only class present) in `y_true`. Matches brush's @@ -93,36 +91,10 @@ def fit(self, X, y): if isinstance(self.random_state, int): set_brush_random_state(self.random_state) - self.feature_names_ = [] - self.feature_types_ = [] - if isinstance(X, pd.DataFrame): - self.feature_names_ = X.columns.to_list() - for values, dtype in zip(X.values.T, X.dtypes): - if is_bool_dtype(dtype): - self.feature_types_.append('ArrayB') - elif is_integer_dtype(dtype): - # For Brush, it does matter if it is realy an integer or a boolean in disguise - if np.all(np.logical_or(values == 0, values == 1)): - self.feature_types_.append('ArrayB') - else: - if len(np.unique(values))<=10: # Categories, encoded - self.feature_types_.append('ArrayI') - else: # Integers, we'll treat as floats so we can do all the math normally - self.feature_types_.append('ArrayF') - elif is_float_dtype(dtype): - self.feature_types_.append('ArrayF') - else: - raise ValueError( - "Unsupported data type. Please try using an " - "encoding method to convert the data to a supported " - "format.") - else: - # For numpy arrays, generate feature names in the correct order - # BEFORE creating the Dataset, so we maintain the column order - self.feature_names_ = [f"x_{i}" for i in range(X.shape[1])] + self._prepare_feature_types(X) # Beyong this point, X is not a dataframe anymore - X, y = check_X_y(X, y) + X, y = check_X_y(self._encode_categories(X), y) if self.mode == 'classification': # The C++ core indexes probability columns with class labels. Keep # that representation internal while preserving sklearn's original @@ -130,7 +102,8 @@ def fit(self, X, y): self.classes_, y = np.unique(y, return_inverse=True) y = y.astype(np.float32) - self.data_ = self._make_data(X, y, + # X has already been encoded above, before sklearn validation. + self.data_ = self._make_data(X, y, _encoded=True, feature_names=self.feature_names_, feature_types=self.feature_types_, validation_size=self.validation_size, @@ -139,7 +112,7 @@ def fit(self, X, y): # Get feature_types from the dataset if we didn't have them (numpy array case) # but DON'T overwrite feature_names_ because the dataset may return them # in alphabetical order due to std::map sorting! - if not self.feature_types_: # if it is not a pandas dataframe, then feature_types will be empty + if not self.feature_types_ or any(not t for t in self.feature_types_): self.feature_types_ = self.data_.get_feature_types() # These have a default behavior to return something meaningfull if @@ -182,9 +155,15 @@ def fit(self, X, y): return self def partial_fit(self, X, y, *, - lock_nodes_depth=0, keep_leaves_unlocked=True, keep_current_weights=False): + lock_nodes_depth=0, keep_leaves_unlocked=True, + keep_current_weights=False, refit=True): """ - Fit an estimator to X,y, without reseting the estimator. + Continue fitting the current population on X and y. + + With ``max_gens=0``, the population is refitted and reevaluated without + evolutionary or final model selection; enabled simplifiers run once. + Use it to re-evaluate the expressions and simplify them based on + their predictions. Parameters ---------- @@ -199,8 +178,17 @@ def partial_fit(self, X, y, *, keep_current_weights : bool, optional Whether to keep current weights at the spot they appear, and preventing them to be changed during optimization. Default is False. + refit : bool, default True + Fit every existing expression once on the first training batch. + Set ``batch_size=1.0`` to fit on the whole training partition. The + validation partition remains separate. Set to False to reevaluate + existing weights and split thresholds without fitting them again. """ + check_is_fitted(self, ["engine_", "classes_" if self.mode == "classification" else "best_estimator_"]) + if isinstance(self.random_state, int): + set_brush_random_state(self.random_state) + if isinstance(X, pd.DataFrame): assert self.feature_names_ == X.columns.to_list(), \ "Feature names must be the same as in data from previous fit" @@ -222,9 +210,10 @@ def partial_fit(self, X, y, *, # We need to update class weights, this is what is happening here. new_parameters = self._wrap_parameters(new_data.get_training_data().y) - # Using the same engine as before --- it will keep the population - assert self.engine_ is not None, \ - "You must call `fit` before calling `partial_fit`" + if self.pop_size != len(self.engine_.get_population()): + raise ValueError("pop_size cannot be changed between fit and partial_fit") + if self.num_islands != self.engine_.params.num_islands: + raise ValueError("num_islands cannot be changed between fit and partial_fit") # The logistic root is not affected by locking or unlocking. # It is fixed due to prob_change==0.0. @@ -233,10 +222,13 @@ def partial_fit(self, X, y, *, self.parameters_ = new_parameters self.engine_.params = new_parameters - # replicating the best individual - self.engine_.set_population([self.best_estimator_ for _ in range(self.pop_size)]) + # The selected individual may have left the current population. Keep + # it as a candidate without replacing every member with copies of it. + self.engine_.set_best_ind(self.best_estimator_) self.engine_.lock_nodes(lock_nodes_depth, keep_leaves_unlocked, keep_current_weights) + if refit: + self.engine_.invalidate_population_fit() self.engine_.fit(new_data) # self.engine_.lock_nodes(0, False, False) # unlocking everything @@ -248,9 +240,13 @@ def partial_fit(self, X, y, *, self.archive_ = self.engine_.get_archive() self.population_ = self.engine_.get_population() self.best_estimator_ = self.engine_.best_ind + self.data_ = new_data + self.train_ = new_data.get_training_data() + self.train_.set_batch_size(self.batch_size) + self.validation_ = new_data.get_validation_data() - if self.final_model_selection != "": - self._update_final_model(new_data.get_validation_data()) + if self.max_gens != 0 and self.final_model_selection != "": + self._update_final_model(self.validation_) return self @@ -259,19 +255,8 @@ def predict(self, X): check_is_fitted(self) - if isinstance(X, pd.DataFrame): - X = X.values - - assert isinstance(X, np.ndarray) - - # Need to provide feature names because reference does not store order. - # Some of the self. are created just after fitting the estimator, - # and they are properly serialized in the python-side. - data = Dataset(X=X, # ref_dataset=self.data_, - feature_types=self.feature_types_, - feature_names=self.feature_names_, - validation_size=0.0, - ) + data = self._make_data(X, feature_types=self.feature_types_, + feature_names=self.feature_names_) prediction = np.asarray(self.best_estimator_.program.predict(data)) if self.mode == 'classification': @@ -335,43 +320,45 @@ def eval(ind, sample=None): else: # accuracy, balanced accuracy, or regression metrics y_pred = np.array(ind.predict(data)) + sample_y = y[sample] + sample_pred = y_pred[sample] metric_kwargs = {} - if self.parameters_.scorer == "multi_log": + if self.parameters_.scorer in ["log", "multi_log"]: metric_kwargs["labels"] = np.arange(self.parameters_.n_classes) elif self.parameters_.scorer in ["precision", "recall"]: metric_kwargs["zero_division"] = 0 metric_kwargs["average"] = "macro" if multiclass else "binary" + # Match the native scorer when a binary AUROC sample has only + # one class: AUROC is undefined, and Brush returns 0.5. + if self.parameters_.scorer == "roc_auc" and not multiclass \ + and len(np.unique(sample_y)) < 2: + return 0.5 + # y_pred = np.nan_to_num(y_pred) # Protecting the evaluation # if user_defined, sample_weight is given by his custom weights. if # support, I calculate it here. otherwise, no weight is used if self.mode == 'classification' \ and (self.class_weights not in ['unbalanced'] and self.parameters_.scorer not in ['balanced_accuracy']): - sample_weight = [] if isinstance(self.class_weights, list): # using user-defined values - sample_weight = [self.class_weights[int(label)] for label in y] + sample_weight = np.array([self.class_weights[int(label)] for label in sample_y]) else: # support - # Calculate class weights by support - classes, counts = np.unique(y[sample], return_counts=True) - - support_weights = { - int(cls): len(y[sample]) / (len(classes)*count) - if count > 0 else 0.0 for cls, count in zip(classes, counts)} - - # classes and support weights are calculated with y[sample]. - # sample_weight will be indexed in the function call, so we use raw y. - sample_weight = [support_weights[int(label)] for label in y] - sample_weight = np.array(sample_weight) - return loss_f(y[sample], y_pred[sample], - sample_weight=sample_weight[sample], **metric_kwargs) + # Weight only sampled labels: a bootstrap sample may + # omit classes that are present in the full dataset. + classes, inverse, counts = np.unique( + sample_y, return_inverse=True, return_counts=True) + sample_weight = (len(sample_y) / (len(classes) * counts))[inverse] + return loss_f(sample_y, sample_pred, + sample_weight=sample_weight, **metric_kwargs) else: # unbalanced metrics, ignoring weights - return loss_f(y[sample], y_pred[sample], **metric_kwargs) + return loss_f(sample_y, sample_pred, **metric_kwargs) - np.random.seed(0) + seed = self.random_state if isinstance(self.random_state, (int, np.integer)) else 0 + bootstrap_rng = np.random.RandomState(seed) val_samples = [] for i in range(100): - sample = np.random.randint(0, len(y), size=len(y)) + sample = bootstrap_rng.randint(0, len(y), size=len(y)) val_samples.append( eval(self.best_estimator_, sample) ) lower_ci, upper_ci = np.quantile(val_samples,0.05), np.quantile(val_samples,0.95) @@ -410,6 +397,8 @@ def eval(ind, sample=None): class BrushClassifier(BrushEstimator, ClassifierMixin): """Brush with c++ engine for classification. + Supports two to five classes. Original class labels are preserved. + Parameters are defined and documented in :py:class:`EstimatorInterface ` @@ -448,16 +437,8 @@ def predict_proba(self, X): check_is_fitted(self) - if isinstance(X, pd.DataFrame): - X = X.values - - assert isinstance(X, np.ndarray) - - # Need to provide feature names because reference does not store order - data = Dataset(X=X, # ref_dataset=self.data_, - feature_types=self.feature_types_, - feature_names=self.feature_names_, - validation_size=0.0) + data = self._make_data(X, feature_types=self.feature_types_, + feature_names=self.feature_names_) prob = self.best_estimator_.program.predict_proba(data) From 3407e4e2b144ee0de77646211b1a472650226d19 Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Fri, 20 Nov 2026 13:06:37 -0500 Subject: [PATCH 24/25] splitBest also search for categories and binary, not just floats. Also, gini scores now take into account weighted samples if the user has provided it --- src/program/split.cpp | 248 +++++++++++++++++++++++++++++++++++------- 1 file changed, 210 insertions(+), 38 deletions(-) diff --git a/src/program/split.cpp b/src/program/split.cpp index 64ddd59a..83a7166d 100644 --- a/src/program/split.cpp +++ b/src/program/split.cpp @@ -1,18 +1,181 @@ #include "operator.h" +#include #include using Brush::Data::State; namespace Brush::Split{ -tuple get_best_variable_and_threshold(const Dataset& d, TreeNode& tn) +Candidate get_best_split(const Dataset& d, const vector& class_weights) { - /* loops thru variables in d and picks the best threshold - * and feature to split at. - */ + // Compare candidate splits from float, integer, and boolean features. + // get_best_thresholds (in split.h) selects among the lowest scores, + // breaking near-ties randomly. using FeatTypes = tuple; constexpr auto size = std::tuple_size::value; - auto [feature, threshold, best_score] = get_best_thresholds(d, std::make_index_sequence{}); - return std::make_tuple(feature, threshold); + return get_best_thresholds(d, class_weights, std::make_index_sequence{}); +} + +ArrayXb category_mask(const ArrayXi& x, const vector& categories) +{ + // Membership selects the first branch; other values select the second. + ArrayXb mask(x.size()); + const std::unordered_set selected(categories.begin(), categories.end()); + for (int i = 0; i < x.size(); ++i) + mask(i) = selected.find(x(i)) != selected.end(); + return mask; +} + +Candidate best_category_split(const ArrayXi& x, const ArrayXf& y, bool classification, + const vector& class_weights) +{ + // Integer features represent categories: search for a group of values + // (for example, {0, 2}) versus all remaining values. + Candidate best; + const auto categories = unique(x); + if (categories.size() < 2) + return best; + const auto classes = classification ? unique(y) : vector{}; + + // Aggregate each category once, so candidate groups can be scored without + // rescanning every row. Mass is the sum of sample weights (or row count); + // class masses are used for Gini, while sums are used for regression. + struct Stats { + double mass = 0.0, sum = 0.0, sum_squared = 0.0; + vector classes; + explicit Stats(size_t n_classes) : classes(n_classes, 0.0) {} + void add(const Stats& other) { + mass += other.mass; + sum += other.sum; + sum_squared += other.sum_squared; + for (size_t i = 0; i < classes.size(); ++i) + classes[i] += other.classes[i]; + } + }; + + vector stats(categories.size(), Stats(classes.size())); + std::unordered_map category_index; + + for (size_t i = 0; i < categories.size(); ++i) + category_index[categories[i]] = i; + + std::map class_index; + for (size_t i = 0; i < classes.size(); ++i) + class_index[classes[i]] = i; + + Stats total(classes.size()); + for (int i = 0; i < x.size(); ++i) { + // Classification labels are encoded as indices into class_weights. + // Regression and unweighted classification give each row weight 1. + const double weight = classification && !class_weights.empty() + ? class_weights.at(static_cast(y(i))) : 1.0; + auto& category = stats[category_index.at(x(i))]; + category.mass += weight; + category.sum += weight * y(i); + category.sum_squared += weight * double(y(i)) * y(i); + if (classification) + category.classes[class_index.at(y(i))] += weight; + } + for (const auto& category : stats) + total.add(category); + + // Consider a group and its complement; a lower post-split score is better. + double best_score = std::numeric_limits::infinity(); + auto consider = [&](const Stats& left, vector subset) { + const double right_mass = total.mass - left.mass; + // A branch with no effective weight cannot define an impurity. + if (left.mass <= 0.0 || right_mass <= 0.0) + return; + double score; + if (classification) { + // Weighted average of the two branches' Gini impurities: + // 1 - sum(left_class^2 / left_mass + right_class^2 / right_mass) / total_mass. + double explained = 0.0; + for (size_t i = 0; i < classes.size(); ++i) { + const double left_class = left.classes[i]; + const double right_class = total.classes[i] - left_class; + explained += left_class * left_class / left.mass + + right_class * right_class / right_mass; + } + score = 1.0 - explained / total.mass; + } else { + // Within each branch, sum(y^2) - sum(y)^2 / count is the + // squared error around its mean. Normalize by the total count. + const double right_sum = total.sum - left.sum; + const double left_error = left.sum_squared - left.sum * left.sum / left.mass; + const double right_error = total.sum_squared - left.sum_squared + - right_sum * right_sum / right_mass; + score = std::max(0.0, (left_error + right_error) / total.mass); + } + if (!std::isfinite(score)) + return; + constexpr double tolerance = 1e-12; + if (score > best_score + tolerance) + return; + + // A partition and its complement have the same score. Always store the + // side containing the smallest category; break equal-score ties by the + // sorted category list, independently of class-label ordering. + std::sort(subset.begin(), subset.end()); + if (!std::binary_search(subset.begin(), subset.end(), categories.front())) { + vector complement; + std::set_difference(categories.begin(), categories.end(), subset.begin(), subset.end(), + std::back_inserter(complement)); + subset = std::move(complement); + } + if (score < best_score - tolerance + || (std::abs(score - best_score) <= tolerance && subset < best.categories)) { + best_score = score; + best.score = static_cast(score); + // Prediction uses the full category group, not this single value. + best.threshold = static_cast(subset.front()); + best.categories = std::move(subset); + } + }; + + // Search all unordered partitions for small categorical features. The first + // category is always included to avoid testing the same split twice; the + // all-categories group is skipped because its other branch would be empty. + if (categories.size() <= 10) { + const size_t combinations = size_t{1} << (categories.size() - 1); + for (size_t bits = 0; bits + 1 < combinations; ++bits) { + vector subset{categories.front()}; + Stats left = stats.front(); + for (size_t i = 1; i < categories.size(); ++i) + if (bits & (size_t{1} << (i - 1))) { + subset.push_back(categories[i]); + left.add(stats[i]); + } + consider(left, std::move(subset)); + } + } else { + // Exhaustive search grows exponentially. For larger features, test + // single categories and prefixes ordered by target mean (regression) + // or by each class's weighted proportion (classification). These are + // candidate splits, so the best possible grouping is not guaranteed. + // Separate class orderings also avoid treating class codes as numbers. + for (size_t i = 0; i < categories.size(); ++i) + consider(stats[i], {categories[i]}); + const size_t orderings = classification ? classes.size() : 1; + for (size_t c = 0; c < orderings; ++c) { + vector> ordered; + for (size_t i = 0; i < categories.size(); ++i) { + const double value = stats[i].mass > 0.0 + ? (classification ? stats[i].classes[c] : stats[i].sum) / stats[i].mass + : 0.0; + ordered.emplace_back(value, i); + } + std::sort(ordered.begin(), ordered.end()); + vector subset; + Stats left(classes.size()); + for (size_t i = 0; i + 1 < ordered.size(); ++i) { + const auto category = ordered[i].second; + subset.push_back(categories[category]); + left.add(stats[category]); + consider(left, subset); + } + } + } + return best; } template<> vector get_thresholds(const ArrayXb& x){ return vector{1.0}; } @@ -33,20 +196,20 @@ template<> vector get_thresholds(const ArrayXiJet& x){ template<> vector get_thresholds(const ArrayXf& x){ vector thresholds; auto s = unique(x); - for (unsigned i =0; i= threshold, the smallest value puts every row on one side. + // Starting at 1 also handles an empty feature without unsigned underflow. + for (size_t i = 1; i < s.size(); ++i) { - // thresholds.push_back((s.at(i) + s.at(i+1))/2.0); - thresholds.push_back(s.at(i+1)); + thresholds.push_back(s.at(i)); } return thresholds; } template<> vector get_thresholds(const ArrayXfJet& x){ vector thresholds; auto s = unique(x); - for (unsigned i =0; i(const State& x, const float& threshold) { x ); } -float gain(const ArrayXf& lsplit, - const ArrayXf& rsplit, - bool classification, vector unique_classes) - { - float lscore, rscore, score; - if (classification) - { - lscore = gini_impurity_index(lsplit, unique_classes); - rscore = gini_impurity_index(rsplit, unique_classes); - /* cout << "lscore: " << lscore << "\n"; */ - /* cout << "rscore: " << rscore << "\n"; */ - score = (lscore*float(lsplit.size()) + - rscore*float(rsplit.size())) - /(float(lsplit.size()) + float(rsplit.size())); - } - else - { - lscore = variance(lsplit); - rscore = variance(rsplit); - /* cout << "lscore: " << lscore << "\n"; */ - /* cout << "rscore: " << rscore << "\n"; */ - score = (lscore * float(lsplit.size()) - + rscore * float(rsplit.size())) - / float(lsplit.size() + rsplit.size()); - } +float gain(const ArrayXf& lsplit, const ArrayXf& rsplit, bool classification, + vector unique_classes, const vector& class_weights) +{ + if (classification) { + // Accumulate weighted counts for every class in each branch. With no + // class weights, each row counts once, as in the original Gini score. + auto weighted_counts = [&](const ArrayXf& labels) { + vector counts(unique_classes.size(), 0.0); + double mass = 0.0; + for (float label : labels) { + const double weight = class_weights.empty() + ? 1.0 : class_weights.at(static_cast(label)); + const auto it = std::find(unique_classes.begin(), unique_classes.end(), label); + counts.at(std::distance(unique_classes.begin(), it)) += weight; + mass += weight; + } + return std::make_pair(counts, mass); + }; + + const auto [left, left_mass] = weighted_counts(lsplit); + const auto [right, right_mass] = weighted_counts(rsplit); - return score; + // Reject a branch containing no effective sample weight. + if (left_mass <= 0.0 || right_mass <= 0.0) + return MAX_FLT; + + // Weighted mean Gini of the two branches; lower scores are better. + double explained = 0.0; + for (size_t i = 0; i < unique_classes.size(); ++i) + explained += left[i] * left[i] / left_mass + right[i] * right[i] / right_mass; + + return static_cast(1.0 - explained / (left_mass + right_mass)); } + return (variance(lsplit) * float(lsplit.size()) + variance(rsplit) * float(rsplit.size())) + / float(lsplit.size() + rsplit.size()); +} + float gini_impurity_index(const ArrayXf& classes, const vector& unique_classes) { From 8de27e65ac1fa5a09ba36d9d291d60287b54202e Mon Sep 17 00:00:00 2001 From: Guilherme Seidyo Imai Aldeia Date: Fri, 20 Nov 2026 13:07:46 -0500 Subject: [PATCH 25/25] updated wrapper and bindings --- pybrush/deap_api/DeapEstimator.py | 61 +++++-------------------------- src/bindings/bind_engines.h | 2 + src/bindings/bind_individuals.h | 5 +++ src/bindings/bind_params.cpp | 3 +- src/bindings/bind_programs.h | 4 ++ 5 files changed, 22 insertions(+), 53 deletions(-) diff --git a/pybrush/deap_api/DeapEstimator.py b/pybrush/deap_api/DeapEstimator.py index 176defe1..b0321403 100644 --- a/pybrush/deap_api/DeapEstimator.py +++ b/pybrush/deap_api/DeapEstimator.py @@ -19,8 +19,6 @@ from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin, \ TransformerMixin -from pandas.api.types import is_float_dtype, is_bool_dtype, is_integer_dtype - from pybrush.EstimatorInterface import EstimatorInterface from pybrush.deap_api.nsga2 import nsga2 from pybrush import individual @@ -90,7 +88,8 @@ def update_current_gen(gen): self.parameters_.current_gen = gen toolbox.register("update_current_gen", update_current_gen) def assign_fit(ind, validation=False): - ind.program.fit(self.data_.get_training_data()) + if not ind.is_fitted: + ind.fit(self.data_.get_training_data(), self.parameters_.class_weights) self.eval_.assign_fit(ind, self.data_, self.parameters_, validation) return ind @@ -136,25 +135,7 @@ def fit(self, X, y): 1-d array of (boolean) target values. """ - self.feature_names_ = [] - self.feature_types_ = [] - if isinstance(X, pd.DataFrame): - self.feature_names_ = X.columns.to_list() - for values, dtype in zip(X.values.T, X.dtypes): - if is_bool_dtype(dtype): - self.feature_types_.append('ArrayB') - elif is_integer_dtype(dtype): - if np.all(np.logical_or(values == 0, values == 1)): - self.feature_types_.append('ArrayB') - else: - self.feature_types_.append('ArrayI') - elif is_float_dtype(dtype): - self.feature_types_.append('ArrayF') - else: - raise ValueError( - "Unsupported data type. Please try using an " - "encoding method to convert the data to a supported " - "format.") + self._prepare_feature_types(X) if self.mode == 'classification': self.classes_, y = np.unique(y, return_inverse=True) @@ -165,6 +146,8 @@ def fit(self, X, y): feature_types=self.feature_types_, validation_size=self.validation_size, shuffle_split=self.shuffle_split) + if not self.feature_types_ or any(not t for t in self.feature_types_): + self.feature_types_ = self.data_.get_feature_types() # These have a default behavior to return something meaningfull if # no values are set @@ -255,21 +238,8 @@ def predict(self, X): check_is_fitted(self) - if self.data_ is None: - self.data_ = self._make_data(X, - feature_names=self.feature_names_, - feature_types=self.feature_types_, - validation_size=self.validation_size, - shuffle_split=self.shuffle_split) - - if isinstance(X, pd.DataFrame): - X = X.values - - assert isinstance(X, np.ndarray) - - # Need to provide feature names because reference does not store order - data = Dataset(X=X, ref_dataset=self.data_, - feature_names=self.feature_names_) + data = self._make_data(X, feature_names=self.feature_names_, + feature_types=self.feature_types_) prediction = np.asarray(self.best_estimator_.program.predict(data)) if self.mode == 'classification': @@ -339,21 +309,8 @@ def predict_proba(self, X): check_is_fitted(self) - if isinstance(X, pd.DataFrame): - X = X.values - - if self.data_ is None: - self.data_ = self._make_data(X, - feature_names=self.feature_names_, - feature_types=self.feature_types_, - validation_size=self.validation_size, - shuffle_split=self.shuffle_split) - - assert isinstance(X, np.ndarray) - - # Need to provide feature names because reference does not store order - data = Dataset(X=X, ref_dataset=self.data_, - feature_names=self.feature_names_) + data = self._make_data(X, feature_names=self.feature_names_, + feature_types=self.feature_types_) prob = self.best_estimator_.program.predict_proba(data) diff --git a/src/bindings/bind_engines.h b/src/bindings/bind_engines.h index 544521a0..20701694 100644 --- a/src/bindings/bind_engines.h +++ b/src/bindings/bind_engines.h @@ -47,6 +47,7 @@ void bind_engine(py::module& m, string name) .def_property("search_space", &T::get_search_space, &T::set_search_space) .def_property_readonly("is_fitted", &T::get_is_fitted) .def_property_readonly("best_ind", &T::get_best_ind) + .def("set_best_ind", &T::set_best_ind) .def("fit", static_cast(&T::fit), py::call_guard(), @@ -64,6 +65,7 @@ void bind_engine(py::module& m, string name) .def("get_archive", &T::get_archive) .def("get_population", &T::get_population) .def("set_population", &T::set_population) + .def("invalidate_population_fit", &T::invalidate_population_fit) .def("get_archive_as_json", &T::get_archive_as_json) .def("get_population_as_json", &T::get_population_as_json) .def("set_population_from_json", &T::set_population_from_json) diff --git a/src/bindings/bind_individuals.h b/src/bindings/bind_individuals.h index 86373173..be7723a6 100644 --- a/src/bindings/bind_individuals.h +++ b/src/bindings/bind_individuals.h @@ -34,6 +34,7 @@ void bind_individual(py::module& m, string name) .def("init", &Class::init) .def_property("objectives", &Class::get_objectives, &Class::set_objectives) .def_property_readonly("program", &Class::get_program) + .def_property_readonly("is_fitted", &Class::get_is_fitted) .def_property_readonly("fitness", &Class::get_fitness) .def_property_readonly("id", &Class::get_id) .def("get_model", &Class::get_model, @@ -44,6 +45,10 @@ void bind_individual(py::module& m, string name) .def("fit", static_cast(&Class::fit), "fit from Dataset object") + .def("fit", + static_cast&)>(&Class::fit), + py::arg("data"), py::arg("class_weights"), + "fit from Dataset object with per-class weights") .def("fit", static_cast &X, const Ref &y)>(&Class::fit), "fit from X,y data") diff --git a/src/bindings/bind_params.cpp b/src/bindings/bind_params.cpp index 775fbcb5..a4659ada 100644 --- a/src/bindings/bind_params.cpp +++ b/src/bindings/bind_params.cpp @@ -42,6 +42,7 @@ void bind_params(py::module& m) .def_property("shuffle_split", &Brush::Parameters::get_shuffle_split, &Brush::Parameters::set_shuffle_split) .def_property("validation_size", &Brush::Parameters::get_validation_size, &Brush::Parameters::set_validation_size) .def_property("feature_names", &Brush::Parameters::get_feature_names, &Brush::Parameters::set_feature_names) + .def_property("feature_types", &Brush::Parameters::get_feature_types, &Brush::Parameters::set_feature_types) .def_property("batch_size", &Brush::Parameters::get_batch_size, &Brush::Parameters::set_batch_size) .def_property("max_depth", &Brush::Parameters::get_max_depth, &Brush::Parameters::set_max_depth) .def_property("max_size", &Brush::Parameters::get_max_size, &Brush::Parameters::set_max_size) @@ -66,4 +67,4 @@ void bind_params(py::module& m) }) ) ; -} \ No newline at end of file +} diff --git a/src/bindings/bind_programs.h b/src/bindings/bind_programs.h index 27f7af4c..c1c0b2e1 100644 --- a/src/bindings/bind_programs.h +++ b/src/bindings/bind_programs.h @@ -27,6 +27,10 @@ void bind_program(py::module& m, string name) .def("fit", static_cast(&T::fit), "fit from Dataset object") + .def("fit", + static_cast&)>(&T::fit), + py::arg("data"), py::arg("class_weights"), + "fit from Dataset object with per-class weights") .def("fit", static_cast &X, const Ref &y)>(&T::fit), "fit from X,y data")