StochTree 0.4.6.9000
Loading...
Searching...
No Matches
tree_sampler.h
1
2#ifndef STOCHTREE_TREE_SAMPLER_H_
3#define STOCHTREE_TREE_SAMPLER_H_
4
5#include <stochtree/container.h>
6#include <stochtree/cutpoint_candidates.h>
7#include <stochtree/data.h>
8#include <stochtree/discrete_sampler.h>
9#include <stochtree/distributions.h>
10#include <stochtree/ensemble.h>
11#include <stochtree/leaf_model.h>
12#include <stochtree/openmp_utils.h>
13#include <stochtree/partition_tracker.h>
14#include <stochtree/prior.h>
15
16#include <cmath>
17#include <numeric>
18#include <random>
19#include <vector>
20
21namespace StochTree {
22
36
48static inline void VarSplitRange(ForestTracker& tracker, ForestDataset& dataset, int tree_num, int leaf_split, int feature_split, double& var_min, double& var_max) {
49 var_min = std::numeric_limits<double>::max();
50 var_max = std::numeric_limits<double>::lowest();
51 double feature_value;
52
53 std::vector<data_size_t>::iterator node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, leaf_split);
54 std::vector<data_size_t>::iterator node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, leaf_split);
55
56 for (auto i = node_begin_iter; i != node_end_iter; i++) {
57 auto idx = *i;
58 feature_value = dataset.CovariateValue(idx, feature_split);
59 if (feature_value < var_min) {
60 var_min = feature_value;
61 }
62 if (feature_value > var_max) {
63 var_max = feature_value;
64 }
65 }
66}
67
79static inline bool NodesNonConstantAfterSplit(ForestDataset& dataset, ForestTracker& tracker, TreeSplit& split, int tree_num, int leaf_split, int feature_split) {
80 int p = dataset.GetCovariates().cols();
81 data_size_t idx;
82 double feature_value;
83 double split_feature_value;
84 double var_max_left;
85 double var_min_left;
86 double var_max_right;
87 double var_min_right;
88
89 for (int j = 0; j < p; j++) {
90 auto node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, leaf_split);
91 auto node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, leaf_split);
92 var_max_left = std::numeric_limits<double>::lowest();
93 var_min_left = std::numeric_limits<double>::max();
94 var_max_right = std::numeric_limits<double>::lowest();
95 var_min_right = std::numeric_limits<double>::max();
96
97 for (auto i = node_begin_iter; i != node_end_iter; i++) {
98 auto idx = *i;
99 split_feature_value = dataset.CovariateValue(idx, feature_split);
100 feature_value = dataset.CovariateValue(idx, j);
101 if (split.SplitTrue(split_feature_value)) {
102 if (var_max_left < feature_value) {
103 var_max_left = feature_value;
104 }
105 if (var_min_left > feature_value) {
106 var_min_left = feature_value;
107 }
108 } else {
109 if (var_max_right < feature_value) {
110 var_max_right = feature_value;
111 }
112 if (var_min_right > feature_value) {
113 var_min_right = feature_value;
114 }
115 }
116 }
117 if ((var_max_left > var_min_left) && (var_max_right > var_min_right)) {
118 return true;
119 }
120 }
121 return false;
122}
123
124static inline bool NodeNonConstant(ForestDataset& dataset, ForestTracker& tracker, int tree_num, int node_id) {
125 int p = dataset.GetCovariates().cols();
126 data_size_t idx;
127 double feature_value;
128 double var_max;
129 double var_min;
130
131 for (int j = 0; j < p; j++) {
132 auto node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, node_id);
133 auto node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, node_id);
134 var_max = std::numeric_limits<double>::lowest();
135 var_min = std::numeric_limits<double>::max();
136
137 for (auto i = node_begin_iter; i != node_end_iter; i++) {
138 auto idx = *i;
139 feature_value = dataset.CovariateValue(idx, j);
140 if (var_max < feature_value) {
141 var_max = feature_value;
142 }
143 if (var_min > feature_value) {
144 var_min = feature_value;
145 }
146 }
147 if (var_max > var_min) {
148 return true;
149 }
150 }
151 return false;
152}
153
154static inline void AddSplitToModel(ForestTracker& tracker, ForestDataset& dataset, TreePrior& tree_prior, TreeSplit& split, std::mt19937& gen, Tree* tree,
155 int tree_num, int leaf_node, int feature_split, bool keep_sorted = false, int num_threads = -1) {
156 // Use zeros as a "temporary" leaf values since we draw leaf parameters after tree sampling is complete
157 if (tree->OutputDimension() > 1) {
158 std::vector<double> temp_leaf_values(tree->OutputDimension(), 0.);
159 tree->ExpandNode(leaf_node, feature_split, split, temp_leaf_values, temp_leaf_values);
160 } else {
161 double temp_leaf_value = 0.;
162 tree->ExpandNode(leaf_node, feature_split, split, temp_leaf_value, temp_leaf_value);
163 }
164 int left_node = tree->LeftChild(leaf_node);
165 int right_node = tree->RightChild(leaf_node);
166
167 // Update the ForestTracker
168 tracker.AddSplit(dataset.GetCovariates(), split, feature_split, tree_num, leaf_node, left_node, right_node, keep_sorted, num_threads);
169}
170
171static inline void RemoveSplitFromModel(ForestTracker& tracker, ForestDataset& dataset, TreePrior& tree_prior, std::mt19937& gen, Tree* tree,
172 int tree_num, int leaf_node, int left_node, int right_node, bool keep_sorted = false) {
173 // Use zeros as a "temporary" leaf values since we draw leaf parameters after tree sampling is complete
174 if (tree->OutputDimension() > 1) {
175 std::vector<double> temp_leaf_values(tree->OutputDimension(), 0.);
176 tree->CollapseToLeaf(leaf_node, temp_leaf_values);
177 } else {
178 double temp_leaf_value = 0.;
179 tree->CollapseToLeaf(leaf_node, temp_leaf_value);
180 }
181
182 // Update the ForestTracker
183 tracker.RemoveSplit(dataset.GetCovariates(), tree, tree_num, leaf_node, left_node, right_node, keep_sorted);
184}
185
186static inline double ComputeMeanOutcome(ColumnVector& residual) {
187 int n = residual.NumRows();
188 double sum_y = 0.;
189 double y;
190 for (data_size_t i = 0; i < n; i++) {
191 y = residual.GetElement(i);
192 sum_y += y;
193 }
194 return sum_y / static_cast<double>(n);
195}
196
197static inline double ComputeVarianceOutcome(ColumnVector& residual) {
198 int n = residual.NumRows();
199 double sum_y = 0.;
200 double sum_y_sq = 0.;
201 double y;
202 for (data_size_t i = 0; i < n; i++) {
203 y = residual.GetElement(i);
204 sum_y += y;
205 sum_y_sq += y * y;
206 }
207 return sum_y_sq / static_cast<double>(n) - (sum_y * sum_y) / (static_cast<double>(n) * static_cast<double>(n));
208}
209
210static inline void UpdateModelVarianceForest(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual,
211 TreeEnsemble* forest, bool requires_basis, std::function<double(double, double)> op) {
212 data_size_t n = dataset.GetCovariates().rows();
213 double tree_pred = 0.;
214 double pred_value = 0.;
215 double new_resid = 0.;
216 int32_t leaf_pred;
217 for (data_size_t i = 0; i < n; i++) {
218 for (int j = 0; j < forest->NumTrees(); j++) {
219 Tree* tree = forest->GetTree(j);
220 leaf_pred = tracker.GetNodeId(i, j);
221 if (requires_basis) {
222 tree_pred += tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
223 } else {
224 tree_pred += tree->PredictFromNode(leaf_pred);
225 }
226 tracker.SetTreeSamplePrediction(i, j, tree_pred);
227 pred_value += tree_pred;
228 }
229
230 // Run op (either plus or minus) on the residual and the new prediction
231 new_resid = op(residual.GetElement(i), pred_value);
232 residual.SetElement(i, new_resid);
233 }
234 tracker.SyncPredictions();
235}
236
237static inline void UpdateResidualNoTrackerUpdate(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, TreeEnsemble* forest,
238 bool requires_basis, std::function<double(double, double)> op) {
239 data_size_t n = dataset.GetCovariates().rows();
240 double tree_pred = 0.;
241 double pred_value = 0.;
242 double new_resid = 0.;
243 int32_t leaf_pred;
244 for (data_size_t i = 0; i < n; i++) {
245 for (int j = 0; j < forest->NumTrees(); j++) {
246 Tree* tree = forest->GetTree(j);
247 leaf_pred = tracker.GetNodeId(i, j);
248 if (requires_basis) {
249 tree_pred += tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
250 } else {
251 tree_pred += tree->PredictFromNode(leaf_pred);
252 }
253 pred_value += tree_pred;
254 }
255
256 // Run op (either plus or minus) on the residual and the new prediction
257 new_resid = op(residual.GetElement(i), pred_value);
258 residual.SetElement(i, new_resid);
259 }
260}
261
262static inline void UpdateResidualEntireForest(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, TreeEnsemble* forest,
263 bool requires_basis, std::function<double(double, double)> op) {
264 data_size_t n = dataset.GetCovariates().rows();
265 double tree_pred = 0.;
266 double pred_value = 0.;
267 double new_resid = 0.;
268 int32_t leaf_pred;
269 for (data_size_t i = 0; i < n; i++) {
270 for (int j = 0; j < forest->NumTrees(); j++) {
271 Tree* tree = forest->GetTree(j);
272 leaf_pred = tracker.GetNodeId(i, j);
273 if (requires_basis) {
274 tree_pred += tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
275 } else {
276 tree_pred += tree->PredictFromNode(leaf_pred);
277 }
278 tracker.SetTreeSamplePrediction(i, j, tree_pred);
279 pred_value += tree_pred;
280 }
281
282 // Run op (either plus or minus) on the residual and the new prediction
283 new_resid = op(residual.GetElement(i), pred_value);
284 residual.SetElement(i, new_resid);
285 }
286 tracker.SyncPredictions();
287}
288
289static inline void UpdateResidualNewOutcome(ForestTracker& tracker, ColumnVector& residual) {
290 data_size_t n = residual.NumRows();
291 double pred_value;
292 double prev_outcome;
293 double new_resid;
294 for (data_size_t i = 0; i < n; i++) {
295 prev_outcome = residual.GetElement(i);
296 pred_value = tracker.GetSamplePrediction(i);
297 // Run op (either plus or minus) on the residual and the new prediction
298 new_resid = prev_outcome - pred_value;
299 residual.SetElement(i, new_resid);
300 }
301}
302
303static inline void UpdateMeanModelTree(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, Tree* tree, int tree_num,
304 bool requires_basis, std::function<double(double, double)> op, bool tree_new) {
305 data_size_t n = dataset.GetCovariates().rows();
306 double pred_value;
307 int32_t leaf_pred;
308 double new_resid;
309 double pred_delta;
310 for (data_size_t i = 0; i < n; i++) {
311 if (tree_new) {
312 // If the tree has been newly sampled or adjusted, we must rerun the prediction
313 // method and update the SamplePredMapper stored in tracker
314 leaf_pred = tracker.GetNodeId(i, tree_num);
315 if (requires_basis) {
316 pred_value = tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
317 } else {
318 pred_value = tree->PredictFromNode(leaf_pred);
319 }
320 pred_delta = pred_value - tracker.GetTreeSamplePrediction(i, tree_num);
321 tracker.SetTreeSamplePrediction(i, tree_num, pred_value);
322 tracker.SetSamplePrediction(i, tracker.GetSamplePrediction(i) + pred_delta);
323 } else {
324 // If the tree has not yet been modified via a sampling step,
325 // we can query its prediction directly from the SamplePredMapper stored in tracker
326 pred_value = tracker.GetTreeSamplePrediction(i, tree_num);
327 }
328 // Run op (either plus or minus) on the residual and the new prediction
329 new_resid = op(residual.GetElement(i), pred_value);
330 residual.SetElement(i, new_resid);
331 }
332}
333
334static inline void UpdateResidualNewBasis(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, TreeEnsemble* forest) {
335 CHECK(dataset.HasBasis());
336 data_size_t n = dataset.GetCovariates().rows();
337 int num_trees = forest->NumTrees();
338 double prev_tree_pred;
339 double new_tree_pred;
340 int32_t leaf_pred;
341 double new_resid;
342 for (int tree_num = 0; tree_num < num_trees; tree_num++) {
343 Tree* tree = forest->GetTree(tree_num);
344 for (data_size_t i = 0; i < n; i++) {
345 // Add back the currently stored tree prediction
346 prev_tree_pred = tracker.GetTreeSamplePrediction(i, tree_num);
347 new_resid = residual.GetElement(i) + prev_tree_pred;
348
349 // Compute new prediction based on updated basis
350 leaf_pred = tracker.GetNodeId(i, tree_num);
351 new_tree_pred = tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
352
353 // Cache the new prediction in the tracker
354 tracker.SetTreeSamplePrediction(i, tree_num, new_tree_pred);
355
356 // Subtract out the updated tree prediction
357 new_resid -= new_tree_pred;
358
359 // Propagate the change back to the residual
360 residual.SetElement(i, new_resid);
361 }
362 }
363 tracker.SyncPredictions();
364}
365
366static inline void UpdateVarModelTree(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, Tree* tree,
367 int tree_num, bool requires_basis, std::function<double(double, double)> op, bool tree_new) {
368 data_size_t n = dataset.GetCovariates().rows();
369 double pred_value;
370 int32_t leaf_pred;
371 double new_weight;
372 double pred_delta;
373 double prev_tree_pred;
374 double prev_pred;
375 for (data_size_t i = 0; i < n; i++) {
376 if (tree_new) {
377 // If the tree has been newly sampled or adjusted, we must rerun the prediction
378 // method and update the SamplePredMapper stored in tracker
379 leaf_pred = tracker.GetNodeId(i, tree_num);
380 if (requires_basis) {
381 pred_value = tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
382 } else {
383 pred_value = tree->PredictFromNode(leaf_pred);
384 }
385 prev_tree_pred = tracker.GetTreeSamplePrediction(i, tree_num);
386 prev_pred = tracker.GetSamplePrediction(i);
387 pred_delta = pred_value - prev_tree_pred;
388 tracker.SetTreeSamplePrediction(i, tree_num, pred_value);
389 tracker.SetSamplePrediction(i, prev_pred + pred_delta);
390 new_weight = std::log(dataset.VarWeightValue(i)) + pred_value;
391 dataset.SetVarWeightValue(i, new_weight, true);
392 } else {
393 // If the tree has not yet been modified via a sampling step,
394 // we can query its prediction directly from the SamplePredMapper stored in tracker
395 pred_value = tracker.GetTreeSamplePrediction(i, tree_num);
396 new_weight = std::log(dataset.VarWeightValue(i)) - pred_value;
397 dataset.SetVarWeightValue(i, new_weight, true);
398 }
399 }
400}
401
402static inline void UpdateCLogLogModelTree(ForestTracker& tracker, ForestDataset& dataset, ColumnVector& residual, Tree* tree, int tree_num,
403 bool requires_basis, bool tree_new) {
404 data_size_t n = dataset.GetCovariates().rows();
405
406 double pred_value;
407 int32_t leaf_pred;
408 double pred_delta;
409 for (data_size_t i = 0; i < n; i++) {
410 if (tree_new) {
411 // If the tree has been newly sampled or adjusted, we must rerun the prediction
412 // method and update the SamplePredMapper stored in tracker
413 leaf_pred = tracker.GetNodeId(i, tree_num);
414 if (requires_basis) {
415 pred_value = tree->PredictFromNode(leaf_pred, dataset.GetBasis(), i);
416 } else {
417 pred_value = tree->PredictFromNode(leaf_pred);
418 }
419 pred_delta = pred_value - tracker.GetTreeSamplePrediction(i, tree_num);
420 tracker.SetTreeSamplePrediction(i, tree_num, pred_value);
421 tracker.SetSamplePrediction(i, tracker.GetSamplePrediction(i) + pred_delta);
422 // Set auxiliary data slot 1 to forest predictions excluding the current tree (tree_num)
423 dataset.SetAuxiliaryDataValue(1, i, tracker.GetSamplePrediction(i) - pred_value);
424 } else {
425 // If the tree has not yet been modified via a sampling step,
426 // we can query its prediction directly from the SamplePredMapper stored in tracker
427 pred_value = tracker.GetTreeSamplePrediction(i, tree_num);
428 // Set auxiliary data slot 1 to forest predictions excluding the current tree (tree_num): needed? since tree not changed?
429 double current_lambda_hat = tracker.GetSamplePrediction(i);
430 double lambda_minus = current_lambda_hat - pred_value;
431 dataset.SetAuxiliaryDataValue(1, i, lambda_minus);
432 }
433 }
434}
435
436template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
437static inline std::tuple<double, double, data_size_t, data_size_t> EvaluateProposedSplit(
438 ForestDataset& dataset, ForestTracker& tracker, ColumnVector& residual, LeafModel& leaf_model,
439 TreeSplit& split, int tree_num, int leaf_num, int split_feature, double global_variance,
440 int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args
441) {
442 // Initialize sufficient statistics
443 LeafSuffStat node_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
444 LeafSuffStat left_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
445 LeafSuffStat right_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
446
447 // Accumulate sufficient statistics
448 AccumulateSuffStatProposed<LeafSuffStat, LeafSuffStatConstructorArgs...>(
449 node_suff_stat, left_suff_stat, right_suff_stat, dataset, tracker,
450 residual, global_variance, split, tree_num, leaf_num, split_feature, num_threads,
451 leaf_suff_stat_args...
452 );
453 data_size_t left_n = left_suff_stat.n;
454 data_size_t right_n = right_suff_stat.n;
455
456 // Evaluate split
457 double split_log_ml = leaf_model.SplitLogMarginalLikelihood(left_suff_stat, right_suff_stat, global_variance);
458 double no_split_log_ml = leaf_model.NoSplitLogMarginalLikelihood(node_suff_stat, global_variance);
459
460 return std::tuple<double, double, data_size_t, data_size_t>(split_log_ml, no_split_log_ml, left_n, right_n);
461}
462
463template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
464static inline std::tuple<double, double, data_size_t, data_size_t> EvaluateExistingSplit(
465 ForestDataset& dataset, ForestTracker& tracker, ColumnVector& residual, LeafModel& leaf_model,
466 double global_variance, int tree_num, int split_node_id, int left_node_id, int right_node_id,
467 LeafSuffStatConstructorArgs&... leaf_suff_stat_args
468) {
469 // Initialize sufficient statistics
470 LeafSuffStat node_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
471 LeafSuffStat left_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
472 LeafSuffStat right_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
473
474 // Accumulate sufficient statistics
475 AccumulateSuffStatExisting<LeafSuffStat>(node_suff_stat, left_suff_stat, right_suff_stat, dataset, tracker,
476 residual, global_variance, tree_num, split_node_id, left_node_id, right_node_id);
477 data_size_t left_n = left_suff_stat.n;
478 data_size_t right_n = right_suff_stat.n;
479
480 // Evaluate split
481 double split_log_ml = leaf_model.SplitLogMarginalLikelihood(left_suff_stat, right_suff_stat, global_variance);
482 double no_split_log_ml = leaf_model.NoSplitLogMarginalLikelihood(node_suff_stat, global_variance);
483
484 return std::tuple<double, double, data_size_t, data_size_t>(split_log_ml, no_split_log_ml, left_n, right_n);
485}
486
487template <typename LeafModel>
488static inline void AdjustStateBeforeTreeSampling(ForestTracker& tracker, LeafModel& leaf_model, ForestDataset& dataset,
489 ColumnVector& residual, TreePrior& tree_prior, bool backfitting, Tree* tree, int tree_num) {
490 if constexpr (std::is_same_v<LeafModel, CloglogOrdinalLeafModel>) {
491 UpdateCLogLogModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), false);
492 } else if (backfitting) {
493 UpdateMeanModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), std::plus<double>(), false);
494 } else {
495 // TODO: think about a generic way to store "state" corresponding to the other models?
496 UpdateVarModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), std::minus<double>(), false);
497 }
498}
499
500template <typename LeafModel>
501static inline void AdjustStateAfterTreeSampling(ForestTracker& tracker, LeafModel& leaf_model, ForestDataset& dataset,
502 ColumnVector& residual, TreePrior& tree_prior, bool backfitting, Tree* tree, int tree_num) {
503 if constexpr (std::is_same_v<LeafModel, CloglogOrdinalLeafModel>) {
504 UpdateCLogLogModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), true);
505 } else if (backfitting) {
506 UpdateMeanModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), std::minus<double>(), true);
507 } else {
508 // TODO: think about a generic way to store "state" corresponding to the other models?
509 UpdateVarModelTree(tracker, dataset, residual, tree, tree_num, leaf_model.RequiresBasis(), std::plus<double>(), true);
510 }
511}
512
513template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
514static inline void SampleSplitRule(Tree* tree, ForestTracker& tracker, LeafModel& leaf_model, ForestDataset& dataset, ColumnVector& residual,
515 TreePrior& tree_prior, std::mt19937& gen, int tree_num, double global_variance, int cutpoint_grid_size,
516 std::unordered_map<int, std::pair<data_size_t, data_size_t>>& node_index_map, std::deque<node_t>& split_queue,
517 int node_id, data_size_t node_begin, data_size_t node_end, std::vector<double>& variable_weights,
518 std::vector<FeatureType>& feature_types, std::vector<bool> feature_subset, int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
519 // Leaf depth
520 int leaf_depth = tree->GetDepth(node_id);
521
522 // Maximum leaf depth
523 int32_t max_depth = tree_prior.GetMaxDepth();
524
525 if ((max_depth == -1) || (leaf_depth < max_depth)) {
526
527 // Vector of vectors to store results for each feature
528 int p = dataset.NumCovariates();
529 std::vector<std::vector<double>> feature_log_cutpoint_evaluations(p+1);
530 std::vector<std::vector<double>> feature_cutpoint_values(p+1);
531 std::vector<int> feature_cutpoint_counts(p+1, 0);
532 StochTree::data_size_t valid_cutpoint_count;
533
534 // Evaluate all possible cutpoints according to the leaf node model,
535 // recording their log-likelihood and other split information in a series of vectors.
536
537 // Initialize node sufficient statistics
538 LeafSuffStat node_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
539
540 // Accumulate aggregate sufficient statistic for the node to be split
541 AccumulateSingleNodeSuffStat<LeafSuffStat, false>(node_suff_stat, dataset, tracker, residual, tree_num, node_id);
542
543 // Compute the "no split" log marginal likelihood
544 double no_split_log_ml = leaf_model.NoSplitLogMarginalLikelihood(node_suff_stat, global_variance);
545
546 // Unpack data
547 Eigen::MatrixXd& covariates = dataset.GetCovariates();
548 Eigen::VectorXd& outcome = residual.GetData();
549 Eigen::VectorXd var_weights;
550 bool has_weights = dataset.HasVarWeights();
551 if (has_weights) var_weights = dataset.GetVarWeights();
552
553 // Minimum size of newly created leaf nodes (used to rule out invalid splits)
554 int32_t min_samples_in_leaf = tree_prior.GetMinSamplesLeaf();
555
556 // Compute sufficient statistics for each possible split
557 data_size_t num_cutpoints = 0;
558 if (num_threads == -1) {
559 num_threads = GetOptimalThreadCount(static_cast<int>(covariates.cols() * covariates.rows()));
560 }
561
562 // Initialize cutpoint grid container
563 CutpointGridContainer cutpoint_grid_container(covariates, outcome, cutpoint_grid_size);
564
565 // Evaluate all possible splits for each feature in parallel
566 StochTree::ParallelFor(0, covariates.cols(), num_threads, [&](int j) {
567 if ((std::abs(variable_weights.at(j)) > kEpsilon) && (feature_subset[j])) {
568 // Enumerate cutpoint strides
569 cutpoint_grid_container.CalculateStrides(covariates, outcome, tracker.GetSortedNodeSampleTracker(), node_id, node_begin, node_end, j, feature_types);
570
571 // Left and right node sufficient statistics
572 LeafSuffStat left_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
573 LeafSuffStat right_suff_stat = LeafSuffStat(leaf_suff_stat_args...);
574
575 // Iterate through possible cutpoints
576 int32_t num_feature_cutpoints = cutpoint_grid_container.NumCutpoints(j);
577 FeatureType feature_type = feature_types[j];
578 // Since we partition an entire cutpoint bin to the left, we must stop one bin before the total number of cutpoint bins
579 for (data_size_t cutpoint_idx = 0; cutpoint_idx < (num_feature_cutpoints - 1); cutpoint_idx++) {
580 data_size_t current_bin_begin = cutpoint_grid_container.BinStartIndex(cutpoint_idx, j);
581 data_size_t current_bin_size = cutpoint_grid_container.BinLength(cutpoint_idx, j);
582 data_size_t next_bin_begin = cutpoint_grid_container.BinStartIndex(cutpoint_idx + 1, j);
583
584 // Accumulate sufficient statistics for the left node
585 AccumulateCutpointBinSuffStat<LeafSuffStat>(left_suff_stat, tracker, cutpoint_grid_container, dataset, residual,
586 global_variance, tree_num, node_id, j, cutpoint_idx);
587
588 // Compute the corresponding right node sufficient statistics
589 right_suff_stat.SubtractSuffStat(node_suff_stat, left_suff_stat);
590
591 // Store the bin index as the "cutpoint value" - we can use this to query the actual split
592 // value or the set of split categories later on once a split is chose
593 double cutoff_value = cutpoint_idx;
594
595 // Only include cutpoint for consideration if it defines a valid split in the training data
596 bool valid_split = (left_suff_stat.SampleGreaterThanEqual(min_samples_in_leaf) &&
597 right_suff_stat.SampleGreaterThanEqual(min_samples_in_leaf));
598 if (valid_split) {
599 feature_cutpoint_counts[j]++;
600 // Add to split rule vector
601 feature_cutpoint_values[j].push_back(cutoff_value);
602 // Add the log marginal likelihood of the split to the split eval vector
603 double split_log_ml = leaf_model.SplitLogMarginalLikelihood(left_suff_stat, right_suff_stat, global_variance);
604 feature_log_cutpoint_evaluations[j].push_back(split_log_ml);
605 }
606 }
607 }
608 });
609
610 // Compute total number of cutpoints
611 valid_cutpoint_count = std::accumulate(feature_cutpoint_counts.begin(), feature_cutpoint_counts.end(), 0);
612
613 // Add the log marginal likelihood of the "no-split" option (adjusted for tree prior and cutpoint size per the XBART paper)
614 feature_log_cutpoint_evaluations[covariates.cols()].push_back(no_split_log_ml);
615
616 // Compute an adjustment to reflect the no split prior probability and the number of cutpoints
617 double bart_prior_no_split_adj;
618 double alpha = tree_prior.GetAlpha();
619 double beta = tree_prior.GetBeta();
620 int node_depth = tree->GetDepth(node_id);
621 if (valid_cutpoint_count == 0) {
622 bart_prior_no_split_adj = std::log(((std::pow(1+node_depth, beta))/alpha) - 1.0);
623 } else {
624 bart_prior_no_split_adj = std::log(((std::pow(1+node_depth, beta))/alpha) - 1.0) + std::log(valid_cutpoint_count);
625 }
626 feature_log_cutpoint_evaluations[covariates.cols()][0] += bart_prior_no_split_adj;
627
628
629 // Convert log marginal likelihood to marginal likelihood, normalizing by the maximum log-likelihood
630 double largest_ml = -std::numeric_limits<double>::infinity();
631 for (int j = 0; j < p + 1; j++) {
632 if (feature_log_cutpoint_evaluations[j].size() > 0) {
633 double feature_max_ml = *std::max_element(feature_log_cutpoint_evaluations[j].begin(), feature_log_cutpoint_evaluations[j].end());;
634 largest_ml = std::max(largest_ml, feature_max_ml);
635 }
636 }
637 std::vector<std::vector<double>> feature_cutpoint_evaluations(p+1);
638 for (int j = 0; j < p + 1; j++) {
639 if (feature_log_cutpoint_evaluations[j].size() > 0) {
640 feature_cutpoint_evaluations[j].resize(feature_log_cutpoint_evaluations[j].size());
641 for (int i = 0; i < feature_log_cutpoint_evaluations[j].size(); i++) {
642 feature_cutpoint_evaluations[j][i] = std::exp(feature_log_cutpoint_evaluations[j][i] - largest_ml);
643 }
644 }
645 }
646
647 // Compute sum of marginal likelihoods for each feature
648 std::vector<double> feature_total_cutpoint_evaluations(p+1, 0.0);
649 for (int j = 0; j < p + 1; j++) {
650 if (feature_log_cutpoint_evaluations[j].size() > 0) {
651 feature_total_cutpoint_evaluations[j] = std::accumulate(feature_cutpoint_evaluations[j].begin(), feature_cutpoint_evaluations[j].end(), 0.0);
652 } else {
653 feature_total_cutpoint_evaluations[j] = 0.0;
654 }
655 }
656
657 // First, sample a feature according to feature_total_cutpoint_evaluations
658 int feature_chosen = sample_discrete_stateless(gen, feature_total_cutpoint_evaluations);
659
660 // Then, sample a cutpoint according to feature_cutpoint_evaluations[feature_chosen]
661 int cutpoint_chosen = sample_discrete_stateless(gen, feature_cutpoint_evaluations[feature_chosen], feature_total_cutpoint_evaluations[feature_chosen]);
662
663 if (feature_chosen == p){
664 // "No split" sampled, don't split or add any nodes to split queue
665 return;
666 } else {
667 // Split sampled
668 int feature_split = feature_chosen;
669 FeatureType feature_type = feature_types[feature_split];
670 double split_value = feature_cutpoint_values[feature_split][cutpoint_chosen];
671 // Perform all of the relevant "split" operations in the model, tree and training dataset
672
673 // Compute node sample size
674 data_size_t node_n = node_end - node_begin;
675
676 // Actual numeric cutpoint used for ordered categorical and numeric features
677 double split_value_numeric;
678 TreeSplit tree_split;
679
680 // We will use these later in the model expansion
681 data_size_t left_n = 0;
682 data_size_t right_n = 0;
683 data_size_t sort_idx;
684 double feature_value;
685 bool split_true;
686
687 if (feature_type == FeatureType::kUnorderedCategorical) {
688 // Determine the number of categories available in a categorical split and the set of categories that route observations to the left node after split
689 int num_categories;
690 std::vector<std::uint32_t> categories = cutpoint_grid_container.CutpointVector(static_cast<std::uint32_t>(split_value), feature_split);
691 tree_split = TreeSplit(categories);
692 } else if (feature_type == FeatureType::kOrderedCategorical) {
693 // Convert the bin split to an actual split value
694 split_value_numeric = cutpoint_grid_container.CutpointValue(static_cast<std::uint32_t>(split_value), feature_split);
695 tree_split = TreeSplit(split_value_numeric);
696 } else if (feature_type == FeatureType::kNumeric) {
697 // Convert the bin split to an actual split value
698 split_value_numeric = cutpoint_grid_container.CutpointValue(static_cast<std::uint32_t>(split_value), feature_split);
699 tree_split = TreeSplit(split_value_numeric);
700 } else {
701 Log::Fatal("Invalid split type");
702 }
703
704 // Add split to tree and trackers
705 AddSplitToModel(tracker, dataset, tree_prior, tree_split, gen, tree, tree_num, node_id, feature_split, true, num_threads);
706
707 // Determine the number of observation in the newly created left node
708 int left_node = tree->LeftChild(node_id);
709 int right_node = tree->RightChild(node_id);
710 auto left_begin_iter = tracker.SortedNodeBeginIterator(left_node, feature_split);
711 auto left_end_iter = tracker.SortedNodeEndIterator(left_node, feature_split);
712 for (auto i = left_begin_iter; i < left_end_iter; i++) {
713 left_n += 1;
714 }
715
716 // Add the begin and end indices for the new left and right nodes to node_index_map
717 node_index_map.insert({left_node, std::make_pair(node_begin, node_begin + left_n)});
718 node_index_map.insert({right_node, std::make_pair(node_begin + left_n, node_end)});
719
720 // Add the left and right nodes to the split tracker
721 split_queue.push_front(right_node);
722 split_queue.push_front(left_node);
723 }
724 }
725}
726
727template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
728static inline void GFRSampleTreeOneIter(Tree* tree, ForestTracker& tracker, ForestContainer& forests, LeafModel& leaf_model, ForestDataset& dataset,
729 ColumnVector& residual, TreePrior& tree_prior, std::mt19937& gen, std::vector<double>& variable_weights,
730 int tree_num, double global_variance, std::vector<FeatureType>& feature_types, int cutpoint_grid_size,
731 int num_features_subsample, int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
732 int root_id = Tree::kRoot;
733 int curr_node_id;
734 data_size_t curr_node_begin;
735 data_size_t curr_node_end;
736 data_size_t n = dataset.GetCovariates().rows();
737 int p = dataset.GetCovariates().cols();
738
739 // Subsample features (if requested)
740 std::vector<bool> feature_subset(p, true);
741 if (num_features_subsample < p) {
742 // Check if the number of (meaningfully) nonzero selection probabilities is greater than num_features_subsample
743 int number_nonzero_weights = 0;
744 for (int j = 0; j < p; j++) {
745 if (std::abs(variable_weights.at(j)) > kEpsilon) {
746 number_nonzero_weights++;
747 }
748 }
749 if (number_nonzero_weights > num_features_subsample) {
750 // Sample with replacement according to variable_weights
751 std::vector<int> feature_indices(p);
752 std::iota(feature_indices.begin(), feature_indices.end(), 0);
753 std::vector<int> features_selected(num_features_subsample);
754 sample_without_replacement<int, double>(
755 features_selected.data(), variable_weights.data(), feature_indices.data(),
756 p, num_features_subsample, gen
757 );
758 for (int i = 0; i < p; i++) {
759 feature_subset.at(i) = false;
760 }
761 for (const auto& feat : features_selected) {
762 feature_subset.at(feat) = true;
763 }
764 }
765 }
766
767 // Mapping from node id to start and end points of sorted indices
768 std::unordered_map<int, std::pair<data_size_t, data_size_t>> node_index_map;
769 node_index_map.insert({root_id, std::make_pair(0, n)});
770 std::pair<data_size_t, data_size_t> begin_end;
771 // Add root node to the split queue
772 std::deque<node_t> split_queue;
773 split_queue.push_back(Tree::kRoot);
774 // Run the "GrowFromRoot" procedure using a stack in place of recursion
775 while (!split_queue.empty()) {
776 // Remove the next node from the queue
777 curr_node_id = split_queue.front();
778 split_queue.pop_front();
779 // Determine the beginning and ending indices of the left and right nodes
780 begin_end = node_index_map[curr_node_id];
781 curr_node_begin = begin_end.first;
782 curr_node_end = begin_end.second;
783 // Draw a split rule at random
784 SampleSplitRule<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
785 tree, tracker, leaf_model, dataset, residual, tree_prior, gen, tree_num, global_variance, cutpoint_grid_size,
786 node_index_map, split_queue, curr_node_id, curr_node_begin, curr_node_end, variable_weights, feature_types,
787 feature_subset, num_threads, leaf_suff_stat_args...
788 );
789 }
790}
791
823template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
824static inline void GFRSampleOneIter(TreeEnsemble& active_forest, ForestTracker& tracker, ForestContainer& forests, LeafModel& leaf_model, ForestDataset& dataset,
825 ColumnVector& residual, TreePrior& tree_prior, std::mt19937& gen, std::vector<double>& variable_weights,
826 std::vector<int>& sweep_update_indices, double global_variance, std::vector<FeatureType>& feature_types, int cutpoint_grid_size,
827 bool keep_forest, bool pre_initialized, bool backfitting, int num_features_subsample, int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
828 // Run the GFR algorithm for each tree
829 int num_trees = forests.NumTrees();
830 for (const int& i : sweep_update_indices) {
831 // Adjust any model state needed to run a tree sampler
832 // For models that involve Bayesian backfitting, this amounts to adding tree i's
833 // predictions back to the residual (thus, training a model on the "partial residual")
834 // For more general "blocked MCMC" models, this might require changes to a ForestTracker or Dataset object
835 Tree* tree = active_forest.GetTree(i);
836 AdjustStateBeforeTreeSampling<LeafModel>(tracker, leaf_model, dataset, residual, tree_prior, backfitting, tree, i);
837
838 // Reset the tree and sample trackers
839 active_forest.ResetInitTree(i);
840 tracker.ResetRoot(dataset.GetCovariates(), feature_types, i);
841 tree = active_forest.GetTree(i);
842
843 // Sample tree i
844 GFRSampleTreeOneIter<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
845 tree, tracker, forests, leaf_model, dataset, residual, tree_prior, gen,
846 variable_weights, i, global_variance, feature_types, cutpoint_grid_size,
847 num_features_subsample, num_threads, leaf_suff_stat_args...
848 );
849
850 // Sample leaf parameters for tree i
851 tree = active_forest.GetTree(i);
852 leaf_model.SampleLeafParameters(dataset, tracker, residual, tree, i, global_variance, gen);
853
854 // Adjust any model state needed to run a tree sampler
855 // For models that involve Bayesian backfitting, this amounts to subtracting tree i's
856 // predictions back out of the residual (thus, using an updated "partial residual" in the following interation).
857 // For more general "blocked MCMC" models, this might require changes to a ForestTracker or Dataset object
858 AdjustStateAfterTreeSampling<LeafModel>(tracker, leaf_model, dataset, residual, tree_prior, backfitting, tree, i);
859 }
860
861 if (keep_forest) {
862 forests.AddSample(active_forest);
863 }
864}
865
866// Proposal availability uses observation counts only. Selecting a constant
867// variable or a leaf at maximum depth still yields a rejected grow proposal.
869 int leaves;
870 int leaf_parents;
871 int grow_candidates;
872 double GrowProbability() const {
873 return grow_candidates > 0 ? (leaf_parents > 0 ? 0.5 : 1.0) : 0.0;
874 }
875 double PruneProbability() const {
876 return leaf_parents > 0 ? (grow_candidates > 0 ? 0.5 : 1.0) : 0.0;
877 }
878};
879
880static inline bool MCMCSizeAllowsGrow(data_size_t n, int minimum) {
881 // Equality permits two children with exactly minimum observations each.
882 return n >= 2 * minimum;
883}
884
885static inline MCMCProposalState MCMCGetProposalState(Tree* tree, ForestTracker& tracker, int tree_num, int minimum) {
886 MCMCProposalState state{tree->NumLeaves(), tree->NumLeafParents(), 0};
887 for (int leaf : tree->GetLeaves()) {
888 state.grow_candidates += MCMCSizeAllowsGrow(tracker.UnsortedNodeSize(tree_num, leaf), minimum);
889 }
890 return state;
891}
892
893static inline MCMCProposalState MCMCStateAfterGrow(Tree* tree, MCMCProposalState state, int leaf,
894 data_size_t left_n, data_size_t right_n, int minimum) {
895 state.leaves += 1;
896 state.leaf_parents += 1;
897 if (!tree->IsRoot(leaf) && tree->IsLeafParent(tree->Parent(leaf))) {
898 state.leaf_parents -= 1;
899 }
900 state.grow_candidates += MCMCSizeAllowsGrow(left_n, minimum) + MCMCSizeAllowsGrow(right_n, minimum)
901 - MCMCSizeAllowsGrow(left_n + right_n, minimum);
902 return state;
903}
904
905static inline MCMCProposalState MCMCStateAfterPrune(Tree* tree, MCMCProposalState state, int node,
906 data_size_t left_n, data_size_t right_n, int minimum) {
907 state.leaves -= 1;
908 state.leaf_parents -= 1;
909 if (!tree->IsRoot(node)) {
910 int parent = tree->Parent(node);
911 int sibling = tree->LeftChild(parent) == node ? tree->RightChild(parent) : tree->LeftChild(parent);
912 if (tree->IsLeaf(sibling)) state.leaf_parents += 1;
913 }
914 state.grow_candidates += MCMCSizeAllowsGrow(left_n + right_n, minimum)
915 - MCMCSizeAllowsGrow(left_n, minimum) - MCMCSizeAllowsGrow(right_n, minimum);
916 return state;
917}
918
919// The split-rule density cancels with the corresponding conditional tree prior.
920// These terms cover move type and uniform leaf / leaf-parent selection only.
921static inline double MCMCLogProposalRatio(const MCMCProposalState& from, const MCMCProposalState& to, bool grow) {
922 if (grow) {
923 return std::log(to.PruneProbability()) - std::log(static_cast<double>(to.leaf_parents))
924 - std::log(from.GrowProbability()) + std::log(static_cast<double>(from.leaves));
925 }
926 return std::log(to.GrowProbability()) - std::log(static_cast<double>(to.leaves))
927 - std::log(from.PruneProbability()) + std::log(static_cast<double>(from.leaf_parents));
928}
929
930template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
931static inline void MCMCGrowTreeOneIter(Tree* tree, ForestTracker& tracker, LeafModel& leaf_model, ForestDataset& dataset, ColumnVector& residual,
932 TreePrior& tree_prior, std::mt19937& gen, int tree_num, std::vector<double>& variable_weights,
933 double global_variance, double prob_grow_old, int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
934 // Extract dataset information
935 data_size_t n = dataset.GetCovariates().rows();
936
937 // Choose a leaf node at random
938 int num_leaves = tree->NumLeaves();
939 std::vector<int> leaves = tree->GetLeaves();
940 std::vector<double> leaf_weights(num_leaves);
941 std::fill(leaf_weights.begin(), leaf_weights.end(), 1.0/num_leaves);
942 walker_vose leaf_dist(leaf_weights.begin(), leaf_weights.end());
943 int leaf_chosen = leaves[leaf_dist(gen)];
944 int leaf_depth = tree->GetDepth(leaf_chosen);
945
946 // Maximum leaf depth
947 int32_t max_depth = tree_prior.GetMaxDepth();
948
949 // Terminate early if cannot be split
950 bool accept;
951 if ((leaf_depth >= max_depth) && (max_depth != -1)) {
952 accept = false;
953 } else {
954
955 // Select a split variable at random
956 int p = dataset.GetCovariates().cols();
957 CHECK_EQ(variable_weights.size(), p);
958 walker_vose var_dist(variable_weights.begin(), variable_weights.end());
959 int var_chosen = var_dist(gen);
960
961 // Determine the range of possible cutpoints
962 // TODO: specialize this for binary / ordered categorical / unordered categorical variables
963 double var_min, var_max;
964 VarSplitRange(tracker, dataset, tree_num, leaf_chosen, var_chosen, var_min, var_max);
965 if (var_max <= var_min) {
966 return;
967 }
968
969 // Split based on var_min to var_max in a given node
970 double split_point_chosen = standard_uniform_draw_53bit(gen) * (var_max - var_min) + var_min;
971
972 // Create a split object
973 TreeSplit split = TreeSplit(split_point_chosen);
974
975 // Compute the marginal likelihood of split and no split, given the leaf prior
976 std::tuple<double, double, int32_t, int32_t> split_eval = EvaluateProposedSplit<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
977 dataset, tracker, residual, leaf_model, split, tree_num, leaf_chosen, var_chosen, global_variance, num_threads, leaf_suff_stat_args...
978 );
979 double split_log_marginal_likelihood = std::get<0>(split_eval);
980 double no_split_log_marginal_likelihood = std::get<1>(split_eval);
981 int32_t left_n = std::get<2>(split_eval);
982 int32_t right_n = std::get<3>(split_eval);
983
984 // Reject the split if either of the left and right nodes are smaller than tree_prior.GetMinSamplesLeaf()
985 bool left_node_sample_cutoff = left_n >= tree_prior.GetMinSamplesLeaf();
986 bool right_node_sample_cutoff = right_n >= tree_prior.GetMinSamplesLeaf();
987 if ((left_node_sample_cutoff) && (right_node_sample_cutoff)) {
988
989 // Determine probability of growing the split node and its two new left and right nodes
990 double pg = tree_prior.GetAlpha() * std::pow(1+leaf_depth, -tree_prior.GetBeta());
991 double pgl = tree_prior.GetAlpha() * std::pow(1+leaf_depth+1, -tree_prior.GetBeta());
992 double pgr = tree_prior.GetAlpha() * std::pow(1+leaf_depth+1, -tree_prior.GetBeta());
993
994 auto old_state = MCMCGetProposalState(tree, tracker, tree_num, tree_prior.GetMinSamplesLeaf());
995 auto new_state = MCMCStateAfterGrow(tree, old_state, leaf_chosen, left_n, right_n, tree_prior.GetMinSamplesLeaf());
996
997 // Compute the final MH ratio
998 double log_mh_ratio = (
999 std::log(pg) + std::log(1-pgl) + std::log(1-pgr) - std::log(1-pg) +
1000 MCMCLogProposalRatio(old_state, new_state, true) - no_split_log_marginal_likelihood + split_log_marginal_likelihood
1001 );
1002 // Threshold at 0
1003 if (log_mh_ratio > 0) {
1004 log_mh_ratio = 0;
1005 }
1006
1007 // Draw a uniform random variable and accept/reject the proposal on this basis
1008 double log_acceptance_prob = std::log(standard_uniform_draw_53bit(gen));
1009 if (log_acceptance_prob <= log_mh_ratio) {
1010 accept = true;
1011 AddSplitToModel(tracker, dataset, tree_prior, split, gen, tree, tree_num, leaf_chosen, var_chosen, false, num_threads);
1012 } else {
1013 accept = false;
1014 }
1015
1016 } else {
1017 accept = false;
1018 }
1019 }
1020}
1021
1022template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
1023static inline void MCMCPruneTreeOneIter(Tree* tree, ForestTracker& tracker, LeafModel& leaf_model, ForestDataset& dataset, ColumnVector& residual,
1024 TreePrior& tree_prior, std::mt19937& gen, int tree_num, double global_variance, int num_threads,
1025 LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
1026 // Choose a "leaf parent" node at random
1027 int num_leaves = tree->NumLeaves();
1028 int num_leaf_parents = tree->NumLeafParents();
1029 std::vector<int> leaf_parents = tree->GetLeafParents();
1030 std::vector<double> leaf_parent_weights(num_leaf_parents);
1031 std::fill(leaf_parent_weights.begin(), leaf_parent_weights.end(), 1.0/num_leaf_parents);
1032 walker_vose leaf_parent_dist(leaf_parent_weights.begin(), leaf_parent_weights.end());
1033 int leaf_parent_chosen = leaf_parents[leaf_parent_dist(gen)];
1034 int leaf_parent_depth = tree->GetDepth(leaf_parent_chosen);
1035 int left_node = tree->LeftChild(leaf_parent_chosen);
1036 int right_node = tree->RightChild(leaf_parent_chosen);
1037 int feature_split = tree->SplitIndex(leaf_parent_chosen);
1038
1039 // Compute the marginal likelihood for the leaf parent and its left and right nodes
1040 std::tuple<double, double, int32_t, int32_t> split_eval = EvaluateExistingSplit<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
1041 dataset, tracker, residual, leaf_model, global_variance, tree_num, leaf_parent_chosen, left_node, right_node, leaf_suff_stat_args...
1042 );
1043 double split_log_marginal_likelihood = std::get<0>(split_eval);
1044 double no_split_log_marginal_likelihood = std::get<1>(split_eval);
1045 int32_t left_n = std::get<2>(split_eval);
1046 int32_t right_n = std::get<3>(split_eval);
1047
1048 // Determine probability of growing the split node and its two new left and right nodes
1049 double pg = tree_prior.GetAlpha() * std::pow(1+leaf_parent_depth, -tree_prior.GetBeta());
1050 double pgl = tree_prior.GetAlpha() * std::pow(1+leaf_parent_depth+1, -tree_prior.GetBeta());
1051 double pgr = tree_prior.GetAlpha() * std::pow(1+leaf_parent_depth+1, -tree_prior.GetBeta());
1052
1053 auto old_state = MCMCGetProposalState(tree, tracker, tree_num, tree_prior.GetMinSamplesLeaf());
1054 auto new_state = MCMCStateAfterPrune(tree, old_state, leaf_parent_chosen, left_n, right_n, tree_prior.GetMinSamplesLeaf());
1055
1056 // Compute the final MH ratio
1057 double log_mh_ratio = (
1058 std::log(1-pg) - std::log(pg) - std::log(1-pgl) - std::log(1-pgr) +
1059 MCMCLogProposalRatio(old_state, new_state, false) + no_split_log_marginal_likelihood - split_log_marginal_likelihood
1060 );
1061 // Threshold at 0
1062 if (log_mh_ratio > 0) {
1063 log_mh_ratio = 0;
1064 }
1065
1066 // Draw a uniform random variable and accept/reject the proposal on this basis
1067 bool accept;
1068 double log_acceptance_prob = std::log(standard_uniform_draw_53bit(gen));
1069 if (log_acceptance_prob <= log_mh_ratio) {
1070 accept = true;
1071 RemoveSplitFromModel(tracker, dataset, tree_prior, gen, tree, tree_num, leaf_parent_chosen, left_node, right_node, false);
1072 } else {
1073 accept = false;
1074 }
1075}
1076
1077template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
1078static inline void MCMCSampleTreeOneIter(Tree* tree, ForestTracker& tracker, ForestContainer& forests, LeafModel& leaf_model, ForestDataset& dataset,
1079 ColumnVector& residual, TreePrior& tree_prior, std::mt19937& gen, std::vector<double>& variable_weights,
1080 int tree_num, double global_variance, int num_threads, LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
1081 auto state = MCMCGetProposalState(tree, tracker, tree_num, tree_prior.GetMinSamplesLeaf());
1082 double prob_grow = state.GrowProbability();
1083 double prob_prune = state.PruneProbability();
1084 // An undersized root has no legal move; retain the current tree.
1085 if (prob_grow == 0.0 && prob_prune == 0.0) return;
1086 std::vector<double> step_probs{prob_grow, prob_prune};
1087 walker_vose step_dist(step_probs.begin(), step_probs.end());
1088
1089 // Draw a split rule at random
1090 data_size_t step_chosen = step_dist(gen);
1091 bool accept;
1092
1093 if (step_chosen == 0) {
1094 MCMCGrowTreeOneIter<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
1095 tree, tracker, leaf_model, dataset, residual, tree_prior, gen, tree_num, variable_weights, global_variance, prob_grow, num_threads, leaf_suff_stat_args...
1096 );
1097 } else {
1098 MCMCPruneTreeOneIter<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
1099 tree, tracker, leaf_model, dataset, residual, tree_prior, gen, tree_num, global_variance, num_threads, leaf_suff_stat_args...
1100 );
1101 }
1102}
1103
1132template <typename LeafModel, typename LeafSuffStat, typename... LeafSuffStatConstructorArgs>
1133static inline void MCMCSampleOneIter(TreeEnsemble& active_forest, ForestTracker& tracker, ForestContainer& forests, LeafModel& leaf_model, ForestDataset& dataset,
1134 ColumnVector& residual, TreePrior& tree_prior, std::mt19937& gen, std::vector<double>& variable_weights,
1135 std::vector<int>& sweep_update_indices, double global_variance, bool keep_forest, bool pre_initialized, bool backfitting, int num_threads,
1136 LeafSuffStatConstructorArgs&... leaf_suff_stat_args) {
1137 // Run the MCMC algorithm for each tree
1138 int num_trees = forests.NumTrees();
1139 for (const int& i : sweep_update_indices) {
1140 // Adjust any model state needed to run a tree sampler
1141 // For models that involve Bayesian backfitting, this amounts to adding tree i's
1142 // predictions back to the residual (thus, training a model on the "partial residual")
1143 // For more general "blocked MCMC" models, this might require changes to a ForestTracker or Dataset object
1144 Tree* tree = active_forest.GetTree(i);
1145 AdjustStateBeforeTreeSampling<LeafModel>(tracker, leaf_model, dataset, residual, tree_prior, backfitting, tree, i);
1146
1147 // Sample tree i
1148 tree = active_forest.GetTree(i);
1149 MCMCSampleTreeOneIter<LeafModel, LeafSuffStat, LeafSuffStatConstructorArgs...>(
1150 tree, tracker, forests, leaf_model, dataset, residual, tree_prior, gen, variable_weights, i,
1151 global_variance, num_threads, leaf_suff_stat_args...
1152 );
1153
1154 // Sample leaf parameters for tree i
1155 tree = active_forest.GetTree(i);
1156 leaf_model.SampleLeafParameters(dataset, tracker, residual, tree, i, global_variance, gen);
1157
1158 // Adjust any model state needed to run a tree sampler
1159 // For models that involve Bayesian backfitting, this amounts to subtracting tree i's
1160 // predictions back out of the residual (thus, using an updated "partial residual" in the following interation).
1161 // For more general "blocked MCMC" models, this might require changes to a ForestTracker or Dataset object
1162 AdjustStateAfterTreeSampling<LeafModel>(tracker, leaf_model, dataset, residual, tree_prior, backfitting, tree, i);
1163 }
1164
1165 if (keep_forest) {
1166 forests.AddSample(active_forest);
1167 }
1168}
1169 // end of sampling_group
1171
1172} // namespace StochTree
1173
1174#endif // STOCHTREE_TREE_SAMPLER_H_
Internal wrapper around Eigen::VectorXd interface for univariate floating point data....
Definition data.h:193
Container class for FeatureCutpointGrid objects stored for every feature in a dataset.
Definition cutpoint_candidates.h:110
Container of TreeEnsemble forest objects. This is the primary (in-memory) storage interface for multi...
Definition container.h:23
void AddSample(TreeEnsemble &forest)
Add a new forest to the container by copying forest.
API for loading and accessing data used to sample tree ensembles The covariates / bases / weights use...
Definition data.h:271
Eigen::MatrixXd & GetCovariates()
Return a reference to the raw Eigen::MatrixXd storing the covariate data.
Definition data.h:383
double CovariateValue(data_size_t row, int col)
Returns a dataset's covariate value stored at (row, col).
Definition data.h:364
"Superclass" wrapper around tracking data structures for forest sampling algorithms
Definition partition_tracker.h:47
Class storing a "forest," or an ensemble of decision trees.
Definition ensemble.h:31
Tree * GetTree(int i)
Return a pointer to a tree in the forest.
Definition ensemble.h:134
void ResetInitTree(int i)
Reset a single tree in an ensemble.
Definition ensemble.h:163
Definition prior.h:43
Representation of arbitrary tree split rules, including numeric split rules (X[,i] <= c) and categori...
Definition tree.h:958
bool SplitTrue(double fvalue)
Whether a given covariate value is True or False on the rule defined by a TreeSplit object.
Definition tree.h:990
Decision tree data structure.
Definition tree.h:66
static void MCMCSampleOneIter(TreeEnsemble &active_forest, ForestTracker &tracker, ForestContainer &forests, LeafModel &leaf_model, ForestDataset &dataset, ColumnVector &residual, TreePrior &tree_prior, std::mt19937 &gen, std::vector< double > &variable_weights, std::vector< int > &sweep_update_indices, double global_variance, bool keep_forest, bool pre_initialized, bool backfitting, int num_threads, LeafSuffStatConstructorArgs &... leaf_suff_stat_args)
Runs one iteration of the MCMC sampler for a tree ensemble model, which consists of two steps for eve...
Definition tree_sampler.h:1133
static void VarSplitRange(ForestTracker &tracker, ForestDataset &dataset, int tree_num, int leaf_split, int feature_split, double &var_min, double &var_max)
Computer the range of available split values for a continuous variable, given the current structure o...
Definition tree_sampler.h:48
static bool NodesNonConstantAfterSplit(ForestDataset &dataset, ForestTracker &tracker, TreeSplit &split, int tree_num, int leaf_split, int feature_split)
Determines whether a proposed split creates two leaf nodes with constant values for every feature (th...
Definition tree_sampler.h:79
static void GFRSampleOneIter(TreeEnsemble &active_forest, ForestTracker &tracker, ForestContainer &forests, LeafModel &leaf_model, ForestDataset &dataset, ColumnVector &residual, TreePrior &tree_prior, std::mt19937 &gen, std::vector< double > &variable_weights, std::vector< int > &sweep_update_indices, double global_variance, std::vector< FeatureType > &feature_types, int cutpoint_grid_size, bool keep_forest, bool pre_initialized, bool backfitting, int num_features_subsample, int num_threads, LeafSuffStatConstructorArgs &... leaf_suff_stat_args)
Definition tree_sampler.h:824
A collection of random number generation utilities.
Definition category_tracker.h:36
double standard_uniform_draw_53bit(std::mt19937 &gen)
Definition distributions.h:19
Definition tree_sampler.h:868