diff --git a/pybrush/EstimatorInterface.py b/pybrush/EstimatorInterface.py index 2df0f82a8..39b823848 100644 --- a/pybrush/EstimatorInterface.py +++ b/pybrush/EstimatorInterface.py @@ -121,8 +121,20 @@ class EstimatorInterface(): (that is, trees using only SplitOn and SplitBest operators). batch_size : float, default 1.0 Percentage of training data to sample every generation. If `1.0`, then - all data is used. Very small values can improve execution time, but - also lead to underfit. + all data is used. Regression batches are stratified by four + equal-frequency target (`y`) quartiles: each batch receives as equal a + share as its size allows from every nonempty quartile and consumes every training row + without replacement before shuffling a new epoch. For classification, + every batch contains at least one example of each class. If the requested + batch would be smaller than the number of + classes, it is enlarged to that number. Remaining slots follow the + original training-set class prevalence. Every training row is used at + 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 + 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' The selection method to perform parent selection. When using lexicase, the selection is done as if it was a single-objective problem, based on diff --git a/src/bindings/bind_evaluator.h b/src/bindings/bind_evaluator.h index 754172204..eb2fa6de3 100644 --- a/src/bindings/bind_evaluator.h +++ b/src/bindings/bind_evaluator.h @@ -14,7 +14,13 @@ void bind_evaluator(py::module& m, string name) // TODO: will this part of c++ be exposed? py::class_ eval(m, name.data() ); eval.def(py::init<>()) - .def("assign_fit", &Class::assign_fit) + // Keep the original four-argument Python API. The optional dataset is + // used internally by batched Engine runs to score a fixed validation + // partition and is not required by the DEAP interface. + .def("assign_fit", &Class::assign_fit, + py::arg("individual"), py::arg("data"), py::arg("params"), + py::arg("validation") = false, + py::arg("validation_data") = nullptr) .def_property("scorer", &Class::get_scorer, &Class::set_scorer) ; -} \ No newline at end of file +} diff --git a/src/data/data.cpp b/src/data/data.cpp index 4d3bbf309..11463cc29 100644 --- a/src/data/data.cpp +++ b/src/data/data.cpp @@ -182,22 +182,191 @@ Dataset Dataset::operator()(const vector& idx) const } -// TODO: i need to improve how get batch works. Maybe a function to update batch indexes, and always using the same dataset? -// TODO: also, i need to make sure the get batch will sample only from training data and not test Dataset Dataset::get_batch() const { - // will always return a new dataset, even when use_batch is false (this case, returns itself) - if (!use_batch) return (*this); - auto n_samples = int(this->get_n_samples()); - // garantee that at least one sample is going to be returned, since - // use_batch is true only if batch_size is (0, 1), and ceil will round - // up - n_samples = int(ceil(n_samples*batch_size)); + const auto total_samples = static_cast(this->get_n_samples()); + const auto target_batch_size = static_cast(ceil(total_samples * batch_size)); + + // Start a new epoch only after every row from the preceding epoch has + // been returned. This prevents replacement before a complete pass through + // the training partition. + if (batch_cycle_idx.empty() || batch_cycle_batch_cursor >= batch_cycle_sizes.size()) + { + // resets everything + batch_cycle_idx.clear(); + batch_cycle_sizes.clear(); + batch_cycle_cursor = 0; + batch_cycle_batch_cursor = 0; + + // repopulate the indexes + if (classification) + { + // Shuffle each class queue. Every batch preserves the original + // class prevalence and reserves one slot per class. Once a class + // queue is exhausted, that class is sampled with replacement so + // later batches still train against it while larger class queues + // complete their no-replacement pass. + std::map> class_indices; + for (size_t i = 0; i < total_samples; ++i) + class_indices[y(i)].push_back(i); + + for (auto& [label, indices] : class_indices) + r.shuffle(indices.begin(), indices.end()); + + // creating the batches + vector positions(class_indices.size(), 0); // this gets incremented everytime a row is added to a batch + const auto class_count = class_indices.size(); + const auto current_batch_size = std::max(target_batch_size, class_count); + while (true) // this while(true) iterates once for each batch creation + { + // searches for classes with unseen samples + bool has_unseen_rows = false; + size_t class_position = 0; + for (const auto& [label, indices] : class_indices) { + has_unseen_rows |= positions[class_position] < indices.size(); + ++class_position; + } + if (!has_unseen_rows) // all rows were added to a batch -- this is the escape condition to the while (true) loop + break; + + vector counts(class_indices.size(), 0); // will count how many samples per class for the current batch + vector> remainders; // will store how many samples are left per class after the current batch + + // free space in the batch. Notice that one sample per class is already being considered here + const auto allocatable_slots = current_batch_size - class_count; + + class_position = 0; + for (const auto& [label, indices] : class_indices) + { + counts[class_position] = 1; // this ensures one sample per class + + // find rounded number of slots that will be used for the class + // to ensure they keep approximate prevalence w.r.t. original data + const float exact = static_cast(indices.size() * allocatable_slots) + / static_cast(total_samples); + const auto floor_allocation = static_cast(std::floor(exact)); + + counts[class_position] += floor_allocation; + remainders.emplace_back(exact - std::floor(exact), class_position); + ++class_position; + } + + std::stable_sort(remainders.begin(), remainders.end(), + [](const auto& left, const auto& right) { + return left.first > right.first; + }); + + size_t assigned = class_count; + for (const auto count : counts) + assigned += count - 1; + for (size_t i = 0; assigned < current_batch_size; ++i, ++assigned) + ++counts[remainders.at(i).second]; + + // filling the batch + vector batch_indices; + batch_indices.reserve(current_batch_size); + class_position = 0; + for (const auto& [label, indices] : class_indices) + { + const auto available = indices.size() - positions[class_position]; + const auto unique_count = std::min(counts[class_position], available); + for (size_t i = 0; i < unique_count; ++i) + batch_indices.push_back(indices[positions[class_position]++]); + + // Repeat only a class that was already exhausted before + // this batch began. If its final unseen row was consumed + // above, return a smaller final batch instead of repeating + // that row immediately. + if (available == 0) { + for (size_t i = 0; i < counts[class_position]; ++i) + batch_indices.push_back(indices.at(r.rnd_int(0, indices.size() - 1))); + } + ++class_position; + } + r.shuffle(batch_indices.begin(), batch_indices.end()); + batch_cycle_idx.insert(batch_cycle_idx.end(), batch_indices.begin(), batch_indices.end()); + batch_cycle_sizes.push_back(batch_indices.size()); + } + } + else + { + // Regression batches are stratified by target rank. The four + // equal-frequency y quartiles are shuffled independently, then + // apportioned evenly into each batch without replacement. + vector sorted_indices(total_samples); + std::iota(sorted_indices.begin(), sorted_indices.end(), 0); + std::stable_sort(sorted_indices.begin(), sorted_indices.end(), + [this](size_t left, size_t right) { return y(left) < y(right); }); + + vector> quartiles(4); + for (size_t rank = 0; rank < total_samples; ++rank) + quartiles.at((rank * quartiles.size()) / total_samples).push_back(sorted_indices.at(rank)); + + size_t nonempty_quartiles = 0; + for (auto& quartile : quartiles) { + if (!quartile.empty()) { + r.shuffle(quartile.begin(), quartile.end()); + ++nonempty_quartiles; + } + } + + vector positions(quartiles.size(), 0); + const auto current_batch_size = std::max(target_batch_size, nonempty_quartiles); + while (true) + { + bool has_unseen_rows = false; + for (size_t quartile = 0; quartile < quartiles.size(); ++quartile) + has_unseen_rows |= positions[quartile] < quartiles[quartile].size(); + if (!has_unseen_rows) + break; + + vector counts(quartiles.size(), 0); + vector> remainders; + const auto allocatable_slots = current_batch_size - nonempty_quartiles; + for (size_t quartile = 0; quartile < quartiles.size(); ++quartile) { + if (quartiles[quartile].empty()) + continue; + counts[quartile] = 1; + const float exact = static_cast(quartiles[quartile].size() * allocatable_slots) + / static_cast(total_samples); + counts[quartile] += static_cast(std::floor(exact)); + remainders.emplace_back(exact - std::floor(exact), quartile); + } + + std::stable_sort(remainders.begin(), remainders.end(), + [](const auto& left, const auto& right) { + return left.first > right.first; + }); + size_t assigned = 0; + for (const auto count : counts) + assigned += count; + for (size_t i = 0; assigned < current_batch_size; ++i, ++assigned) + ++counts[remainders.at(i).second]; + + vector batch_indices; + batch_indices.reserve(current_batch_size); + for (size_t quartile = 0; quartile < quartiles.size(); ++quartile) { + const auto available = quartiles[quartile].size() - positions[quartile]; + const auto unique_count = std::min(counts[quartile], available); + for (size_t i = 0; i < unique_count; ++i) + batch_indices.push_back(quartiles[quartile][positions[quartile]++]); + } + r.shuffle(batch_indices.begin(), batch_indices.end()); + batch_cycle_idx.insert(batch_cycle_idx.end(), batch_indices.begin(), batch_indices.end()); + batch_cycle_sizes.push_back(batch_indices.size()); + } + } + } - return (*this)(r.shuffled_index(n_samples)); + // get the indices and move the two cursors + const auto count = batch_cycle_sizes.at(batch_cycle_batch_cursor++); + vector indices(batch_cycle_idx.begin() + batch_cycle_cursor, + batch_cycle_idx.begin() + batch_cycle_cursor + count); + batch_cycle_cursor += count; + return (*this)(indices); } std::array Dataset::split(const ArrayXb& mask) const @@ -381,6 +550,10 @@ float Dataset::get_batch_size() { return batch_size; } void Dataset::set_batch_size(float new_size) { batch_size = new_size; use_batch = batch_size > 0.0 && batch_size < 1.0; + batch_cycle_idx.clear(); + batch_cycle_sizes.clear(); + batch_cycle_cursor = 0; + batch_cycle_batch_cursor = 0; } /// turns input data into a feature map diff --git a/src/data/data.h b/src/data/data.h index f9b2826f9..c891d560e 100644 --- a/src/data/data.h +++ b/src/data/data.h @@ -56,6 +56,14 @@ class Dataset private: vector training_data_idx; vector validation_data_idx; + // A batch epoch records row indices and batch boundaries. Classification + // epochs may repeat an exhausted minority class to keep it represented. + // These are mutable because get_batch advances the sampler while the + // dataset values themselves remain immutable. + mutable vector batch_cycle_idx; + mutable vector batch_cycle_sizes; + mutable size_t batch_cycle_cursor = 0; + mutable size_t batch_cycle_batch_cursor = 0; /// @brief stores the original feature name order before map sorting vector feature_name_order_; @@ -229,7 +237,8 @@ class Dataset ); }; inline int get_n_features() const { return this->features.size(); }; - /// select random subset of data for training weights. + /// Select the next batch without replacement. Classification batches + /// preserve the prevalence of the remaining class-specific queues. Dataset get_batch() const; float get_batch_size(); diff --git a/src/engine.cpp b/src/engine.cpp index ea023b49d..a955232fe 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -530,13 +530,19 @@ bool Engine::update_best() template void Engine::run(Dataset &data) { + // 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(); + training.set_batch_size(params.batch_size); + Dataset validation = data.get_validation_data(); + // avoid re-initializing stuff so we can perform partial fits if (!this->is_fitted){ //TODO: i need to make sure i initialize everything (pybind needs to have constructors // without arguments to work, and i need to handle correcting these values before running) // initializing classes that need data references - this->ss.init(data, params.functions, params.weights_init); + this->ss.init(training, params.functions, params.weights_init); // TODO: make init to take necessary arguments and perform all initializations inside that function this->init(); @@ -562,14 +568,17 @@ void Engine::run(Dataset &data) // This is data dependent so we initialize it everytime, regardless of partial fit // TODO: make variator have a default constructor and make it an attribute of engine - Variation variator = Variation(this->params, this->ss, data); + Variation variator = Variation(this->params, this->ss, training); if (!params.logfile.empty()) open_logs(); evaluator.set_scorer(params.scorer); - Dataset &batch = data; + // Batch samples are drawn from training data only. Keep the hold-out set + // separate so it stays fixed for validation throughout the run. + Dataset batch = training; + Dataset* fixed_validation = data.use_validation ? &validation : nullptr; int threads; if (params.n_jobs == -1) @@ -623,10 +632,13 @@ 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. + batch = training.get_batch(); for (int island = 0; island < this->params.num_islands; ++island) { - // Evaluate the individuals at least once. Set validation - // loss before calling update_best. - evaluator.update_fitness(this->pop, island, data, params, true, true); + evaluator.update_fitness(this->pop, island, batch, params, + true, true, true, fixed_validation); } }); auto find_init_best = subflow.emplace([&]() { @@ -645,10 +657,7 @@ void Engine::run(Dataset &data) [&](tf::Subflow& subflow) { // loop body (evolutionary main loop) auto prepare_gen = subflow.emplace([&]() { params.set_current_gen(generation); - // the variator keeps its own copy of the parameters. It uses the - // generation to set individual ids and to tag simplification logs. - variator.parameters.set_current_gen(generation); - batch = data.get_batch(); // will return the original dataset if it is set to dont use batch + batch = training.get_batch(); // returns all training data when batching is disabled }).name("prepare generation");// set generation in params, get batch // Selection consumes the process-wide random stream. Keep island @@ -657,19 +666,24 @@ void Engine::run(Dataset &data) // nondeterministic. Initial fitness evaluation is ordered too, // so the complete seeded evolutionary path is scheduler-neutral. auto run_generation = subflow.emplace([&]() { + // Lexicase samples case indices from the score dataset. Its + // sample weights must therefore have the same length as the + // current batch, not the full training partition. + Parameters selection_params = params; + if (params.classification) + selection_params.set_sample_weights(batch.y); + for (int island = 0; island < this->params.num_islands; ++island) { - evaluator.update_fitness(this->pop, island, data, params, false, false); // fit the weights with all training data - - // TODO: have some way to set which fitness to use (for example in params, or it can infer based on split size idk) - // TODO: if using batch, fitness should be called before selection to set the batch - if (data.use_batch) // assign the batch error as fitness (but fit was done with training data) - evaluator.update_fitness(this->pop, island, batch, params, false, false); - - vector parents = selector.select(this->pop, island, params); - for (int i=0; i< parents.size(); i++){ - island_parents.at(island).at(i) = parents.at(i); - } + // Refit each surviving program on this generation's batch. + // Parent selection uses batch fitness while validation always + // uses the original, fixed hold-out partition. + evaluator.update_fitness(this->pop, island, batch, params, + true, false, true, fixed_validation); + + vector parents = selector.select( + this->pop, island, selection_params); + island_parents.at(island) = std::move(parents); this->pop.add_offspring_indexes(island); } @@ -683,13 +697,14 @@ void Engine::run(Dataset &data) // TODO: do I have to pass data as an argument here? or can I use the instance reference. // OBS: this function already calls fit internally! variator.vary_and_update(this->pop, island, island_parents.at(island), - data, evaluator, + batch, evaluator, // conditions to apply simplification. // It starts only on the second half of generations. // Also, we garantee that the final generation // will be simplified. - (generation>=params.max_gens/2) || (stall_count == params.max_stall) || (generation==params.max_gens-1) + (generation>=params.max_gens/2) || (stall_count == params.max_stall) || (generation==params.max_gens-1), + fixed_validation ); } @@ -710,9 +725,11 @@ void Engine::run(Dataset &data) auto finish_gen = subflow.emplace([&]() { // Set validation loss before calling update best for (int island = 0; island < this->params.num_islands; ++island) { - // we can set fit to true, because already fitted individuals will be skipped, - // and we ensure we fit everyone - evaluator.update_fitness(this->pop, island, data, params, true, true); + // Keep batch fitness for evolution but replace the fitness + // values used by the archive and best-model selection with + // scores from the fixed, complete validation partition. + evaluator.update_fitness(this->pop, island, batch, params, + false, true, false, fixed_validation); } archive.update(pop, params); @@ -752,9 +769,11 @@ void Engine::run(Dataset &data) [&]() { return 0; }, // jump back to the next iteration [&](tf::Subflow& subflow) { - // set validation loss, refit (will work only on individuals not fitted) + // Keep the final batch-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, data, params, true, true); + evaluator.update_fitness(this->pop, island, batch, params, + false, true, false, fixed_validation); } archive.update(pop, params); diff --git a/src/engine.h b/src/engine.h index ec3a34d91..a6e4f74b6 100644 --- a/src/engine.h +++ b/src/engine.h @@ -84,11 +84,16 @@ class Engine{ }; Engine &fit(const Ref& X, const Ref& y) { + // The dataset constructor may shuffle its validation split. Seed before + // constructing it so the native X/y entry point is reproducible too. + r.set_seed(params.get_random_state()); + // Using constructor 2 to create the dataset Dataset d(X,y,params.feature_names,{},params.feature_types, params.classification,params.validation_size, params.batch_size, params.shuffle_split); - return fit(d); + + return fit(d); }; auto predict(const Dataset& data) { return this->best_ind.predict(data); }; diff --git a/src/eval/evaluation.cpp b/src/eval/evaluation.cpp index 766731638..56d8e55d5 100644 --- a/src/eval/evaluation.cpp +++ b/src/eval/evaluation.cpp @@ -11,7 +11,9 @@ void Evaluation::update_fitness(Population& pop, const Dataset& data, const Parameters& params, bool fit, - bool validation + bool validation, + bool force_fit, + Dataset* validation_data ) { auto indices = pop.get_island_indexes(island); @@ -40,12 +42,12 @@ void Evaluation::update_fitness(Population& pop, else { // assign weights to individual - if (fit && ind.get_is_fitted() == false) + if (fit && (force_fit || ind.get_is_fitted() == false)) { ind.program.fit(data.get_training_data(), params.class_weights); } - assign_fit(ind, data, params, validation); + assign_fit(ind, data, params, validation, validation_data); } } } @@ -53,7 +55,8 @@ void Evaluation::update_fitness(Population& pop, // assign loss to program template void Evaluation::assign_fit(Individual& ind, const Dataset& data, - const Parameters& params, bool val) + const Parameters& params, bool val, + Dataset* validation_data) { ++n_evaluations; @@ -65,7 +68,11 @@ void Evaluation::assign_fit(Individual& ind, const Dataset& data, ind.error = errors; float f_v = f; - if (data.use_validation) { + if (validation_data != nullptr) { + VectorXf val_errors; + f_v = S.score(ind, *validation_data, val_errors, params); + } + else if (data.use_validation) { Dataset validation = data.get_validation_data(); // when calculating validation score, we should not let diff --git a/src/eval/evaluation.h b/src/eval/evaluation.h index 51a785bd3..604812129 100644 --- a/src/eval/evaluation.h +++ b/src/eval/evaluation.h @@ -74,7 +74,9 @@ class Evaluation { const Dataset& data, const Parameters& params, bool fit=true, - bool validation=true // if there is no validation, then loss_v==loss + bool validation=true, // if there is no validation, then loss_v==loss + bool force_fit=false, + Dataset* validation_data=nullptr ); /** @@ -85,7 +87,8 @@ class Evaluation { * @param val Flag indicating whether it is validation fitness. */ void assign_fit(Individual& ind, const Dataset& data, - const Parameters& params, bool val=false); + const Parameters& params, bool val=false, + Dataset* validation_data=nullptr); /// number of calls to assign_fit (each one scores an individual on the /// training partition and, if there is one, on the validation partition). diff --git a/src/vary/variation.h b/src/vary/variation.h index 7b5296533..fb8722bdd 100644 --- a/src/vary/variation.h +++ b/src/vary/variation.h @@ -221,7 +221,8 @@ class Variation { * @param parents The indices of the parent individuals. */ void vary_and_update(Population& pop, int island, const vector& parents, - const Dataset& data, Evaluation& evaluator, bool do_simplification) { + const Dataset& data, Evaluation& evaluator, bool do_simplification, + Dataset* validation_data=nullptr) { // TODO: move implementation to cpp file and keep only declarations here // TODO: rewrite this entire function to avoid repetition (this is a frankenstein) @@ -382,7 +383,7 @@ class Variation { simplification_records.push_back(std::move(rec)); } - evaluator.assign_fit(ind, data, parameters, false); + evaluator.assign_fit(ind, data, parameters, false, validation_data); // vector deltas(ind.get_objectives().size(), 0.0f); vector deltas; diff --git a/tests/cpp/test_data.cpp b/tests/cpp/test_data.cpp index 1589efcd6..be3092004 100644 --- a/tests/cpp/test_data.cpp +++ b/tests/cpp/test_data.cpp @@ -1,4 +1,6 @@ #include "testsHeader.h" +#include +#include // #include "../../src/bandit/bandit.cpp" TEST(Data, ErrorHandling) @@ -203,3 +205,107 @@ TEST(Data, ShuffleTrueFalse) ASSERT_EQ(dt6.get_training_data().get_n_samples(), total); ASSERT_EQ(dt6.get_validation_data().get_n_samples(), total); } + +TEST(Data, ClassificationBatchesCycleTrainingRowsAndPreserveTypes) +{ + // The source has a 3:1 class ratio. With a 25% validation split, training + // has nine class-0 and three class-1 rows. Five 25%-sized batches should + // preserve that prevalence, retain the minority class after its unique + // rows are exhausted, visit every training row, and never touch validation + // rows. + + Util::r.set_seed(42); + MatrixXf X(16, 3); + ArrayXf y(16); + for (int i = 0; i < 16; ++i) { + X(i, 0) = static_cast(i); // unique row identifier (used to extract row ids later in the test) + X(i, 1) = static_cast(i % 2); // boolean feature + X(i, 2) = static_cast(i % 4); // categorical feature + y(i) = i < 12 ? 0.0f : 1.0f; + } + + Dataset data(X, y, {"id", "flag", "category"}, {}, + {"ArrayF", "ArrayB", "ArrayI"}, true, 0.25f, 1.0f, true); + Dataset training = data.get_training_data(); + Dataset validation = data.get_validation_data(); // we set 0.25f validation data + training.set_batch_size(0.25f); // percentage of the training data to be used per batch (will be 0.25 of the 12 samples from the train split) + + std::set training_ids; + const auto& training_id_values = std::get(training.features.at("id")); + for (int i = 0; i < training_id_values.size(); ++i) + training_ids.insert(static_cast(training_id_values(i))); + + std::set validation_ids; + const auto& validation_id_values = std::get(validation.features.at("id")); + for (int i = 0; i < validation_id_values.size(); ++i) + validation_ids.insert(static_cast(validation_id_values(i))); + + std::set batch_ids; + + // Each batch targets 25% of the 12 training rows, so 3 rows. + // To include the minority class, each full batch contains 2 + // class-0 rows and 1 class-1 row. + + // There are 9 class-0 rows, so covering them takes five batches; + // four with 2 class-0 rows and a final batch with 1. The minority class + // is repeated in the last two batches, producing sizes 3, 3, 3, 3, 2. + const vector expected_class_zero_counts{2, 2, 2, 2, 1}; + const vector expected_batch_sizes{3, 3, 3, 3, 2}; + + for (int batch_number = 0; batch_number < 5; ++batch_number) { + Dataset batch = training.get_batch(); + + EXPECT_EQ(batch.feature_names, (vector{"id", "flag", "category"})); + ASSERT_EQ(batch.feature_types.size(), 3U); + EXPECT_EQ(static_cast(batch.feature_types.at(0)), static_cast(DataType::ArrayF)); + EXPECT_EQ(static_cast(batch.feature_types.at(1)), static_cast(DataType::ArrayB)); + EXPECT_EQ(static_cast(batch.feature_types.at(2)), static_cast(DataType::ArrayI)); + EXPECT_EQ(batch.get_n_samples(), expected_batch_sizes.at(batch_number)); + + int class_zero_count = 0; + for (int i = 0; i < batch.y.size(); ++i) + class_zero_count += batch.y(i) == 0.0f; + + EXPECT_EQ(class_zero_count, expected_class_zero_counts.at(batch_number)); + + EXPECT_TRUE(std::any_of(batch.y.data(), batch.y.data() + batch.y.size(), + [](float label) { return label == 1.0f; })); + + const auto& batch_id_values = std::get(batch.features.at("id")); + for (int i = 0; i < batch_id_values.size(); ++i) + batch_ids.insert(static_cast(batch_id_values(i))); + } + + EXPECT_EQ(batch_ids, training_ids); // those are sets (unordered!), not lists + EXPECT_EQ(std::count_if(training.y.data(), training.y.data() + training.y.size(), + [](float label) { return label == 0.0f; }), 9); + + for (int id : batch_ids) + EXPECT_EQ(validation_ids.count(id), 0U); +} + +TEST(Data, RegressionBatchesContainEveryTargetQuartile) +{ + Util::r.set_seed(42); + MatrixXf X(16, 1); + ArrayXf y(16); + for (int i = 0; i < 16; ++i) { + X(i, 0) = static_cast(i); + y(i) = static_cast(i); + } + + Dataset data(X, y, {"id"}, {}, {"ArrayF"}, false, 0.0f, 0.25f, false); + std::set seen_targets; + for (int batch_number = 0; batch_number < 4; ++batch_number) { + Dataset batch = data.get_batch(); + ASSERT_EQ(batch.get_n_samples(), 4); + vector quartile_counts(4, 0); + for (int i = 0; i < batch.y.size(); ++i) { + const int target = static_cast(batch.y(i)); + ++quartile_counts.at(target / 4); + seen_targets.insert(target); + } + EXPECT_EQ(quartile_counts, (vector{1, 1, 1, 1})); + } + EXPECT_EQ(seen_targets.size(), 16U); +} diff --git a/tests/python/test_sklearn_interface.py b/tests/python/test_sklearn_interface.py index faa18b569..de4b533ed 100644 --- a/tests/python/test_sklearn_interface.py +++ b/tests/python/test_sklearn_interface.py @@ -8,9 +8,125 @@ from sklearn.datasets import make_classification, make_regression from sklearn.model_selection import GridSearchCV from pybrush import BrushClassifier, BrushRegressor +from pybrush import Dataset +from pybrush._brush import set_random_state as set_brush_random_state from sklearn.metrics import accuracy_score +def test_classification_batches_preserve_prevalence_and_cycle_training_rows(): + """Public Dataset batches retain each class while covering an epoch.""" + + # equivalent to cpp test -- just in python now + set_brush_random_state(42) + + identifiers = np.arange(16, dtype=np.float32) + + X = np.column_stack((identifiers, identifiers % 2, identifiers % 4)).astype(np.float32) + y = np.where(identifiers < 12, 0.0, 1.0).astype(np.float32) + + data = Dataset( + X=X, + y=y, + feature_names=["id", "flag", "category"], + feature_types=["ArrayF", "ArrayB", "ArrayI"], + c=True, + validation_size=0.25, + shuffle_split=True, + ) + + training = data.get_training_data() + training.set_batch_size(0.25) + + # each batch will be a new instance of a brush dataset + batches = [training.get_batch() for _ in range(5)] + + assert all(batch.get_feature_names() == ["id", "flag", "category"] for batch in batches) + assert all(batch.get_feature_types() == ["ArrayF", "ArrayB", "ArrayI"] for batch in batches) + + # Every batch reserves one minority-class example. The final two may be + # repeats because the training partition contains only three such rows. + # (obs: see explanation for those numbers in test_data.cpp) + assert [np.count_nonzero(batch.y == 0.0) for batch in batches] == [2, 2, 2, 2, 1] + assert [batch.get_n_samples() for batch in batches] == [3, 3, 3, 3, 2] + + assert all(np.any(batch.y == 1.0) for batch in batches) + + # The binding exposes labels on sliced datasets. One full epoch must yield + # All nine majority rows are visited in the five batches. The minority + # count is larger because its examples are deliberately repeated. + + epoch_labels = np.concatenate([batch.y for batch in batches]).astype(int) + training_labels = training.y.astype(int) + + assert np.bincount(epoch_labels)[0] == np.bincount(training_labels)[0] + + +def test_classification_batch_apportions_all_remaining_slots(): + """Large batches distribute floor and remainder slots without overflow.""" + set_brush_random_state(42) + y = np.array([0.0] * 20 + [1.0] * 20, dtype=np.float32) + data = Dataset(X=y.reshape(-1, 1), y=y, c=True, batch_size=0.25) + + batch = data.get_batch() + + assert batch.get_n_samples() == 10 + + # we have 40 samples and 0.25 batch size --> 10 samples each batch. + # the batch will have 50/50 (because we set the data as a balanced problem) + assert np.bincount(batch.y.astype(int), minlength=2).tolist() == [5, 5] + + +def test_classification_batch_expands_when_smaller_than_class_count(): + set_brush_random_state(42) + + # For classification, if the requested batch has fewer rows than there are + # classes, Brush enlarges it to include one row per class. + # For example, a requested 2-row batch with 4 classes becomes 4 rows. + + y = np.repeat(np.arange(4, dtype=np.float32), 2) # 4 classes + data = Dataset(X=y.reshape(-1, 1), y=y, c=True, batch_size=0.05) + + batch = data.get_batch() + + assert batch.get_n_samples() == 4 + assert np.bincount(batch.y.astype(int), minlength=4).tolist() == [1, 1, 1, 1] + + +def test_batched_classifier_completes_multiple_generations(): + """Batch-sized lexicase weights remain aligned with batch case indices.""" + X = np.arange(80, dtype=np.float32).reshape(40, 2) + y = np.array([0] * 20 + [1] * 20) + estimator = BrushClassifier( + pop_size=10, + max_gens=100, + max_stall=0, + max_time=-1, + max_depth=3, + batch_size=0.25, + validation_size=0.2, + random_state=7, + n_jobs=1, + ) + + estimator.fit(X, y) + + assert estimator.engine_.is_fitted + + +def test_regression_batches_stratify_target_quartiles(): + set_brush_random_state(42) + y = np.arange(16, dtype=np.float32) + X = y.reshape(-1, 1) + data = Dataset(X=X, y=y, feature_names=["id"], batch_size=0.25) + + batches = [data.get_batch() for _ in range(4)] + for batch in batches: + assert batch.get_n_samples() == 4 + assert np.bincount((batch.y // 4).astype(int), minlength=4).tolist() == [1, 1, 1, 1] + + assert np.array_equal(np.sort(np.concatenate([batch.y for batch in batches])), y) + + def test_brush_regressor_grid_search(): # Generate synthetic regression data X, y = make_regression(n_samples=50, n_features=3, noise=0.1, random_state=42)