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