Treelite
predict.cc
Go to the documentation of this file.
1 
9 #include <treelite/gtil.h>
10 #include <treelite/tree.h>
11 #include <treelite/data.h>
12 #include <treelite/logging.h>
13 #include <limits>
14 #include <vector>
15 #include <cmath>
16 #include <cstddef>
17 #include "./pred_transform.h"
18 
19 namespace {
20 
21 using PredTransformFuncType = std::size_t (*) (const treelite::Model&, const float*, float*);
22 
23 template <typename T>
24 inline int NextNode(float fvalue, T threshold, treelite::Operator op,
25  int left_child, int right_child, int default_child) {
26  if (std::isnan(fvalue)) {
27  return default_child;
28  }
29  switch (op) {
30  case treelite::Operator::kEQ:
31  return (fvalue == threshold) ? left_child : right_child;
32  case treelite::Operator::kLT:
33  return (fvalue < threshold) ? left_child : right_child;
34  case treelite::Operator::kLE:
35  return (fvalue <= threshold) ? left_child : right_child;
36  case treelite::Operator::kGT:
37  return (fvalue > threshold) ? left_child : right_child;
38  case treelite::Operator::kGE:
39  return (fvalue >= threshold) ? left_child : right_child;
40  default:
41  TREELITE_CHECK(false) << "Unrecognized comparison operator " << static_cast<int>(op);
42  return -1;
43  }
44 }
45 
46 inline int NextNodeCategorical(float fvalue, const std::vector<uint32_t>& matching_categories,
47  bool categories_list_right_child, int left_child, int right_child,
48  int default_child) {
49  if (std::isnan(fvalue)) {
50  return default_child;
51  }
52  const auto category_value = static_cast<uint32_t>(fvalue);
53  const bool is_matching_category = (
54  std::find(matching_categories.begin(), matching_categories.end(), category_value)
55  != matching_categories.end());
56  if (categories_list_right_child) {
57  return is_matching_category ? right_child : left_child;
58  } else {
59  return is_matching_category ? left_child : right_child;
60  }
61 }
62 
63 template <typename ThresholdType, typename LeafOutputType, typename DMatrixType,
64  typename OutputFunc>
65 inline std::size_t PredictImplInner(const treelite::ModelImpl<ThresholdType, LeafOutputType>& model,
66  const DMatrixType* input, float* output, bool pred_transform,
67  OutputFunc output_func) {
69  const size_t num_row = input->GetNumRow();
70  const size_t num_col = input->GetNumCol();
71  std::vector<ThresholdType> row(num_col);
72  const treelite::TaskParam task_param = model.task_param;
73  std::vector<float> sum(task_param.num_class);
74 
75  // TODO(phcho): Use parallelism
76  std::size_t output_offset = 0;
77  for (size_t row_id = 0; row_id < num_row; ++row_id) {
78  input->FillRow(row_id, row.data());
79  std::fill(sum.begin(), sum.end(), 0.0f);
80  const std::size_t num_tree = model.trees.size();
81  for (std::size_t tree_id = 0; tree_id < num_tree; ++tree_id) {
82  const TreeType& tree = model.trees[tree_id];
83  int node_id = 0;
84  while (!tree.IsLeaf(node_id)) {
85  treelite::SplitFeatureType split_type = tree.SplitType(node_id);
86  if (split_type == treelite::SplitFeatureType::kNumerical) {
87  node_id = NextNode(row[tree.SplitIndex(node_id)], tree.Threshold(node_id),
88  tree.ComparisonOp(node_id), tree.LeftChild(node_id),
89  tree.RightChild(node_id), tree.DefaultChild(node_id));
90  } else if (split_type == treelite::SplitFeatureType::kCategorical) {
91  node_id = NextNodeCategorical(row[tree.SplitIndex(node_id)],
92  tree.MatchingCategories(node_id),
93  tree.CategoriesListRightChild(node_id),
94  tree.LeftChild(node_id), tree.RightChild(node_id),
95  tree.DefaultChild(node_id));
96  } else {
97  TREELITE_CHECK(false) << "Unrecognized split type: " << static_cast<int>(split_type);
98  }
99  }
100  output_func(tree, tree_id, node_id, sum.data());
101  }
102  if (model.average_tree_output) {
103  float average_factor;
104  if (model.task_type == treelite::TaskType::kMultiClfGrovePerClass) {
105  TREELITE_CHECK(task_param.grove_per_class);
106  TREELITE_CHECK_EQ(task_param.leaf_vector_size, 1);
107  TREELITE_CHECK_GT(task_param.num_class, 1);
108  TREELITE_CHECK_EQ(num_tree % task_param.num_class, 0)
109  << "Expected the number of trees to be divisible by the number of classes";
110  int num_boosting_round = num_tree / static_cast<int>(task_param.num_class);
111  average_factor = static_cast<float>(num_boosting_round);
112  } else {
113  TREELITE_CHECK(model.task_type == treelite::TaskType::kBinaryClfRegr
114  || model.task_type == treelite::TaskType::kMultiClfProbDistLeaf);
115  TREELITE_CHECK(task_param.num_class == task_param.leaf_vector_size);
116  TREELITE_CHECK(!task_param.grove_per_class);
117  average_factor = static_cast<float>(num_tree);
118  }
119  for (unsigned int i = 0; i < task_param.num_class; ++i) {
120  sum[i] /= average_factor;
121  }
122  }
123  for (unsigned int i = 0; i < task_param.num_class; ++i) {
124  sum[i] += model.param.global_bias;
125  }
126  if (pred_transform) {
127  PredTransformFuncType pred_transform_func
128  = treelite::gtil::LookupPredTransform(model.param.pred_transform);
129  output_offset += pred_transform_func(model, sum.data(), &output[output_offset]);
130  } else {
131  for (unsigned int i = 0; i < task_param.num_class; ++i) {
132  output[output_offset + i] = sum[i];
133  }
134  output_offset += task_param.num_class;
135  }
136  input->ClearRow(row_id, row.data());
137  }
138  return output_offset;
139 }
140 
141 template <typename ThresholdType, typename LeafOutputType, typename DMatrixType>
142 inline std::size_t PredictImpl(const treelite::ModelImpl<ThresholdType, LeafOutputType>& model,
143  const DMatrixType* input, float* output,
144  bool pred_transform) {
146  const treelite::TaskParam task_param = model.task_param;
147  if (task_param.num_class > 1) {
148  if (task_param.leaf_vector_size > 1) {
149  // multi-class classification with random forest
150  auto output_logic = [task_param](
151  const TreeType& tree, int, int node_id, float* sum) {
152  auto leaf_vector = tree.LeafVector(node_id);
153  for (unsigned int i = 0; i < task_param.leaf_vector_size; ++i) {
154  sum[i] += leaf_vector[i];
155  }
156  };
157  return PredictImplInner(model, input, output, pred_transform, output_logic);
158  } else {
159  // multi-class classification with gradient boosted trees
160  auto output_logic = [task_param](
161  const TreeType& tree, int tree_id, int node_id, float* sum) {
162  sum[tree_id % task_param.num_class] += tree.LeafValue(node_id);
163  };
164  return PredictImplInner(model, input, output, pred_transform, output_logic);
165  }
166  } else {
167  auto output_logic = [task_param](
168  const TreeType& tree, int tree_id, int node_id, float* sum) {
169  sum[0] += tree.LeafValue(node_id);
170  };
171  return PredictImplInner(model, input, output, pred_transform, output_logic);
172  }
173 }
174 
175 } // anonymous namespace
176 
177 namespace treelite {
178 namespace gtil {
179 
180 std::size_t Predict(const Model* model, const DMatrix* input, float* output, bool pred_transform) {
181  // Check type of DMatrix
182  const auto* d1 = dynamic_cast<const DenseDMatrixImpl<float>*>(input);
183  const auto* d2 = dynamic_cast<const CSRDMatrixImpl<float>*>(input);
184  if (d1) {
185  return model->Dispatch([d1, output, pred_transform](const auto& model) {
186  return PredictImpl(model, d1, output, pred_transform);
187  });
188  } else if (d2) {
189  return model->Dispatch([d2, output, pred_transform](const auto& model) {
190  return PredictImpl(model, d2, output, pred_transform);
191  });
192  } else {
193  TREELITE_LOG(FATAL) << "DMatrix with float64 data is not supported";
194  return 0;
195  }
196 }
197 
198 std::size_t Predict(const Model* model, const float* input, std::size_t num_row, float* output,
199  bool pred_transform) {
200  std::unique_ptr<DenseDMatrixImpl<float>> dmat =
201  std::make_unique<DenseDMatrixImpl<float>>(
202  std::vector<float>(input, input + num_row * model->num_feature),
203  std::numeric_limits<float>::quiet_NaN(),
204  num_row,
205  model->num_feature);
206  return Predict(model, dmat.get(), output, pred_transform);
207 }
208 
209 std::size_t GetPredictOutputSize(const Model* model, std::size_t num_row) {
210  return model->task_param.num_class * num_row;
211 }
212 
213 std::size_t GetPredictOutputSize(const Model* model, const DMatrix* input) {
214  return GetPredictOutputSize(model, input->GetNumRow());
215 }
216 
217 } // namespace gtil
218 } // namespace treelite
ModelParam param
extra parameters
Definition: tree.h:675
SplitFeatureType
feature split type
Definition: base.h:22
bool grove_per_class
Whether we designate a subset of the trees to compute the prediction for each class.
Definition: tree.h:168
Group of parameters that are dependent on the choice of the task type.
Definition: tree.h:157
bool average_tree_output
whether to average tree outputs
Definition: tree.h:671
Input data structure of Treelite.
model structure for tree ensemble
unsigned int leaf_vector_size
Dimension of the output from each leaf node.
Definition: tree.h:183
in-memory representation of a decision tree
Definition: tree.h:190
logging facility for Treelite
unsigned int num_class
The number of classes in the target label.
Definition: tree.h:176
TaskType task_type
Task type.
Definition: tree.h:669
std::vector< Tree< ThresholdType, LeafOutputType > > trees
member trees
Definition: tree.h:699
General Tree Inference Library (GTIL), providing a reference implementation for predicting with decis...
TaskParam task_param
Group of parameters that are specific to the particular task type.
Definition: tree.h:673
thin wrapper for tree ensemble model
Definition: tree.h:626
Operator
comparison operators
Definition: base.h:26