5#ifndef STOCHTREE_LEAF_MODEL_H_
6#define STOCHTREE_LEAF_MODEL_H_
9#include <stochtree/cutpoint_candidates.h>
10#include <stochtree/data.h>
11#include <stochtree/gamma_sampler.h>
12#include <stochtree/ig_sampler.h>
13#include <stochtree/log.h>
14#include <stochtree/meta.h>
15#include <stochtree/normal_sampler.h>
16#include <stochtree/partition_tracker.h>
17#include <stochtree/prior.h>
18#include <stochtree/tree.h>
352 kConstantLeafGaussian,
353 kUnivariateRegressionLeafGaussian,
354 kMultivariateRegressionLeafGaussian,
369 void IncrementSuffStat(
ForestDataset& dataset, Eigen::VectorXd& outcome,
ForestTracker& tracker, data_size_t row_idx,
int tree_idx) {
376 sum_yw += outcome(row_idx, 0);
379 void ResetSuffStat() {
386 sum_w = lhs.sum_w + rhs.sum_w;
387 sum_yw = lhs.sum_yw + rhs.sum_yw;
391 sum_w = lhs.sum_w - rhs.sum_w;
392 sum_yw = lhs.sum_yw - rhs.sum_yw;
394 bool SampleGreaterThan(data_size_t threshold) {
395 return n > threshold;
397 bool SampleGreaterThanEqual(data_size_t threshold) {
398 return n >= threshold;
400 data_size_t SampleSize() {
452 void SetScale(
double tau) {tau_ = tau;}
453 inline bool RequiresBasis() {
return false;}
456 UnivariateNormalSampler normal_sampler_;
470 void IncrementSuffStat(
ForestDataset& dataset, Eigen::VectorXd& outcome,
ForestTracker& tracker, data_size_t row_idx,
int tree_idx) {
477 sum_yxw += outcome(row_idx, 0)*dataset.
BasisValue(row_idx, 0);
480 void ResetSuffStat() {
487 sum_xxw = lhs.sum_xxw + rhs.sum_xxw;
488 sum_yxw = lhs.sum_yxw + rhs.sum_yxw;
492 sum_xxw = lhs.sum_xxw - rhs.sum_xxw;
493 sum_yxw = lhs.sum_yxw - rhs.sum_yxw;
495 bool SampleGreaterThan(data_size_t threshold) {
496 return n > threshold;
498 bool SampleGreaterThanEqual(data_size_t threshold) {
499 return n >= threshold;
501 data_size_t SampleSize() {
553 void SetScale(
double tau) {tau_ = tau;}
554 inline bool RequiresBasis() {
return true;}
557 UnivariateNormalSampler normal_sampler_;
565 Eigen::MatrixXd XtWX;
566 Eigen::MatrixXd ytWX;
569 XtWX = Eigen::MatrixXd::Zero(basis_dim, basis_dim);
570 ytWX = Eigen::MatrixXd::Zero(1, basis_dim);
573 void IncrementSuffStat(
ForestDataset& dataset, Eigen::VectorXd& outcome,
ForestTracker& tracker, data_size_t row_idx,
int tree_idx) {
579 XtWX += dataset.
GetBasis()(row_idx, Eigen::all).transpose()*dataset.
GetBasis()(row_idx, Eigen::all);
580 ytWX += (outcome(row_idx, 0)*(dataset.
GetBasis()(row_idx, Eigen::all)));
583 void ResetSuffStat() {
585 XtWX = Eigen::MatrixXd::Zero(p, p);
586 ytWX = Eigen::MatrixXd::Zero(1, p);
590 XtWX = lhs.XtWX + rhs.XtWX;
591 ytWX = lhs.ytWX + rhs.ytWX;
595 XtWX = lhs.XtWX - rhs.XtWX;
596 ytWX = lhs.ytWX - rhs.ytWX;
598 bool SampleGreaterThan(data_size_t threshold) {
599 return n > threshold;
601 bool SampleGreaterThanEqual(data_size_t threshold) {
602 return n >= threshold;
604 data_size_t SampleSize() {
661 void SetScale(Eigen::MatrixXd& Sigma_0) {Sigma_0_ = Sigma_0;}
662 inline bool RequiresBasis() {
return true;}
664 Eigen::MatrixXd Sigma_0_;
665 MultivariateNormalSampler multivariate_normal_sampler_;
672 double weighted_sum_ei;
675 weighted_sum_ei = 0.0;
677 void IncrementSuffStat(
ForestDataset& dataset, Eigen::VectorXd& outcome,
ForestTracker& tracker, data_size_t row_idx,
int tree_idx) {
679 weighted_sum_ei += std::exp(std::log(outcome(row_idx)*outcome(row_idx)) - tracker.GetSamplePrediction(row_idx) + tracker.GetTreeSamplePrediction(row_idx, tree_idx));
681 void ResetSuffStat() {
683 weighted_sum_ei = 0.0;
687 weighted_sum_ei = lhs.weighted_sum_ei + rhs.weighted_sum_ei;
691 weighted_sum_ei = lhs.weighted_sum_ei - rhs.weighted_sum_ei;
693 bool SampleGreaterThan(data_size_t threshold) {
694 return n > threshold;
696 bool SampleGreaterThanEqual(data_size_t threshold) {
697 return n >= threshold;
699 data_size_t SampleSize() {
752 void SetPriorShape(
double a) {a_ = a;}
753 void SetPriorRate(
double b) {b_ = b;}
754 inline bool RequiresBasis() {
return false;}
758 GammaSampler gamma_sampler_;
761using SuffStatVariant = std::variant<GaussianConstantSuffStat,
762 GaussianUnivariateRegressionSuffStat,
763 GaussianMultivariateRegressionSuffStat,
764 LogLinearVarianceSuffStat>;
766using LeafModelVariant = std::variant<GaussianConstantLeafModel,
767 GaussianUnivariateRegressionLeafModel,
768 GaussianMultivariateRegressionLeafModel,
769 LogLinearVarianceLeafModel>;
771template<
typename SuffStatType,
typename... SuffStatConstructorArgs>
772static inline SuffStatVariant createSuffStat(SuffStatConstructorArgs... leaf_suff_stat_args) {
773 return SuffStatType(leaf_suff_stat_args...);
776template<
typename LeafModelType,
typename... LeafModelConstructorArgs>
777static inline LeafModelVariant createLeafModel(LeafModelConstructorArgs... leaf_model_args) {
778 return LeafModelType(leaf_model_args...);
781static inline SuffStatVariant suffStatFactory(
ModelType model_type,
int basis_dim = 0) {
782 if (model_type == kConstantLeafGaussian) {
783 return createSuffStat<GaussianConstantSuffStat>();
784 }
else if (model_type == kUnivariateRegressionLeafGaussian) {
785 return createSuffStat<GaussianUnivariateRegressionSuffStat>();
786 }
else if (model_type == kMultivariateRegressionLeafGaussian) {
787 return createSuffStat<GaussianMultivariateRegressionSuffStat, int>(basis_dim);
789 return createSuffStat<LogLinearVarianceSuffStat>();
793static inline LeafModelVariant leafModelFactory(
ModelType model_type,
double tau, Eigen::MatrixXd& Sigma0,
double a,
double b) {
794 if (model_type == kConstantLeafGaussian) {
795 return createLeafModel<GaussianConstantLeafModel, double>(tau);
796 }
else if (model_type == kUnivariateRegressionLeafGaussian) {
797 return createLeafModel<GaussianUnivariateRegressionLeafModel, double>(tau);
798 }
else if (model_type == kMultivariateRegressionLeafGaussian) {
799 return createLeafModel<GaussianMultivariateRegressionLeafModel, Eigen::MatrixXd>(Sigma0);
800 }
else if (model_type == kLogLinearVariance) {
801 return createLeafModel<LogLinearVarianceLeafModel, double, double>(a, b);
803 Log::Fatal(
"Incompatible model type provided to leaf model factory");
807template<
typename SuffStatType>
808static inline void AccumulateSuffStatProposed(SuffStatType& node_suff_stat, SuffStatType& left_suff_stat, SuffStatType& right_suff_stat, ForestDataset& dataset, ForestTracker& tracker,
809 ColumnVector& residual,
double global_variance, TreeSplit& split,
int tree_num,
int leaf_num,
int split_feature) {
811 auto node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, leaf_num);
812 auto node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, leaf_num);
815 for (
auto i = node_begin_iter; i != node_end_iter; i++) {
817 double feature_value = dataset.CovariateValue(idx, split_feature);
818 node_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
819 if (split.SplitTrue(feature_value)) {
820 left_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
822 right_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
827template<
typename SuffStatType>
828static inline void AccumulateSuffStatExisting(SuffStatType& node_suff_stat, SuffStatType& left_suff_stat, SuffStatType& right_suff_stat, ForestDataset& dataset, ForestTracker& tracker,
829 ColumnVector& residual,
double global_variance,
int tree_num,
int split_node_id,
int left_node_id,
int right_node_id) {
831 auto left_node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, left_node_id);
832 auto left_node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, left_node_id);
833 auto right_node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, right_node_id);
834 auto right_node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, right_node_id);
837 for (
auto i = left_node_begin_iter; i != left_node_end_iter; i++) {
839 left_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
840 node_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
844 for (
auto i = right_node_begin_iter; i != right_node_end_iter; i++) {
846 right_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
847 node_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
851template<
typename SuffStatType,
bool sorted>
852static inline void AccumulateSingleNodeSuffStat(SuffStatType& node_suff_stat, ForestDataset& dataset, ForestTracker& tracker, ColumnVector& residual,
int tree_num,
int node_id) {
854 std::vector<data_size_t>::iterator node_begin_iter;
855 std::vector<data_size_t>::iterator node_end_iter;
858 node_begin_iter = tracker.SortedNodeBeginIterator(node_id, 0);
859 node_end_iter = tracker.SortedNodeEndIterator(node_id, 0);
861 node_begin_iter = tracker.UnsortedNodeBeginIterator(tree_num, node_id);
862 node_end_iter = tracker.UnsortedNodeEndIterator(tree_num, node_id);
866 for (
auto i = node_begin_iter; i != node_end_iter; i++) {
868 node_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
872template<
typename SuffStatType>
873static inline void AccumulateCutpointBinSuffStat(SuffStatType& left_suff_stat, ForestTracker& tracker, CutpointGridContainer& cutpoint_grid_container,
874 ForestDataset& dataset, ColumnVector& residual,
double global_variance,
int tree_num,
int node_id,
875 int feature_num,
int cutpoint_num) {
877 auto node_begin_iter = tracker.SortedNodeBeginIterator(node_id, feature_num);
878 auto node_end_iter = tracker.SortedNodeEndIterator(node_id, feature_num);
881 data_size_t node_begin = tracker.SortedNodeBegin(node_id, feature_num);
884 data_size_t current_bin_begin = cutpoint_grid_container.BinStartIndex(cutpoint_num, feature_num);
885 data_size_t current_bin_size = cutpoint_grid_container.BinLength(cutpoint_num, feature_num);
886 data_size_t next_bin_begin = cutpoint_grid_container.BinStartIndex(cutpoint_num + 1, feature_num);
890 auto cutpoint_begin_iter = node_begin_iter + (current_bin_begin - node_begin);
891 auto cutpoint_end_iter = node_begin_iter + (next_bin_begin - node_begin);
894 for (
auto i = cutpoint_begin_iter; i != cutpoint_end_iter; i++) {
896 left_suff_stat.IncrementSuffStat(dataset, residual.GetData(), tracker, idx, tree_num);
Internal wrapper around Eigen::VectorXd interface for univariate floating point data....
Definition data.h:194
API for loading and accessing data used to sample tree ensembles The covariates / bases / weights use...
Definition data.h:272
double BasisValue(data_size_t row, int col)
Returns a dataset's basis value stored at (row, col)
Definition data.h:372
Eigen::MatrixXd & GetBasis()
Return a reference to the raw Eigen::MatrixXd storing the basis data.
Definition data.h:390
double VarWeightValue(data_size_t row)
Returns a dataset's variance weight stored at element row
Definition data.h:378
bool HasVarWeights()
Whether or not a ForestDataset has (yet) loaded variance weights.
Definition data.h:352
"Superclass" wrapper around tracking data structures for forest sampling algorithms
Definition partition_tracker.h:50
Definition gamma_sampler.h:9
Marginal likelihood and posterior computation for gaussian homoskedastic constant leaf outcome model.
Definition leaf_model.h:406
double SplitLogMarginalLikelihood(GaussianConstantSuffStat &left_stat, GaussianConstantSuffStat &right_stat, double global_variance)
Log marginal likelihood for a proposed split, evaluated only for observations that fall into the node...
double PosteriorParameterVariance(GaussianConstantSuffStat &suff_stat, double global_variance)
Leaf node posterior variance.
void SampleLeafParameters(ForestDataset &dataset, ForestTracker &tracker, ColumnVector &residual, Tree *tree, int tree_num, double global_variance, std::mt19937 &gen)
Draw new parameters for every leaf node in tree, using a Gibbs update that conditions on the data,...
double NoSplitLogMarginalLikelihood(GaussianConstantSuffStat &suff_stat, double global_variance)
Log marginal likelihood of a node, evaluated only for observations that fall into the node being spli...
double PosteriorParameterMean(GaussianConstantSuffStat &suff_stat, double global_variance)
Leaf node posterior mean.
Sufficient statistic and associated operations for gaussian homoskedastic constant leaf outcome model...
Definition leaf_model.h:359
Marginal likelihood and posterior computation for gaussian homoskedastic constant leaf outcome model.
Definition leaf_model.h:610
void SampleLeafParameters(ForestDataset &dataset, ForestTracker &tracker, ColumnVector &residual, Tree *tree, int tree_num, double global_variance, std::mt19937 &gen)
Draw new parameters for every leaf node in tree, using a Gibbs update that conditions on the data,...
Eigen::MatrixXd PosteriorParameterVariance(GaussianMultivariateRegressionSuffStat &suff_stat, double global_variance)
Leaf node posterior variance.
double SplitLogMarginalLikelihood(GaussianMultivariateRegressionSuffStat &left_stat, GaussianMultivariateRegressionSuffStat &right_stat, double global_variance)
Log marginal likelihood for a proposed split, evaluated only for observations that fall into the node...
GaussianMultivariateRegressionLeafModel(Eigen::MatrixXd &Sigma_0)
Construct a new GaussianMultivariateRegressionLeafModel object.
Definition leaf_model.h:617
Eigen::VectorXd PosteriorParameterMean(GaussianMultivariateRegressionSuffStat &suff_stat, double global_variance)
Leaf node posterior mean.
double NoSplitLogMarginalLikelihood(GaussianMultivariateRegressionSuffStat &suff_stat, double global_variance)
Log marginal likelihood of a node, evaluated only for observations that fall into the node being spli...
Sufficient statistic and associated operations for gaussian homoskedastic constant leaf outcome model...
Definition leaf_model.h:561
Marginal likelihood and posterior computation for gaussian homoskedastic constant leaf outcome model.
Definition leaf_model.h:507
double SplitLogMarginalLikelihood(GaussianUnivariateRegressionSuffStat &left_stat, GaussianUnivariateRegressionSuffStat &right_stat, double global_variance)
Log marginal likelihood for a proposed split, evaluated only for observations that fall into the node...
void SampleLeafParameters(ForestDataset &dataset, ForestTracker &tracker, ColumnVector &residual, Tree *tree, int tree_num, double global_variance, std::mt19937 &gen)
Draw new parameters for every leaf node in tree, using a Gibbs update that conditions on the data,...
double PosteriorParameterVariance(GaussianUnivariateRegressionSuffStat &suff_stat, double global_variance)
Leaf node posterior variance.
double PosteriorParameterMean(GaussianUnivariateRegressionSuffStat &suff_stat, double global_variance)
Leaf node posterior mean.
double NoSplitLogMarginalLikelihood(GaussianUnivariateRegressionSuffStat &suff_stat, double global_variance)
Log marginal likelihood of a node, evaluated only for observations that fall into the node being spli...
Sufficient statistic and associated operations for gaussian homoskedastic constant leaf outcome model...
Definition leaf_model.h:460
Marginal likelihood and posterior computation for heteroskedastic log-linear variance model.
Definition leaf_model.h:705
double NoSplitLogMarginalLikelihood(LogLinearVarianceSuffStat &suff_stat, double global_variance)
Log marginal likelihood of a node, evaluated only for observations that fall into the node being spli...
double PosteriorParameterShape(LogLinearVarianceSuffStat &suff_stat, double global_variance)
Leaf node posterior shape parameter.
void SampleLeafParameters(ForestDataset &dataset, ForestTracker &tracker, ColumnVector &residual, Tree *tree, int tree_num, double global_variance, std::mt19937 &gen)
Draw new parameters for every leaf node in tree, using a Gibbs update that conditions on the data,...
double SplitLogMarginalLikelihood(LogLinearVarianceSuffStat &left_stat, LogLinearVarianceSuffStat &right_stat, double global_variance)
Log marginal likelihood for a proposed split, evaluated only for observations that fall into the node...
double PosteriorParameterScale(LogLinearVarianceSuffStat &suff_stat, double global_variance)
Leaf node posterior scale parameter.
Sufficient statistic and associated operations for heteroskedastic log-linear variance model.
Definition leaf_model.h:669
Definition normal_sampler.h:24
Class storing a "forest," or an ensemble of decision trees.
Definition ensemble.h:37
Decision tree data structure.
Definition tree.h:69
Definition normal_sampler.h:12
ModelType
Leaf models for the forest sampler:
Definition leaf_model.h:351
Definition category_tracker.h:40