Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ApplicationClassificationPyTorch.py
Go to the documentation of this file.
1#!/usr/bin/env python
2## \file
3## \ingroup tutorial_tmva_pytorch
4## \notebook -nodraw
5## This tutorial shows how to apply a trained model to new data.
6##
7## \macro_code
8##
9## \date 2020
10## \author Anirudh Dagar <anirudhdagar6@gmail.com> - IIT, Roorkee
11
12
13# PyTorch has to be imported before ROOT to avoid crashes because of clashing
14# std::regexp symbols that are exported by cppyy.
15# See also: https://github.com/wlav/cppyy/issues/227
16import torch
17
18from ROOT import TMVA, TFile, TString
19from array import array
20from subprocess import call
21from os.path import isfile
22
23
24# Setup TMVA
27reader = TMVA.Reader("Color:!Silent")
28
29
30# Load data
31if not isfile('tmva_class_example.root'):
32 call(['curl', '-L', '-O', 'http://root.cern.ch/files/tmva_class_example.root'])
33
34data = TFile.Open('tmva_class_example.root')
35signal = data.Get('TreeS')
36background = data.Get('TreeB')
37
38branches = {}
39for branch in signal.GetListOfBranches():
40 branchName = branch.GetName()
41 branches[branchName] = array('f', [-999])
42 reader.AddVariable(branchName, branches[branchName])
43 signal.SetBranchAddress(branchName, branches[branchName])
44 background.SetBranchAddress(branchName, branches[branchName])
45
46
47# Define predict function
48def predict(model, test_X, batch_size=32):
49 # Set to eval mode
50 model.eval()
51
52 test_dataset = torch.utils.data.TensorDataset(torch.Tensor(test_X))
53 test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
54
55 predictions = []
56 with torch.no_grad():
57 for i, data in enumerate(test_loader):
58 X = data[0]
59 outputs = model(X)
60 predictions.append(outputs)
61 preds = torch.cat(predictions)
62
63 return preds.numpy()
64
65
66load_model_custom_objects = {"optimizer": None, "criterion": None, "train_func": None, "predict_func": predict}
67
68
69# Book methods
70reader.BookMVA('PyTorch', TString('dataset/weights/TMVAClassification_PyTorch.weights.xml'))
71
72
73# Print some example classifications
74print('Some signal example classifications:')
75for i in range(20):
76 signal.GetEntry(i)
77 print(reader.EvaluateMVA('PyTorch'))
78print('')
79
80print('Some background example classifications:')
81for i in range(20):
82 background.GetEntry(i)
83 print(reader.EvaluateMVA('PyTorch'))
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
static void PyInitialize()
Initialize Python interpreter.
The Reader class serves to use the MVAs in a specific analysis context.
Definition Reader.h:64
static Tools & Instance()
Definition Tools.cxx:71
Basic string class.
Definition TString.h:139