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 __doc__ = "Convert XGBoost model to TTree to be used with MVAUtils."
 
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 278 of file convertXGBoostToRootTree.py.

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

◆ 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 132 of file convertXGBoostToRootTree.py.

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

◆ dump2ROOT()

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

Definition at line 92 of file convertXGBoostToRootTree.py.

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

◆ 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 66 of file convertXGBoostToRootTree.py.

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

◆ test()

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

Definition at line 146 of file convertXGBoostToRootTree.py.

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

◆ test_binary()

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

Definition at line 205 of file convertXGBoostToRootTree.py.

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

◆ test_multiclass()

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

Definition at line 239 of file convertXGBoostToRootTree.py.

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

◆ test_regression()

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

Definition at line 169 of file convertXGBoostToRootTree.py.

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

Variable Documentation

◆ __author__

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

Definition at line 6 of file convertXGBoostToRootTree.py.

◆ __doc__

string util.convertXGBoostToRootTree.__doc__ = "Convert XGBoost model to TTree to be used with MVAUtils."
private

Definition at line 5 of file convertXGBoostToRootTree.py.

◆ action

util.convertXGBoostToRootTree.action

Definition at line 302 of file convertXGBoostToRootTree.py.

◆ args

util.convertXGBoostToRootTree.args = parser.parse_args()

Definition at line 307 of file convertXGBoostToRootTree.py.

◆ data

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

Definition at line 345 of file convertXGBoostToRootTree.py.

◆ default

util.convertXGBoostToRootTree.default

Definition at line 300 of file convertXGBoostToRootTree.py.

◆ help

util.convertXGBoostToRootTree.help

Definition at line 299 of file convertXGBoostToRootTree.py.

◆ int

util.convertXGBoostToRootTree.int

Definition at line 303 of file convertXGBoostToRootTree.py.

◆ level

util.convertXGBoostToRootTree.level

Definition at line 19 of file convertXGBoostToRootTree.py.

◆ objective

util.convertXGBoostToRootTree.objective = args.objective

Definition at line 343 of file convertXGBoostToRootTree.py.

◆ output_treename

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

Definition at line 328 of file convertXGBoostToRootTree.py.

◆ parser

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

Definition at line 298 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 338 of file convertXGBoostToRootTree.py.

◆ str

util.convertXGBoostToRootTree.str

Definition at line 300 of file convertXGBoostToRootTree.py.

◆ supported_objective

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

Definition at line 311 of file convertXGBoostToRootTree.py.

◆ type

util.convertXGBoostToRootTree.type

Definition at line 300 of file convertXGBoostToRootTree.py.

util.convertXGBoostToRootTree.dump2ROOT
def dump2ROOT(model, output_filename, output_treename='xgboost')
Definition: convertXGBoostToRootTree.py:92
util.convertXGBoostToRootTree.check_file
def check_file(fn)
Definition: convertXGBoostToRootTree.py:278
util.convertXGBoostToRootTree.dump_tree
def dump_tree(tree_structure)
Definition: convertXGBoostToRootTree.py:66
util.convertXGBoostToRootTree.type
type
Definition: convertXGBoostToRootTree.py:300
util.convertXGBoostToRootTree.test
def test(model_file, tree_file, objective, tree_name='xgboost', ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:146
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:169
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:205
Muon::print
std::string print(const MuPatSegment &)
Definition: MuonTrackSteering.cxx:28
util.convertXGBoostToRootTree.convertXGBoostToRootTree
def convertXGBoostToRootTree(model, output_filename, tree_name='xgboost')
Definition: convertXGBoostToRootTree.py:132
util.convertXGBoostToRootTree.test_multiclass
def test_multiclass(booster, mva_utils, objective, ntests=10000, test_file=None)
Definition: convertXGBoostToRootTree.py:239