Logo ROOT   6.10/09
Reference Guide
ClassificationKeras.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 from ROOT import TMVA, TFile, TTree, TCut
4 from subprocess import call
5 from os.path import isfile
6 
7 from keras.models import Sequential
8 from keras.layers.core import Dense, Activation
9 from keras.regularizers import l2
10 from keras import initializations
11 from keras.optimizers import SGD
12 
13 # Setup TMVA
16 
17 output = TFile.Open('TMVA.root', 'RECREATE')
18 factory = TMVA.Factory('TMVAClassification', output,
19  '!V:!Silent:Color:DrawProgressBar:Transformations=D,G:AnalysisType=Classification')
20 
21 # Load data
22 if not isfile('tmva_class_example.root'):
23  call(['curl', '-O', 'http://root.cern.ch/files/tmva_class_example.root'])
24 
25 data = TFile.Open('tmva_class_example.root')
26 signal = data.Get('TreeS')
27 background = data.Get('TreeB')
28 
29 dataloader = TMVA.DataLoader('dataset')
30 for branch in signal.GetListOfBranches():
31  dataloader.AddVariable(branch.GetName())
32 
33 dataloader.AddSignalTree(signal, 1.0)
34 dataloader.AddBackgroundTree(background, 1.0)
35 dataloader.PrepareTrainingAndTestTree(TCut(''),
36  'nTrain_Signal=4000:nTrain_Background=4000:SplitMode=Random:NormMode=NumEvents:!V')
37 
38 # Generate model
39 
40 # Define initialization
41 def normal(shape, name=None):
42  return initializations.normal(shape, scale=0.05, name=name)
43 
44 # Define model
45 model = Sequential()
46 model.add(Dense(64, init=normal, activation='relu', W_regularizer=l2(1e-5), input_dim=4))
47 #model.add(Dense(32, init=normal, activation='relu', W_regularizer=l2(1e-5)))
48 model.add(Dense(2, init=normal, activation='softmax'))
49 
50 # Set loss and optimizer
51 model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01), metrics=['accuracy',])
52 
53 # Store model to file
54 model.save('model.h5')
55 model.summary()
56 
57 # Book methods
58 factory.BookMethod(dataloader, TMVA.Types.kFisher, 'Fisher',
59  '!H:!V:Fisher:VarTransform=D,G')
60 factory.BookMethod(dataloader, TMVA.Types.kPyKeras, 'PyKeras',
61  'H:!V:VarTransform=D,G:FilenameModel=model.h5:NumEpochs=20:BatchSize=32')
62 
63 # Run training, test and evaluation
64 factory.TrainAllMethods()
65 factory.TestAllMethods()
66 factory.EvaluateAllMethods()
static Tools & Instance()
Definition: Tools.cxx:75
static void PyInitialize()
Initialize Python interpreter.
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=1, Int_t netopt=0)
Create / open a file.
Definition: TFile.cxx:3909
This is the main MVA steering class.
Definition: Factory.h:81
def normal(shape, name=None)