tree.cpp 21.2 KB
Newer Older
Guolin Ke's avatar
Guolin Ke committed
1
2
3
4
5
6
7
8
9
10
11
12
#include <LightGBM/tree.h>

#include <LightGBM/utils/threading.h>
#include <LightGBM/utils/common.h>

#include <LightGBM/dataset.h>

#include <sstream>
#include <unordered_map>
#include <functional>
#include <vector>
#include <string>
Guolin Ke's avatar
Guolin Ke committed
13
#include <memory>
14
#include <iomanip>
Guolin Ke's avatar
Guolin Ke committed
15
16
17

namespace LightGBM {

18
19
20
21
22
std::vector<bool(*)(uint32_t, uint32_t)> Tree::inner_decision_funs =
{ Tree::NumericalDecision<uint32_t>, Tree::CategoricalDecision<uint32_t> };
std::vector<bool(*)(double, double)> Tree::decision_funs =
{ Tree::NumericalDecision<double>, Tree::CategoricalDecision<double> };

Guolin Ke's avatar
Guolin Ke committed
23
24
25
Tree::Tree(int max_leaves)
  :max_leaves_(max_leaves) {

Guolin Ke's avatar
Guolin Ke committed
26
  num_leaves_ = 0;
Guolin Ke's avatar
Guolin Ke committed
27
28
29
30
31
32
  left_child_.resize(max_leaves_ - 1);
  right_child_.resize(max_leaves_ - 1);
  split_feature_inner_.resize(max_leaves_ - 1);
  split_feature_.resize(max_leaves_ - 1);
  threshold_in_bin_.resize(max_leaves_ - 1);
  threshold_.resize(max_leaves_ - 1);
Guolin Ke's avatar
Guolin Ke committed
33
  decision_type_.resize(max_leaves_ - 1, 0);
Guolin Ke's avatar
Guolin Ke committed
34
35
36
37
38
39
40
  split_gain_.resize(max_leaves_ - 1);
  leaf_parent_.resize(max_leaves_);
  leaf_value_.resize(max_leaves_);
  leaf_count_.resize(max_leaves_);
  internal_value_.resize(max_leaves_ - 1);
  internal_count_.resize(max_leaves_ - 1);
  leaf_depth_.resize(max_leaves_);
Guolin Ke's avatar
Guolin Ke committed
41
42
  // root is in the depth 0
  leaf_depth_[0] = 0;
Guolin Ke's avatar
Guolin Ke committed
43
44
  num_leaves_ = 1;
  leaf_parent_[0] = -1;
Guolin Ke's avatar
Guolin Ke committed
45
  shrinkage_ = 1.0f;
46
  has_categorical_ = false;
Guolin Ke's avatar
Guolin Ke committed
47
}
Guolin Ke's avatar
Guolin Ke committed
48

Guolin Ke's avatar
Guolin Ke committed
49
Tree::~Tree() {
Guolin Ke's avatar
Guolin Ke committed
50

Guolin Ke's avatar
Guolin Ke committed
51
52
}

Guolin Ke's avatar
Guolin Ke committed
53
54
int Tree::Split(int leaf, int feature, BinType bin_type, uint32_t threshold_bin, int real_feature, double threshold_double, 
                double left_value, double right_value, data_size_t left_cnt, data_size_t right_cnt, double gain,
Guolin Ke's avatar
Guolin Ke committed
55
                MissingType missing_type, bool default_left) {
Guolin Ke's avatar
Guolin Ke committed
56
57
58
59
60
61
62
63
64
65
66
67
  int new_node_idx = num_leaves_ - 1;
  // update parent info
  int parent = leaf_parent_[leaf];
  if (parent >= 0) {
    // if cur node is left child
    if (left_child_[parent] == ~leaf) {
      left_child_[parent] = new_node_idx;
    } else {
      right_child_[parent] = new_node_idx;
    }
  }
  // add new node
Guolin Ke's avatar
Guolin Ke committed
68
  split_feature_inner_[new_node_idx] = feature;
Guolin Ke's avatar
Guolin Ke committed
69
  split_feature_[new_node_idx] = real_feature;
Guolin Ke's avatar
Guolin Ke committed
70

Guolin Ke's avatar
Guolin Ke committed
71
  decision_type_[new_node_idx] = 0;
72
  if (bin_type == BinType::NumericalBin) {
Guolin Ke's avatar
Guolin Ke committed
73
    SetDecisionType(&decision_type_[new_node_idx], false, kCategoricalMask);
74
75
  } else {
    has_categorical_ = true;
Guolin Ke's avatar
Guolin Ke committed
76
77
78
79
80
81
82
83
84
    SetDecisionType(&decision_type_[new_node_idx], true, kCategoricalMask);
  }
  SetDecisionType(&decision_type_[new_node_idx], default_left, kDefaultLeftMask);
  if (missing_type == MissingType::None) {
    SetMissingType(&decision_type_[new_node_idx], 0);
  } else if (missing_type == MissingType::Zero) {
    SetMissingType(&decision_type_[new_node_idx], 1);
  } else if (missing_type == MissingType::NaN) {
    SetMissingType(&decision_type_[new_node_idx], 2);
85
  }
Guolin Ke's avatar
Guolin Ke committed
86

Guolin Ke's avatar
Guolin Ke committed
87
  threshold_in_bin_[new_node_idx] = threshold_bin;
88
  threshold_[new_node_idx] = Common::AvoidInf(threshold_double);
Guolin Ke's avatar
Guolin Ke committed
89
  split_gain_[new_node_idx] = Common::AvoidInf(gain);
Guolin Ke's avatar
Guolin Ke committed
90
91
92
93
94
95
  // add two new leaves
  left_child_[new_node_idx] = ~leaf;
  right_child_[new_node_idx] = ~num_leaves_;
  // update new leaves
  leaf_parent_[leaf] = new_node_idx;
  leaf_parent_[num_leaves_] = new_node_idx;
96
97
  // save current leaf value to internal node before change
  internal_value_[new_node_idx] = leaf_value_[leaf];
Guolin Ke's avatar
Guolin Ke committed
98
  internal_count_[new_node_idx] = left_cnt + right_cnt;
Guolin Ke's avatar
Guolin Ke committed
99
  leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
Guolin Ke's avatar
Guolin Ke committed
100
  leaf_count_[leaf] = left_cnt;
Guolin Ke's avatar
Guolin Ke committed
101
  leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
Guolin Ke's avatar
Guolin Ke committed
102
  leaf_count_[num_leaves_] = right_cnt;
Guolin Ke's avatar
Guolin Ke committed
103
104
105
  // update leaf depth
  leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
  leaf_depth_[leaf]++;
Guolin Ke's avatar
Guolin Ke committed
106
107
108
109
110

  ++num_leaves_;
  return num_leaves_ - 1;
}

111
void Tree::AddPredictionToScore(const Dataset* data, data_size_t num_data, double* score) const {
Guolin Ke's avatar
Guolin Ke committed
112
  if (num_leaves_ <= 1) { return; }
Guolin Ke's avatar
Guolin Ke committed
113
114
115
116
117
118
119
120
  std::vector<uint32_t> default_bins(num_leaves_ - 1);
  std::vector<uint32_t> max_bins(num_leaves_ - 1);
  for (int i = 0; i < num_leaves_ - 1; ++i) {
    const int fidx = split_feature_inner_[i];
    auto bin_mapper = data->FeatureBinMapper(fidx);
    default_bins[i] = bin_mapper->GetDefaultBin();
    max_bins[i] = bin_mapper->num_bin() - 1;
  }
121
122
123
  if (has_categorical_) {
    if (data->num_features() > num_leaves_ - 1) {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
124
        [this, &data, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
125
126
        std::vector<std::unique_ptr<BinIterator>> iter(num_leaves_ - 1);
        for (int i = 0; i < num_leaves_ - 1; ++i) {
Guolin Ke's avatar
Guolin Ke committed
127
          const int fidx = split_feature_inner_[i];
128
129
130
131
132
133
          iter[i].reset(data->FeatureIterator(fidx));
          iter[i]->Reset(start);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
134
135
            uint32_t fval = ConvertMissingValue(iter[node]->Get(i), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
            if (inner_decision_funs[GetDecisionType(decision_type_[node], kCategoricalMask)](
Guolin Ke's avatar
Guolin Ke committed
136
              fval,
137
138
139
140
141
142
143
144
145
146
147
              threshold_in_bin_[node])) {
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[i] += static_cast<double>(leaf_value_[~node]);
        }
      });
    } else {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
148
        [this, &data, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
149
150
151
152
153
154
155
156
        std::vector<std::unique_ptr<BinIterator>> iter(data->num_features());
        for (int i = 0; i < data->num_features(); ++i) {
          iter[i].reset(data->FeatureIterator(i));
          iter[i]->Reset(start);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
157
158
            uint32_t fval = ConvertMissingValue(iter[split_feature_inner_[node]]->Get(i), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
            if (inner_decision_funs[GetDecisionType(decision_type_[node], kCategoricalMask)](
Guolin Ke's avatar
Guolin Ke committed
159
              fval,
160
161
162
163
164
165
166
167
168
169
              threshold_in_bin_[node])) {
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[i] += static_cast<double>(leaf_value_[~node]);
        }
      });
    }
Guolin Ke's avatar
Guolin Ke committed
170
  } else {
171
172
    if (data->num_features() > num_leaves_ - 1) {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
173
        [this, &data, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
174
175
        std::vector<std::unique_ptr<BinIterator>> iter(num_leaves_ - 1);
        for (int i = 0; i < num_leaves_ - 1; ++i) {
Guolin Ke's avatar
Guolin Ke committed
176
          const int fidx = split_feature_inner_[i];
177
178
179
180
181
182
          iter[i].reset(data->FeatureIterator(fidx));
          iter[i]->Reset(start);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
183
            uint32_t fval = ConvertMissingValue(iter[node]->Get(i), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
Guolin Ke's avatar
Guolin Ke committed
184
            if (fval <= threshold_in_bin_[node]) {
185
186
187
188
189
190
191
192
193
194
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[i] += static_cast<double>(leaf_value_[~node]);
        }
      });
    } else {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
195
        [this, &data, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
196
197
198
199
200
201
202
203
        std::vector<std::unique_ptr<BinIterator>> iter(data->num_features());
        for (int i = 0; i < data->num_features(); ++i) {
          iter[i].reset(data->FeatureIterator(i));
          iter[i]->Reset(start);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
204
            uint32_t fval = ConvertMissingValue(iter[split_feature_inner_[node]]->Get(i), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
Guolin Ke's avatar
Guolin Ke committed
205
            if (fval <= threshold_in_bin_[node]) {
206
207
208
209
210
211
212
213
214
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[i] += static_cast<double>(leaf_value_[~node]);
        }
      });
    }
Guolin Ke's avatar
Guolin Ke committed
215
  }
Guolin Ke's avatar
Guolin Ke committed
216
217
}

Guolin Ke's avatar
Guolin Ke committed
218
219
220
void Tree::AddPredictionToScore(const Dataset* data,
  const data_size_t* used_data_indices,
  data_size_t num_data, double* score) const {
Guolin Ke's avatar
Guolin Ke committed
221
  if (num_leaves_ <= 1) { return; }
Guolin Ke's avatar
Guolin Ke committed
222
223
224
225
226
227
228
229
  std::vector<uint32_t> default_bins(num_leaves_ - 1);
  std::vector<uint32_t> max_bins(num_leaves_ - 1);
  for (int i = 0; i < num_leaves_ - 1; ++i) {
    const int fidx = split_feature_inner_[i];
    auto bin_mapper = data->FeatureBinMapper(fidx);
    default_bins[i] = bin_mapper->GetDefaultBin();
    max_bins[i] = bin_mapper->num_bin() - 1;
  }
230
231
232
  if (has_categorical_) {
    if (data->num_features() > num_leaves_ - 1) {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
233
        [this, data, used_data_indices, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
234
235
        std::vector<std::unique_ptr<BinIterator>> iter(num_leaves_ - 1);
        for (int i = 0; i < num_leaves_ - 1; ++i) {
Guolin Ke's avatar
Guolin Ke committed
236
          const int fidx = split_feature_inner_[i];
237
238
239
240
241
242
243
          iter[i].reset(data->FeatureIterator(fidx));
          iter[i]->Reset(used_data_indices[start]);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          const data_size_t idx = used_data_indices[i];
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
244
245
            uint32_t fval = ConvertMissingValue(iter[node]->Get(idx), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
            if (inner_decision_funs[GetDecisionType(decision_type_[node], kCategoricalMask)](
Guolin Ke's avatar
Guolin Ke committed
246
              fval,
247
248
249
250
251
252
253
254
255
256
257
              threshold_in_bin_[node])) {
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[idx] += static_cast<double>(leaf_value_[~node]);
        }
      });
    } else {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
258
        [this, data, used_data_indices, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
259
260
261
262
263
264
265
266
267
        std::vector<std::unique_ptr<BinIterator>> iter(data->num_features());
        for (int i = 0; i < data->num_features(); ++i) {
          iter[i].reset(data->FeatureIterator(i));
          iter[i]->Reset(used_data_indices[start]);
        }
        for (data_size_t i = start; i < end; ++i) {
          const data_size_t idx = used_data_indices[i];
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
268
269
            uint32_t fval = ConvertMissingValue(iter[split_feature_inner_[node]]->Get(idx), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
            if (inner_decision_funs[GetDecisionType(decision_type_[node], kCategoricalMask)](
Guolin Ke's avatar
Guolin Ke committed
270
              fval,
271
272
273
274
275
276
277
278
279
280
              threshold_in_bin_[node])) {
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[idx] += static_cast<double>(leaf_value_[~node]);
        }
      });
    }
Guolin Ke's avatar
Guolin Ke committed
281
  } else {
282
283
    if (data->num_features() > num_leaves_ - 1) {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
284
        [this, data, used_data_indices, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
285
286
        std::vector<std::unique_ptr<BinIterator>> iter(num_leaves_ - 1);
        for (int i = 0; i < num_leaves_ - 1; ++i) {
Guolin Ke's avatar
Guolin Ke committed
287
          const int fidx = split_feature_inner_[i];
288
289
290
291
292
293
294
          iter[i].reset(data->FeatureIterator(fidx));
          iter[i]->Reset(used_data_indices[start]);
        }
        for (data_size_t i = start; i < end; ++i) {
          int node = 0;
          const data_size_t idx = used_data_indices[i];
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
295
            uint32_t fval = ConvertMissingValue(iter[node]->Get(idx), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
Guolin Ke's avatar
Guolin Ke committed
296
            if (fval <= threshold_in_bin_[node]) {
297
298
299
300
301
302
303
304
305
306
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[idx] += static_cast<double>(leaf_value_[~node]);
        }
      });
    } else {
      Threading::For<data_size_t>(0, num_data,
Guolin Ke's avatar
Guolin Ke committed
307
        [this, data, used_data_indices, score, &default_bins, &max_bins](int, data_size_t start, data_size_t end) {
308
309
310
311
312
313
314
315
316
        std::vector<std::unique_ptr<BinIterator>> iter(data->num_features());
        for (int i = 0; i < data->num_features(); ++i) {
          iter[i].reset(data->FeatureIterator(i));
          iter[i]->Reset(used_data_indices[start]);
        }
        for (data_size_t i = start; i < end; ++i) {
          const data_size_t idx = used_data_indices[i];
          int node = 0;
          while (node >= 0) {
Guolin Ke's avatar
Guolin Ke committed
317
            uint32_t fval = ConvertMissingValue(iter[split_feature_inner_[node]]->Get(idx), threshold_in_bin_[node], decision_type_[node], default_bins[node], max_bins[node]);
Guolin Ke's avatar
Guolin Ke committed
318
            if (fval <= threshold_in_bin_[node]) {
319
320
321
322
323
324
325
326
327
              node = left_child_[node];
            } else {
              node = right_child_[node];
            }
          }
          score[idx] += static_cast<double>(leaf_value_[~node]);
        }
      });
    }
Guolin Ke's avatar
Guolin Ke committed
328
  }
Guolin Ke's avatar
Guolin Ke committed
329
330
331
}

std::string Tree::ToString() {
332
333
334
  std::stringstream str_buf;
  str_buf << "num_leaves=" << num_leaves_ << std::endl;
  str_buf << "split_feature="
Guolin Ke's avatar
Guolin Ke committed
335
    << Common::ArrayToString<int>(split_feature_, num_leaves_ - 1, ' ') << std::endl;
336
  str_buf << "split_gain="
Guolin Ke's avatar
Guolin Ke committed
337
    << Common::ArrayToString<double>(split_gain_, num_leaves_ - 1, ' ') << std::endl;
338
  str_buf << "threshold="
Guolin Ke's avatar
Guolin Ke committed
339
    << Common::ArrayToString<double>(threshold_, num_leaves_ - 1, ' ') << std::endl;
340
341
  str_buf << "decision_type="
    << Common::ArrayToString<int>(Common::ArrayCast<int8_t, int>(decision_type_), num_leaves_ - 1, ' ') << std::endl;
342
  str_buf << "left_child="
Guolin Ke's avatar
Guolin Ke committed
343
    << Common::ArrayToString<int>(left_child_, num_leaves_ - 1, ' ') << std::endl;
344
  str_buf << "right_child="
Guolin Ke's avatar
Guolin Ke committed
345
    << Common::ArrayToString<int>(right_child_, num_leaves_ - 1, ' ') << std::endl;
346
  str_buf << "leaf_parent="
Guolin Ke's avatar
Guolin Ke committed
347
    << Common::ArrayToString<int>(leaf_parent_, num_leaves_, ' ') << std::endl;
348
  str_buf << "leaf_value="
Guolin Ke's avatar
Guolin Ke committed
349
    << Common::ArrayToString<double>(leaf_value_, num_leaves_, ' ') << std::endl;
350
  str_buf << "leaf_count="
Guolin Ke's avatar
Guolin Ke committed
351
    << Common::ArrayToString<data_size_t>(leaf_count_, num_leaves_, ' ') << std::endl;
352
  str_buf << "internal_value="
Guolin Ke's avatar
Guolin Ke committed
353
    << Common::ArrayToString<double>(internal_value_, num_leaves_ - 1, ' ') << std::endl;
354
  str_buf << "internal_count="
Guolin Ke's avatar
Guolin Ke committed
355
    << Common::ArrayToString<data_size_t>(internal_count_, num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
356
  str_buf << "shrinkage=" << shrinkage_ << std::endl;
Guolin Ke's avatar
Guolin Ke committed
357
  str_buf << "has_categorical=" << (has_categorical_ ? 1 : 0) << std::endl;
358
359
  str_buf << std::endl;
  return str_buf.str();
Guolin Ke's avatar
Guolin Ke committed
360
361
}

wxchan's avatar
wxchan committed
362
std::string Tree::ToJSON() {
363
  std::stringstream str_buf;
364
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
365
  str_buf << "\"num_leaves\":" << num_leaves_ << "," << std::endl;
Guolin Ke's avatar
Guolin Ke committed
366
  str_buf << "\"shrinkage\":" << shrinkage_ << "," << std::endl;
Guolin Ke's avatar
Guolin Ke committed
367
  str_buf << "\"has_categorical\":" << (has_categorical_ ? 1 : 0) << "," << std::endl;
wxchan's avatar
wxchan committed
368
369
370
371
372
  if (num_leaves_ == 1) {
    str_buf << "\"tree_structure\":" << NodeToJSON(-1) << std::endl;
  } else {
    str_buf << "\"tree_structure\":" << NodeToJSON(0) << std::endl;
  }
wxchan's avatar
wxchan committed
373

374
  return str_buf.str();
wxchan's avatar
wxchan committed
375
376
377
}

std::string Tree::NodeToJSON(int index) {
378
  std::stringstream str_buf;
379
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
wxchan's avatar
wxchan committed
380
381
  if (index >= 0) {
    // non-leaf
382
383
    str_buf << "{" << std::endl;
    str_buf << "\"split_index\":" << index << "," << std::endl;
Guolin Ke's avatar
Guolin Ke committed
384
    str_buf << "\"split_feature\":" << split_feature_[index] << "," << std::endl;
385
    str_buf << "\"split_gain\":" << split_gain_[index] << "," << std::endl;
386
    str_buf << "\"threshold\":" << Common::AvoidInf(threshold_[index]) << "," << std::endl;
387
    str_buf << "\"decision_type\":\"" << Tree::GetDecisionTypeName(decision_type_[index]) << "\"," << std::endl;
388
389
390
391
392
    str_buf << "\"internal_value\":" << internal_value_[index] << "," << std::endl;
    str_buf << "\"internal_count\":" << internal_count_[index] << "," << std::endl;
    str_buf << "\"left_child\":" << NodeToJSON(left_child_[index]) << "," << std::endl;
    str_buf << "\"right_child\":" << NodeToJSON(right_child_[index]) << std::endl;
    str_buf << "}";
wxchan's avatar
wxchan committed
393
394
395
  } else {
    // leaf
    index = ~index;
396
397
398
399
400
401
    str_buf << "{" << std::endl;
    str_buf << "\"leaf_index\":" << index << "," << std::endl;
    str_buf << "\"leaf_parent\":" << leaf_parent_[index] << "," << std::endl;
    str_buf << "\"leaf_value\":" << leaf_value_[index] << "," << std::endl;
    str_buf << "\"leaf_count\":" << leaf_count_[index] << std::endl;
    str_buf << "}";
wxchan's avatar
wxchan committed
402
403
  }

404
  return str_buf.str();
wxchan's avatar
wxchan committed
405
406
}

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
std::string Tree::ToIfElse(int index, bool is_predict_leaf_index) {
  std::stringstream str_buf;
  str_buf << "double PredictTree" << index;
  if (is_predict_leaf_index) {
    str_buf << "Leaf";
  }
  str_buf << "(const double* arr) { ";
  if (num_leaves_ == 1) {
    str_buf << "return 0";
  } else {
    str_buf << NodeToIfElse(0, is_predict_leaf_index);
  }
  str_buf << " }" << std::endl;
  return str_buf.str();
}

std::string Tree::NodeToIfElse(int index, bool is_predict_leaf_index) {
  std::stringstream str_buf;
  str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
  if (index >= 0) {
    // non-leaf
Guolin Ke's avatar
Guolin Ke committed
428
429
    str_buf << "if (Tree::ConvertMissingValue(arr[" << split_feature_[index] << "], " << threshold_[index] << ", " << static_cast<int>(decision_type_[index]) << ") ";
    if (GetDecisionType(decision_type_[index], kCategoricalMask) == 0) {
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
      str_buf << "<";
    } else {
      str_buf << "=";
    }
    str_buf << "= " << threshold_[index] << " ) { ";
    // left subtree
    str_buf << NodeToIfElse(left_child_[index], is_predict_leaf_index);
    str_buf << " } else { ";
    // right subtree
    str_buf << NodeToIfElse(right_child_[index], is_predict_leaf_index);
    str_buf << " }";
  } else {
    // leaf
    str_buf << "return ";
    if (is_predict_leaf_index) {
      str_buf << ~index;
    } else {
      str_buf << leaf_value_[~index];
    }
    str_buf << ";";
  }

  return str_buf.str();
}

Guolin Ke's avatar
Guolin Ke committed
455
Tree::Tree(const std::string& str) {
Guolin Ke's avatar
Guolin Ke committed
456
  std::vector<std::string> lines = Common::SplitLines(str.c_str());
Guolin Ke's avatar
Guolin Ke committed
457
458
459
460
461
462
463
464
465
466
467
  std::unordered_map<std::string, std::string> key_vals;
  for (const std::string& line : lines) {
    std::vector<std::string> tmp_strs = Common::Split(line.c_str(), '=');
    if (tmp_strs.size() == 2) {
      std::string key = Common::Trim(tmp_strs[0]);
      std::string val = Common::Trim(tmp_strs[1]);
      if (key.size() > 0 && val.size() > 0) {
        key_vals[key] = val;
      }
    }
  }
468
  if (key_vals.count("num_leaves") <= 0) {
Guolin Ke's avatar
Guolin Ke committed
469
    Log::Fatal("Tree model should contain num_leaves field.");
Guolin Ke's avatar
Guolin Ke committed
470
471
472
473
  }

  Common::Atoi(key_vals["num_leaves"].c_str(), &num_leaves_);

474
475
  if (num_leaves_ <= 1) { return; }

Guolin Ke's avatar
Guolin Ke committed
476
477
478
479
  if (key_vals.count("left_child")) {
    left_child_ = Common::StringToArray<int>(key_vals["left_child"], ' ', num_leaves_ - 1);
  } else {
    Log::Fatal("Tree model string format error, should contain left_child field");
480
481
  }

Guolin Ke's avatar
Guolin Ke committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
  if (key_vals.count("right_child")) {
    right_child_ = Common::StringToArray<int>(key_vals["right_child"], ' ', num_leaves_ - 1);
  } else {
    Log::Fatal("Tree model string format error, should contain right_child field");
  }

  if (key_vals.count("split_feature")) {
    split_feature_ = Common::StringToArray<int>(key_vals["split_feature"], ' ', num_leaves_ - 1);
  } else {
    Log::Fatal("Tree model string format error, should contain split_feature field");
  }

  if (key_vals.count("threshold")) {
    threshold_ = Common::StringToArray<double>(key_vals["threshold"], ' ', num_leaves_ - 1);
  } else {
    Log::Fatal("Tree model string format error, should contain threshold field");
  }

  if (key_vals.count("leaf_value")) {
    leaf_value_ = Common::StringToArray<double>(key_vals["leaf_value"], ' ', num_leaves_);
  } else {
    Log::Fatal("Tree model string format error, should contain leaf_value field");
  }

  if (key_vals.count("split_gain")) {
    split_gain_ = Common::StringToArray<double>(key_vals["split_gain"], ' ', num_leaves_ - 1);
  } else {
    split_gain_.resize(num_leaves_ - 1);
  }

  if (key_vals.count("internal_count")) {
    internal_count_ = Common::StringToArray<data_size_t>(key_vals["internal_count"], ' ', num_leaves_ - 1);
  } else {
    internal_count_.resize(num_leaves_ - 1);
  }

  if (key_vals.count("internal_value")) {
    internal_value_ = Common::StringToArray<double>(key_vals["internal_value"], ' ', num_leaves_ - 1);
  } else {
    internal_value_.resize(num_leaves_ - 1);
  }

  if (key_vals.count("leaf_count")) {
    leaf_count_ = Common::StringToArray<data_size_t>(key_vals["leaf_count"], ' ', num_leaves_);
  } else {
    leaf_count_.resize(num_leaves_);
  }

  if (key_vals.count("leaf_parent")) {
    leaf_parent_ = Common::StringToArray<int>(key_vals["leaf_parent"], ' ', num_leaves_);
  } else {
    leaf_parent_.resize(num_leaves_);
  }

  if (key_vals.count("decision_type")) {
    decision_type_ = Common::StringToArray<int8_t>(key_vals["decision_type"], ' ', num_leaves_ - 1);
  } else {
    decision_type_ = std::vector<int8_t>(num_leaves_ - 1, 0);
  }

  if (key_vals.count("shrinkage")) {
    Common::Atof(key_vals["shrinkage"].c_str(), &shrinkage_);
  } else {
    shrinkage_ = 1.0f;
  }
Guolin Ke's avatar
Guolin Ke committed
547
548
549
550
551
552
553
554
555

  if (key_vals.count("has_categorical")) {
    int t = 0;
    Common::Atoi(key_vals["has_categorical"].c_str(), &t);
    has_categorical_ = t > 0;
  } else {
    has_categorical_ = false;
  }

Guolin Ke's avatar
Guolin Ke committed
556
557
558
}

}  // namespace LightGBM