Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
tmva101_Training.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_ml
3## \notebook -nodraw
4## This tutorial show how you can train a machine learning model with any package
5## reading the training data directly from ROOT files. Using XGBoost, we illustrate
6## how you can convert an externally trained model in a format serializable and readable
7## with the fast tree inference engine offered by TMVA.
8##
9## \macro_code
10## \macro_output
11##
12## \date August 2019
13## \author Stefan Wunsch
14
15import numpy as np
16import ROOT
17from tmva100_DataPreparation import variables
18
19
20def load_data(signal_filename, background_filename):
21 # Read data from ROOT files
22 data_sig = ROOT.RDataFrame("Events", signal_filename).AsNumpy()
23 data_bkg = ROOT.RDataFrame("Events", background_filename).AsNumpy()
24
25 # Convert inputs to format readable by machine learning tools
26 x_sig = np.vstack([data_sig[var] for var in variables]).T
27 x_bkg = np.vstack([data_bkg[var] for var in variables]).T
28 x = np.vstack([x_sig, x_bkg])
29
30 # Create labels
31 num_sig = x_sig.shape[0]
32 num_bkg = x_bkg.shape[0]
33 y = np.hstack([np.ones(num_sig), np.zeros(num_bkg)])
34
35 # Compute weights balancing both classes
36 num_all = num_sig + num_bkg
37 w = np.hstack([np.ones(num_sig) * num_all / num_sig, np.ones(num_bkg) * num_all / num_bkg])
38
39 return x, y, w
40
41
42if __name__ == "__main__":
43
44 from xgboost import XGBClassifier
45
46 # Load data
47 x, y, w = load_data("train_signal.root", "train_background.root")
48
49 # Fit xgboost model
50 bdt = XGBClassifier(max_depth=3, n_estimators=500)
51 bdt.fit(x, y, sample_weight=w)
52
53 # Save model in TMVA format
54 print("Training done on ", x.shape[0], "events. Saving model in tmva101.root")
55 ROOT.TMVA.Experimental.SaveXGBoost(bdt, "myBDT", "tmva101.root", num_inputs=x.shape[1])
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...