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, gROOT
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
30data = TFile.Open(str(gROOT.GetTutorialDir()) + '/tmva/data/tmva_class_example.root')
31signal = data.Get('TreeS')
32background = data.Get('TreeB')
33
34dataloader = TMVA.DataLoader('dataset')
35for branch in signal.GetListOfBranches():
36 dataloader.AddVariable(branch.GetName())
37
38dataloader.AddSignalTree(signal, 1.0)
39dataloader.AddBackgroundTree(background, 1.0)
40dataloader.PrepareTrainingAndTestTree(TCut(''),
41 'nTrain_Signal=4000:nTrain_Background=4000:SplitMode=Random:NormMode=NumEvents:!V')
42
43# Generate model
44
45# Define model
46model = Sequential()
47model.add(Dense(64, activation='relu', input_dim=4))
48model.add(Dense(2, activation='softmax'))
49
50# Set loss and optimizer
51model.compile(loss='categorical_crossentropy',
52 optimizer=SGD(learning_rate=0.01), weighted_metrics=['accuracy', ])
53
54# Store model to file
55model.save('modelClassification.h5')
56model.summary()
57
58# Book methods
59factory.BookMethod(dataloader, TMVA.Types.kFisher, 'Fisher',
60 '!H:!V:Fisher:VarTransform=D,G')
61factory.BookMethod(dataloader, TMVA.Types.kPyKeras, 'PyKeras',
62 'H:!V:VarTransform=D,G:FilenameModel=modelClassification.h5:FilenameTrainedModel=trainedModelClassification.h5:NumEpochs=20:BatchSize=32')
63
64# Run training, test and evaluation
65factory.TrainAllMethods()
66factory.TestAllMethods()
67factory.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:4110
This is the main MVA steering class.
Definition Factory.h:80
static void PyInitialize()
Initialize Python interpreter.
static Tools & Instance()
Definition Tools.cxx:71