StochTree 0.5.0.9000
Loading...
Searching...
No Matches
container.h
1
6#ifndef STOCHTREE_CONTAINER_H_
7#define STOCHTREE_CONTAINER_H_
8
9#include <stochtree/data.h>
10#include <stochtree/ensemble.h>
11#include <stochtree/log.h>
12#include <nlohmann/json.hpp>
13#include <stochtree/tree.h>
14
15#include <fstream>
16
17namespace StochTree {
18
25 public:
44 ForestContainer(int num_samples, int num_trees, int output_dimension = 1, bool is_leaf_constant = true, bool is_exponentiated = false);
53 forests_[inbound_forest_index]->MergeForest(*forests_[outbound_forest_index]);
54 }
62 forests_[forest_index]->AddValueToLeaves(constant_value);
63 }
71 forests_[forest_index]->MultiplyLeavesByValue(constant_multiple);
72 }
84 void AddSample(TreeEnsemble& forest);
96 void InitializeRoot(std::vector<double>& leaf_vector);
102 void AddSamples(int num_samples);
120 std::vector<double> Predict(ForestDataset& dataset);
134 std::vector<double> PredictRaw(ForestDataset& dataset, bool row_major = true);
135 std::vector<double> PredictRaw(ForestDataset& dataset, int forest_num);
136 std::vector<double> PredictRawSingleTree(ForestDataset& dataset, int forest_num, int tree_num);
137 void PredictInPlace(ForestDataset& dataset, std::vector<double>& output);
138 void PredictRawInPlace(ForestDataset& dataset, std::vector<double>& output, bool row_major = true);
139 void PredictRawInPlace(ForestDataset& dataset, int forest_num, std::vector<double>& output);
140 void PredictRawSingleTreeInPlace(ForestDataset& dataset, int forest_num, int tree_num, std::vector<double>& output);
141 void PredictLeafIndicesInplace(Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>& covariates,
142 Eigen::Map<Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>& output,
143 std::vector<int>& forest_indices, int num_trees, data_size_t n);
144
145 inline TreeEnsemble* GetEnsemble(int i) { return forests_[i].get(); }
146 inline int32_t NumSamples() { return num_samples_; }
147 inline int32_t NumTrees() { return num_trees_; }
148 inline int32_t NumTrees(int ensemble_num) { return forests_[ensemble_num]->NumTrees(); }
149 inline int32_t NumLeaves(int ensemble_num) { return forests_[ensemble_num]->NumLeaves(); }
150 inline int32_t EnsembleTreeMaxDepth(int ensemble_num, int tree_num) { return forests_[ensemble_num]->TreeMaxDepth(tree_num); }
151 inline double EnsembleAverageMaxDepth(int ensemble_num) { return forests_[ensemble_num]->AverageMaxDepth(); }
152 inline double AverageMaxDepth() {
153 double numerator = 0.;
154 double denominator = 0.;
155 for (int i = 0; i < num_samples_; i++) {
156 for (int j = 0; j < num_trees_; j++) {
157 numerator += static_cast<double>(forests_[i]->TreeMaxDepth(j));
158 denominator += 1.;
159 }
160 }
161 return numerator / denominator;
162 }
163 inline int32_t OutputDimension() { return output_dimension_; }
164 inline int32_t OutputDimension(int ensemble_num) { return forests_[ensemble_num]->OutputDimension(); }
165 inline bool IsLeafConstant() { return is_leaf_constant_; }
166 inline bool IsLeafConstant(int ensemble_num) { return forests_[ensemble_num]->IsLeafConstant(); }
167 inline bool IsExponentiated() { return is_exponentiated_; }
168 inline bool IsExponentiated(int ensemble_num) { return forests_[ensemble_num]->IsExponentiated(); }
169 inline bool AllRoots(int ensemble_num) { return forests_[ensemble_num]->AllRoots(); }
170 inline void SetLeafValue(int ensemble_num, double leaf_value) { forests_[ensemble_num]->SetLeafValue(leaf_value); }
171 inline void SetLeafVector(int ensemble_num, std::vector<double>& leaf_vector) { forests_[ensemble_num]->SetLeafVector(leaf_vector); }
172 inline void IncrementSampleCount() { num_samples_++; }
173
174 void SaveToJsonFile(std::string filename) {
175 nlohmann::json model_json = this->to_json();
176 std::ofstream output_file(filename);
177 output_file << model_json << std::endl;
178 }
179
180 void LoadFromJsonFile(std::string filename) {
181 std::ifstream f(filename);
182 nlohmann::json file_tree_json = nlohmann::json::parse(f);
183 this->Reset();
184 this->from_json(file_tree_json);
185 }
186
187 std::string DumpJsonString() {
188 nlohmann::json model_json = this->to_json();
189 return model_json.dump();
190 }
191
192 void LoadFromJsonString(std::string& json_string) {
193 nlohmann::json file_tree_json = nlohmann::json::parse(json_string);
194 this->Reset();
195 this->from_json(file_tree_json);
196 }
197
198 void Reset() {
199 forests_.clear();
200 num_samples_ = 0;
201 num_trees_ = 0;
202 output_dimension_ = 0;
203 is_leaf_constant_ = 0;
204 initialized_ = false;
205 }
206
208 nlohmann::json to_json();
210 void from_json(const nlohmann::json& forest_container_json);
212 void append_from_json(const nlohmann::json& forest_container_json);
213
214 private:
215 std::vector<std::unique_ptr<TreeEnsemble>> forests_;
216 int num_samples_;
217 int num_trees_;
218 int output_dimension_;
219 bool is_exponentiated_{false};
220 bool is_leaf_constant_;
221 bool initialized_{false};
222};
223
229inline void AppendForestContainerSamples(std::unique_ptr<ForestContainer>& dst,
230 const std::unique_ptr<ForestContainer>& src,
231 const char* name) {
232 if (src == nullptr && dst == nullptr) return;
233 if (src == nullptr || dst == nullptr) {
234 Log::Fatal("Cannot merge samples: %s forest present in one chain but not the other", name);
235 }
236 for (int i = 0; i < src->NumSamples(); i++) {
237 dst->AddSample(*src->GetEnsemble(i));
238 }
239}
240} // namespace StochTree
241
242#endif // STOCHTREE_CONTAINER_H_
Container of TreeEnsemble forest objects. This is the primary (in-memory) storage interface for multi...
Definition container.h:24
ForestContainer(int num_samples, int num_trees, int output_dimension=1, bool is_leaf_constant=true, bool is_exponentiated=false)
Construct a new ForestContainer object.
std::vector< double > Predict(ForestDataset &dataset)
Predict from every forest in the container on every observation in the provided dataset....
void MultiplyForest(int forest_index, double constant_multiple)
Multiply every leaf of every tree of a specified forest by a constant value.
Definition container.h:70
void InitializeRoot(std::vector< double > &leaf_vector)
Initialize a "root" forest of multivariate trees as the first element of the container,...
void DeleteSample(int sample_num)
Remove a forest from a container of forest samples and delete the corresponding object,...
void MergeForests(int inbound_forest_index, int outbound_forest_index)
Combine two forests into a single forest by merging their trees.
Definition container.h:52
std::vector< double > PredictRaw(ForestDataset &dataset, bool row_major=true)
Predict from every forest in the container on every observation in the provided dataset....
void append_from_json(const nlohmann::json &forest_container_json)
Append to a forest container from JSON, requires that the ensemble already contains a nonzero number ...
void CopyFromPreviousSample(int new_sample_id, int previous_sample_id)
Copy the forest stored at previous_sample_id to the forest stored at new_sample_id.
void from_json(const nlohmann::json &forest_container_json)
Load from JSON.
void InitializeRoot(double leaf_value)
Initialize a "root" forest of univariate trees as the first element of the container,...
nlohmann::json to_json()
Save to JSON.
void AddSamples(int num_samples)
Pre-allocate space for num_samples additional forests in the container.
ForestContainer(int num_trees, int output_dimension=1, bool is_leaf_constant=true, bool is_exponentiated=false)
Construct a new ForestContainer object.
void AddToForest(int forest_index, double constant_value)
Add a constant value to every leaf of every tree of a specified forest.
Definition container.h:61
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:272
Class storing a "forest," or an ensemble of decision trees.
Definition ensemble.h:31
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:816
A collection of random number generation utilities.
Definition bart.h:15
void AppendForestContainerSamples(std::unique_ptr< ForestContainer > &dst, const std::unique_ptr< ForestContainer > &src, const char *name)
Append every retained forest sample from src onto the end of dst (deep copy). Used by BARTSamples::Me...
Definition container.h:229