ATLAS Offline Software
Classes | Functions | Variables
util.convertXGBoostToRootTree Namespace Reference

Classes

class  XBGoostTextNode
 

Functions

def dump_tree (tree_structure)
 
def dump2ROOT (model, output_filename, output_treename='xgboost')
 
def convertXGBoostToRootTree (model, output_filename, tree_name='xgboost')
 
def test (model_file, tree_file, objective, tree_name='xgboost', ntests=10000, test_file=None)
 
def test_regression (booster, mva_utils, objective, ntests=10000, test_file=None)
 
def test_binary (booster, mva_utils, objective, ntests=10000, test_file=None)
 
def test_multiclass (booster, mva_utils, objective, ntests=10000, test_file=None)
 
def check_file (fn)
 

Variables

string __author__ = "Yuan-Tang Chou"
 
 level
 
 parser = argparse.ArgumentParser(description=__doc__)
 
 help
 
 type
 
 str
 
 default
 
 action
 
 int
 
 args = parser.parse_args()
 
list supported_objective = ['binary:logistic', 'reg:linear', 'reg:squarederror','multi:softprob']
 
def output_treename = convertXGBoostToRootTree(args.input, args.output, args.tree_name)
 
def result = test(args.input, args.output, args.objective, args.tree_name, args.ntests, args.test_file)
 
 objective = args.objective
 
 data = np.load(args.test_file)
 

Function Documentation

◆ check_file()

def util.convertXGBoostToRootTree.check_file (   fn)

Definition at line 279 of file convertXGBoostToRootTree.py.

279 def check_file(fn):
280  f = ROOT.TFile.Open(fn)
281  keys = f.GetListOfKeys()
282  keys = list(keys)
283  if len(keys) != 1:
284  logging.info("file %s is empty", fn)
285  return False
286  tree = f.Get(keys[0].GetName())
287  if type(tree) is not ROOT.TTree:
288  logging.info("cannot find TTree in file %s", fn)
289  return False
290  if not tree.GetEntries():
291  logging.info("tree is empty")
292  return False
293  return True
294 
295 

◆ convertXGBoostToRootTree()

def util.convertXGBoostToRootTree.convertXGBoostToRootTree (   model,
  output_filename,
  tree_name = 'xgboost' 
)
Model: - a string, in this case, it is the name of the input file containing the xgboost model
         you can get this model with xgboost with `bst.save_model('my_model.model')
       - directly a xgboost booster object

Definition at line 133 of file convertXGBoostToRootTree.py.

133 def convertXGBoostToRootTree(model, output_filename, tree_name='xgboost'):
134  """
135  Model: - a string, in this case, it is the name of the input file containing the xgboost model
136  you can get this model with xgboost with `bst.save_model('my_model.model')
137  - directly a xgboost booster object
138  """
139  if type(model) is str:
140  bst = xgb.Booster()
141  bst.load_model(model)
142  return dump2ROOT(bst, output_filename, tree_name)
143  else:
144  return dump2ROOT(model, output_filename, tree_name)
145 
146 

◆ dump2ROOT()

def util.convertXGBoostToRootTree.dump2ROOT (   model,
  output_filename,
  output_treename = 'xgboost' 
)

Definition at line 93 of file convertXGBoostToRootTree.py.

93 def dump2ROOT(model, output_filename, output_treename='xgboost'):
94  model.dump_model('dump_model.json', dump_format='json')
95  with open('dump_model.json', 'r') as dump_json:
96  model_dump = dump_json.read()
97  trees = json.loads(model_dump)
98  fout = ROOT.TFile.Open(output_filename, 'recreate')
99 
100  features_array = ROOT.std.vector('int')()
101  values_array = ROOT.std.vector('float')()
102  default_lefts_array = ROOT.std.vector('bool')()
103 
104  title = 'creator=xgboost'
105  root_tree = ROOT.TTree(output_treename, title)
106  root_tree.Branch('vars', 'vector<int>', ROOT.AddressOf(features_array))
107  root_tree.Branch('values', 'vector<float>', ROOT.AddressOf(values_array))
108  root_tree.Branch('default_left', 'vector<bool>', ROOT.AddressOf(default_lefts_array))
109 
110  logging.info("tree support nan: using XGBoost implementation")
111 
112  for tree in trees:
113  tree_structure = tree
114  features, values, default_lefts = dump_tree(tree_structure)
115 
116  features_array.clear()
117  values_array.clear()
118  default_lefts_array.clear()
119 
120  for value in values:
121  values_array.push_back(value)
122  for feature in features:
123  features_array.push_back(feature)
124  for default_left in default_lefts:
125  default_lefts_array.push_back(default_left)
126 
127  root_tree.Fill()
128 
129  root_tree.Write()
130  fout.Close()
131  return output_treename
132 

◆ dump_tree()

def util.convertXGBoostToRootTree.dump_tree (   tree_structure)
dump a single decision tree to arrays to be written into the TTree

Definition at line 67 of file convertXGBoostToRootTree.py.

67 def dump_tree(tree_structure):
68  """
69  dump a single decision tree to arrays to be written into the TTree
70  """
71 
72  split_values = []
73  split_features = []
74  default_left = []
75  top = XBGoostTextNode(tree_structure)
76 
77  def preorder(node):
78  # visit root
79  split_features.append(node.get_split_feature())
80  split_values.append(node.get_value())
81  default_left.append(node.get_default_left())
82 
83  # visit (yes)left
84  if node.get_left() is not None:
85  preorder(node.get_left())
86  # visit (no)right
87  if node.get_right() is not None:
88  preorder(node.get_right())
89 
90  preorder(top)
91  return split_features, split_values, default_left
92 

◆ test()

def util.convertXGBoostToRootTree.test (   model_file,
  tree_file,
  objective,
  tree_name = 'xgboost',
  ntests = 10000,
  test_file = None 
)

Definition at line 147 of file convertXGBoostToRootTree.py.

147 def test(model_file, tree_file, objective, tree_name='xgboost', ntests=10000, test_file=None):
148  bst = xgb.Booster()
149  bst.load_model(model_file)
150  f = ROOT.TFile.Open(tree_file)
151  tree = f.Get(tree_name)
152  try:
153  _ = ROOT.MVAUtils.BDT
154  except Exception:
155  print("cannot import MVAUtils")
156  return None
157 
158  mva_utils = ROOT.MVAUtils.BDT(tree)
159 
160  if 'binary' in objective:
161  logging.info("testing binary")
162  return test_binary(bst, mva_utils, objective, ntests, test_file)
163  elif 'multi' in objective:
164  logging.info("testing multi-class")
165  return test_multiclass(bst,mva_utils, objective, ntests, test_file)
166  else:
167  logging.info("testing regression")
168  return test_regression(bst, mva_utils, objective, ntests, test_file)
169 

◆ test_binary()

def util.convertXGBoostToRootTree.test_binary (   booster,
  mva_utils,
  objective,
  ntests = 10000,
  test_file = None 
)

Definition at line 206 of file convertXGBoostToRootTree.py.

206 def test_binary(booster, mva_utils, objective, ntests=10000, test_file=None):
207  import numpy as np
208  logging.info("Testing input features with binary classification")
209  if test_file is not None:
210  data_input = np.load(test_file)
211  logging.info("using as input %s inputs from file %s", len(data_input), test_file)
212  else:
213  logging.error("Please provide an input test file for testing")
214 
215  start = time.time()
216  dTest = xgb.DMatrix(data_input)
217  results_xgboost = booster.predict(dTest)
218  logging.info("xgboost (vectorized) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
219 
220  input_values_vector = ROOT.std.vector("float")()
221  results_MVAUtils = []
222  start = time.time()
223  for input_values in data_input:
224  input_values_vector.clear()
225  for v in input_values:
226  input_values_vector.push_back(v)
227  output_MVAUtils = mva_utils.GetClassification(input_values_vector)
228  results_MVAUtils.append(output_MVAUtils)
229  logging.info("mvautils (not vectorized+overhead) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
230 
231  for input_values, output_xgb, output_MVAUtils in zip(data_input, results_xgboost, results_MVAUtils):
232  if not np.allclose(output_xgb, output_MVAUtils):
233  logging.info("output are different:"
234  "mvautils: %s\n"
235  "xgboost: %s\n"
236  "inputs: %s", output_MVAUtils, output_xgb, input_values)
237  return False
238  return True
239 

◆ test_multiclass()

def util.convertXGBoostToRootTree.test_multiclass (   booster,
  mva_utils,
  objective,
  ntests = 10000,
  test_file = None 
)

Definition at line 240 of file convertXGBoostToRootTree.py.

240 def test_multiclass(booster, mva_utils, objective, ntests=10000, test_file=None):
241  import numpy as np
242  logging.info("using multiclass model")
243 
244  if test_file is not None:
245  data_input = np.load(test_file)
246  logging.info("using as input %s inputs from file %s", len(data_input), test_file)
247  else:
248  logging.error("Please provide an input test file for testing")
249 
250  start = time.time()
251  dTest = xgb.DMatrix(data_input)
252  results_xgboost = booster.predict(dTest)
253 
254  nclasses = results_xgboost.shape[1]
255  logging.info("xgboost (vectorized) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
256 
257  input_values_vector = ROOT.std.vector("float")()
258  results_MVAUtils = []
259  start = time.time()
260  for input_values in data_input:
261  input_values_vector.clear()
262  for v in input_values:
263  input_values_vector.push_back(v)
264  output_MVAUtils = mva_utils.GetMultiResponse(input_values_vector, nclasses)
265  results_MVAUtils.append(output_MVAUtils)
266 
267  logging.info("mvautils (not vectorized+overhead) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
268 
269  for input_values, output_xgb, output_MVAUtils in zip(data_input, results_xgboost, results_MVAUtils):
270  if not np.allclose(output_xgb, output_MVAUtils):
271  logging.info("output are different:"
272  "mvautils: %s\n"
273  "xgboost: %s\n"
274  "inputs: %s", output_MVAUtils, output_xgb, input_values)
275  return False
276  return True
277 
278 

◆ test_regression()

def util.convertXGBoostToRootTree.test_regression (   booster,
  mva_utils,
  objective,
  ntests = 10000,
  test_file = None 
)

Definition at line 170 of file convertXGBoostToRootTree.py.

170 def test_regression(booster, mva_utils, objective, ntests=10000, test_file=None):
171  import numpy as np
172  logging.info("Tesing input features with regression")
173 
174  if test_file is not None:
175  data_input = np.load(test_file)
176  logging.info("using as input %s inputs from file %s", len(data_input), test_file)
177  else:
178  logging.error("Please provide an input test file for testing")
179 
180  start = time.time()
181  dTest = xgb.DMatrix(data_input)
182  results_xgboost = booster.predict(dTest)
183  logging.info("xgboost (vectorized) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
184 
185  input_values_vector = ROOT.std.vector("float")()
186  results_MVAUtils = []
187  start = time.time()
188  for input_values in data_input:
189  input_values_vector.clear()
190  for v in input_values:
191  input_values_vector.push_back(v)
192  output_MVAUtils = mva_utils.GetResponse(input_values_vector)
193  results_MVAUtils.append(output_MVAUtils)
194  logging.info("mvautils (not vectorized+overhead) timing = %s ms/input", (time.time() - start) * 1000 / len(data_input))
195 
196  for input_values, output_xgb, output_MVAUtils in zip(data_input, results_xgboost, results_MVAUtils):
197  if not np.allclose(output_xgb, output_MVAUtils, rtol=1E-4):
198  logging.info("output are different:"
199  "mvautils: %s\n"
200  "xgboost: %s\n"
201  "inputs: %s", output_MVAUtils, output_xgb, input_values)
202  return False
203  return True
204 
205 

Variable Documentation

◆ __author__

string util.convertXGBoostToRootTree.__author__ = "Yuan-Tang Chou"
private

Definition at line 7 of file convertXGBoostToRootTree.py.

◆ action

util.convertXGBoostToRootTree.action

Definition at line 303 of file convertXGBoostToRootTree.py.

◆ args

util.convertXGBoostToRootTree.args = parser.parse_args()

Definition at line 308 of file convertXGBoostToRootTree.py.

◆ data

util.convertXGBoostToRootTree.data = np.load(args.test_file)

Definition at line 346 of file convertXGBoostToRootTree.py.

◆ default

util.convertXGBoostToRootTree.default

Definition at line 301 of file convertXGBoostToRootTree.py.

◆ help

util.convertXGBoostToRootTree.help

Definition at line 300 of file convertXGBoostToRootTree.py.

◆ int

util.convertXGBoostToRootTree.int

Definition at line 304 of file convertXGBoostToRootTree.py.

◆ level

util.convertXGBoostToRootTree.level

Definition at line 20 of file convertXGBoostToRootTree.py.

◆ objective

util.convertXGBoostToRootTree.objective = args.objective

Definition at line 344 of file convertXGBoostToRootTree.py.

◆ output_treename

def util.convertXGBoostToRootTree.output_treename = convertXGBoostToRootTree(args.input, args.output, args.tree_name)

Definition at line 329 of file convertXGBoostToRootTree.py.

◆ parser

util.convertXGBoostToRootTree.parser = argparse.ArgumentParser(description=__doc__)

Definition at line 299 of file convertXGBoostToRootTree.py.

◆ result

def util.convertXGBoostToRootTree.result = test(args.input, args.output, args.objective, args.tree_name, args.ntests, args.test_file)

Definition at line 339 of file convertXGBoostToRootTree.py.

◆ str

util.convertXGBoostToRootTree.str

Definition at line 301 of file convertXGBoostToRootTree.py.

◆ supported_objective

list util.convertXGBoostToRootTree.supported_objective = ['binary:logistic', 'reg:linear', 'reg:squarederror','multi:softprob']

Definition at line 312 of file convertXGBoostToRootTree.py.

◆ type

util.convertXGBoostToRootTree.type

Definition at line 301 of file convertXGBoostToRootTree.py.

util.convertXGBoostToRootTree.dump2ROOT
def dump2ROOT(model, output_filename, output_treename='xgboost')
Definition: convertXGBoostToRootTree.py:93
util.convertXGBoostToRootTree.check_file
def check_file(fn)
Definition: convertXGBoostToRootTree.py:279
util.convertXGBoostToRootTree.dump_tree
def dump_tree(tree_structure)
Definition: convertXGBoostToRootTree.py:67
util.convertXGBoostToRootTree.type
type
Definition: convertXGBoostToRootTree.py:301
util.convertXGBoostToRootTree.test
def test(model_file, tree_file, objective, tree_name='xgboost', ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:147
histSizes.list
def list(name, path='/')
Definition: histSizes.py:38
util.convertXGBoostToRootTree.test_regression
def test_regression(booster, mva_utils, objective, ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:170
print
void print(char *figname, TCanvas *c1)
Definition: TRTCalib_StrawStatusPlots.cxx:25
Trk::open
@ open
Definition: BinningType.h:40
util.convertXGBoostToRootTree.test_binary
def test_binary(booster, mva_utils, objective, ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:206
util.convertXGBoostToRootTree.convertXGBoostToRootTree
def convertXGBoostToRootTree(model, output_filename, tree_name='xgboost')
Definition: convertXGBoostToRootTree.py:133
util.convertXGBoostToRootTree.test_multiclass
def test_multiclass(booster, mva_utils, objective, ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:240