Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ClassificationKeras.py
Go to the documentation of this file.
1#!/usr/bin/env python
2## \file
3## \ingroup tutorial_tmva_keras
4## \notebook -nodraw
5## This tutorial shows how to do classification in TMVA with neural networks
6## trained with keras.
7##
8## \macro_code
9##
10## \date 2017
11## \author TMVA Team
12
13from ROOT import TMVA, TFile, TTree, TCut
14from subprocess import call
15from os.path import isfile
16
17from tensorflow.keras.models import Sequential
18from tensorflow.keras.layers import Dense, Activation
19from tensorflow.keras.optimizers import SGD
20
21# Setup TMVA
24
25output = TFile.Open('TMVA_Classification_Keras.root', 'RECREATE')
26factory = TMVA.Factory('TMVAClassification', output,
27 '!V:!Silent:Color:DrawProgressBar:Transformations=D,G:AnalysisType=Classification')
28
29# Load data
30if not isfile('tmva_class_example.root'):
31 call(['curl', '-L', '-O', 'http://root.cern/files/tmva_class_example.root'])
32
33data = TFile.Open('tmva_class_example.root')
34signal = data.Get('TreeS')
35background = data.Get('TreeB')
36
37dataloader = TMVA.DataLoader('dataset')
38for branch in signal.GetListOfBranches():
39 dataloader.AddVariable(branch.GetName())
40
41dataloader.AddSignalTree(signal, 1.0)
42dataloader.AddBackgroundTree(background, 1.0)
43dataloader.PrepareTrainingAndTestTree(TCut(''),
44 'nTrain_Signal=4000:nTrain_Background=4000:SplitMode=Random:NormMode=NumEvents:!V')
45
46# Generate model
47
48# Define model
49model = Sequential()
50model.add(Dense(64, activation='relu', input_dim=4))
51model.add(Dense(2, activation='softmax'))
52
53# Set loss and optimizer
54model.compile(loss='categorical_crossentropy',
55 optimizer=SGD(learning_rate=0.01), weighted_metrics=['accuracy', ])
56
57# Store model to file
58model.save('modelClassification.h5')
59model.summary()
60
61# Book methods
62factory.BookMethod(dataloader, TMVA.Types.kFisher, 'Fisher',
63 '!H:!V:Fisher:VarTransform=D,G')
64factory.BookMethod(dataloader, TMVA.Types.kPyKeras, 'PyKeras',
65 'H:!V:VarTransform=D,G:FilenameModel=modelClassification.h5:FilenameTrainedModel=trainedModelClassification.h5:NumEpochs=20:BatchSize=32')
66
67# Run training, test and evaluation
68factory.TrainAllMethods()
69factory.TestAllMethods()
70factory.EvaluateAllMethods()
A specialized string object used for TTree selections.
Definition TCut.h:25
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4089
This is the main MVA steering class.
Definition Factory.h:80
static void PyInitialize()
Initialize Python interpreter.
static Tools & Instance()
Definition Tools.cxx:71