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

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

#include <LightGBM/dataset.h>
#include <LightGBM/feature.h>

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

namespace LightGBM {

Tree::Tree(int max_leaves)
  :max_leaves_(max_leaves) {

Guolin Ke's avatar
Guolin Ke committed
21
22
23
24
25
26
27
28
29
30
31
32
  num_leaves_ = 0;
  left_child_ = std::vector<int>(max_leaves_ - 1);
  right_child_ = std::vector<int>(max_leaves_ - 1);
  split_feature_ = std::vector<int>(max_leaves_ - 1);
  split_feature_real_ = std::vector<int>(max_leaves_ - 1);
  threshold_in_bin_ = std::vector<unsigned int>(max_leaves_ - 1);
  threshold_ = std::vector<double>(max_leaves_ - 1);
  split_gain_ = std::vector<double>(max_leaves_ - 1);
  leaf_parent_ = std::vector<int>(max_leaves_);
  leaf_value_ = std::vector<double>(max_leaves_);
  internal_value_ = std::vector<double>(max_leaves_ - 1);
  leaf_depth_ = std::vector<int>(max_leaves_);
Guolin Ke's avatar
Guolin Ke committed
33
34
  // root is in the depth 1
  leaf_depth_[0] = 1;
Guolin Ke's avatar
Guolin Ke committed
35
36
37
38
  num_leaves_ = 1;
  leaf_parent_[0] = -1;
}
Tree::~Tree() {
Guolin Ke's avatar
Guolin Ke committed
39

Guolin Ke's avatar
Guolin Ke committed
40
41
42
}

int Tree::Split(int leaf, int feature, unsigned int threshold_bin, int real_feature,
43
  double threshold, double left_value, double right_value, double gain) {
Guolin Ke's avatar
Guolin Ke committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
  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
  split_feature_[new_node_idx] = feature;
  split_feature_real_[new_node_idx] = real_feature;
  threshold_in_bin_[new_node_idx] = threshold_bin;
  threshold_[new_node_idx] = threshold;
  split_gain_[new_node_idx] = gain;
  // 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;
67
68
  // save current leaf value to internal node before change
  internal_value_[new_node_idx] = leaf_value_[leaf];
Guolin Ke's avatar
Guolin Ke committed
69
70
  leaf_value_[leaf] = left_value;
  leaf_value_[num_leaves_] = right_value;
Guolin Ke's avatar
Guolin Ke committed
71
72
73
  // update leaf depth
  leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
  leaf_depth_[leaf]++;
Guolin Ke's avatar
Guolin Ke committed
74
75
76
77
78
79
80

  ++num_leaves_;
  return num_leaves_ - 1;
}

void Tree::AddPredictionToScore(const Dataset* data, data_size_t num_data, score_t* score) const {
  Threading::For<data_size_t>(0, num_data, [this, data, score](int, data_size_t start, data_size_t end) {
Guolin Ke's avatar
Guolin Ke committed
81
    std::vector<std::unique_ptr<BinIterator>> iterators(data->num_features());
82
    for (int i = 0; i < data->num_features(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
83
      iterators[i].reset(data->FeatureAt(i)->bin_data()->GetIterator(start));
Guolin Ke's avatar
Guolin Ke committed
84
    }
85
    for (data_size_t i = start; i < end; ++i) {
86
      score[i] += static_cast<score_t>(leaf_value_[GetLeaf(iterators, i)]);
Guolin Ke's avatar
Guolin Ke committed
87
88
89
90
91
92
93
94
    }
  });
}

void Tree::AddPredictionToScore(const Dataset* data, const data_size_t* used_data_indices,
                                             data_size_t num_data, score_t* score) const {
  Threading::For<data_size_t>(0, num_data,
      [this, data, used_data_indices, score](int, data_size_t start, data_size_t end) {
Guolin Ke's avatar
Guolin Ke committed
95
    std::vector<std::unique_ptr<BinIterator>> iterators(data->num_features());
96
    for (int i = 0; i < data->num_features(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
97
      iterators[i].reset(data->FeatureAt(i)->bin_data()->GetIterator(used_data_indices[start]));
Guolin Ke's avatar
Guolin Ke committed
98
    }
99
    for (data_size_t i = start; i < end; ++i) {
100
      score[used_data_indices[i]] += static_cast<score_t>(leaf_value_[GetLeaf(iterators, used_data_indices[i])]);
Guolin Ke's avatar
Guolin Ke committed
101
102
103
104
105
106
107
108
    }
  });
}

std::string Tree::ToString() {
  std::stringstream ss;
  ss << "num_leaves=" << num_leaves_ << std::endl;
  ss << "split_feature="
Guolin Ke's avatar
Guolin Ke committed
109
    << Common::ArrayToString<int>(split_feature_real_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
110
  ss << "split_gain="
Guolin Ke's avatar
Guolin Ke committed
111
    << Common::ArrayToString<double>(split_gain_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
112
  ss << "threshold="
Guolin Ke's avatar
Guolin Ke committed
113
    << Common::ArrayToString<double>(threshold_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
114
  ss << "left_child="
Guolin Ke's avatar
Guolin Ke committed
115
    << Common::ArrayToString<int>(left_child_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
116
  ss << "right_child="
Guolin Ke's avatar
Guolin Ke committed
117
    << Common::ArrayToString<int>(right_child_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
118
  ss << "leaf_parent="
Guolin Ke's avatar
Guolin Ke committed
119
    << Common::ArrayToString<int>(leaf_parent_.data(), num_leaves_, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
120
  ss << "leaf_value="
Guolin Ke's avatar
Guolin Ke committed
121
    << Common::ArrayToString<double>(leaf_value_.data(), num_leaves_, ' ') << std::endl;
122
  ss << "internal_value="
Guolin Ke's avatar
Guolin Ke committed
123
    << Common::ArrayToString<double>(internal_value_.data(), num_leaves_ - 1, ' ') << std::endl;
Guolin Ke's avatar
Guolin Ke committed
124
125
126
127
  ss << std::endl;
  return ss.str();
}

wxchan's avatar
wxchan committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
std::string Tree::ToJSON() {
  std::stringstream ss;

  ss << "\"num_leaves\":" << num_leaves_ << "," << std::endl;

  ss << "\"tree_structure\":" << NodeToJSON(0) << std::endl;

  return ss.str();
}

std::string Tree::NodeToJSON(int index) {
  std::stringstream ss;

  if (index >= 0) {
    // non-leaf
    ss << "{" << std::endl;
    ss << "\"split_index\":" << index << "," << std::endl;
    ss << "\"split_feature\":" << split_feature_real_.data()[index] << "," << std::endl;
    ss << "\"split_gain\":" << split_gain_.data()[index] << "," << std::endl;
    ss << "\"threshold\":" << threshold_.data()[index] << "," << std::endl;
    ss << "\"internal_value\":" << internal_value_.data()[index] << "," << std::endl;
    ss << "\"left_child\":" << NodeToJSON(left_child_.data()[index]) << "," << std::endl;
    ss << "\"right_child\":" << NodeToJSON(right_child_.data()[index]) << std::endl;
    ss << "}";
  } else {
    // leaf
    index = ~index;
    ss << "{" << std::endl;
    ss << "\"leaf_index\":" << index << "," << std::endl;
    ss << "\"leaf_parent\":" << leaf_parent_.data()[index] << "," << std::endl;
    ss << "\"leaf_value\":" << leaf_value_.data()[index] << std::endl;
    ss << "}";
  }

  return ss.str();
}

Guolin Ke's avatar
Guolin Ke committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
Tree::Tree(const std::string& str) {
  std::vector<std::string> lines = Common::Split(str.c_str(), '\n');
  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;
      }
    }
  }
  if (key_vals.count("num_leaves") <= 0 || key_vals.count("split_feature") <= 0
    || key_vals.count("split_gain") <= 0 || key_vals.count("threshold") <= 0
    || key_vals.count("left_child") <= 0 || key_vals.count("right_child") <= 0
181
182
    || key_vals.count("leaf_parent") <= 0 || key_vals.count("leaf_value") <= 0
    || key_vals.count("internal_value") <= 0) {
183
    Log::Fatal("Tree model string format error");
Guolin Ke's avatar
Guolin Ke committed
184
185
186
187
  }

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

Guolin Ke's avatar
Guolin Ke committed
188
189
190
191
192
193
194
195
  left_child_ = std::vector<int>(num_leaves_ - 1);
  right_child_ = std::vector<int>(num_leaves_ - 1);
  split_feature_real_ = std::vector<int>(num_leaves_ - 1);
  threshold_ = std::vector<double>(num_leaves_ - 1);
  split_gain_ = std::vector<double>(num_leaves_ - 1);
  leaf_parent_ = std::vector<int>(num_leaves_);
  leaf_value_ = std::vector<double>(num_leaves_);
  internal_value_ = std::vector<double>(num_leaves_ - 1);
Guolin Ke's avatar
Guolin Ke committed
196
197

  Common::StringToIntArray(key_vals["split_feature"], ' ',
Guolin Ke's avatar
Guolin Ke committed
198
                           num_leaves_ - 1, split_feature_real_.data());
199
  Common::StringToDoubleArray(key_vals["split_gain"], ' ',
Guolin Ke's avatar
Guolin Ke committed
200
                              num_leaves_ - 1, split_gain_.data());
201
  Common::StringToDoubleArray(key_vals["threshold"], ' ',
Guolin Ke's avatar
Guolin Ke committed
202
                              num_leaves_ - 1, threshold_.data());
Guolin Ke's avatar
Guolin Ke committed
203
  Common::StringToIntArray(key_vals["left_child"], ' ',
Guolin Ke's avatar
Guolin Ke committed
204
                           num_leaves_ - 1, left_child_.data());
Guolin Ke's avatar
Guolin Ke committed
205
  Common::StringToIntArray(key_vals["right_child"], ' ',
Guolin Ke's avatar
Guolin Ke committed
206
                           num_leaves_ - 1, right_child_.data());
Guolin Ke's avatar
Guolin Ke committed
207
  Common::StringToIntArray(key_vals["leaf_parent"], ' ',
Guolin Ke's avatar
Guolin Ke committed
208
                           num_leaves_ , leaf_parent_.data());
209
  Common::StringToDoubleArray(key_vals["leaf_value"], ' ',
Guolin Ke's avatar
Guolin Ke committed
210
                              num_leaves_ , leaf_value_.data());
211
  Common::StringToDoubleArray(key_vals["internal_value"], ' ',
Guolin Ke's avatar
Guolin Ke committed
212
                              num_leaves_ - 1 , internal_value_.data());
Guolin Ke's avatar
Guolin Ke committed
213
214
215
}

}  // namespace LightGBM