Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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, gROOT
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
31fname = str(gROOT.GetTutorialDir()) + "/tmva/data/tmva_class_example.root"
32data = TFile.Open(fname)
33signal = data.Get('TreeS')
34background = data.Get('TreeB')
35
36branches = {}
37for branch in signal.GetListOfBranches():
38 branchName = branch.GetName()
39 branches[branchName] = array('f', [-999])
40 reader.AddVariable(branchName, branches[branchName])
41 signal.SetBranchAddress(branchName, branches[branchName])
42 background.SetBranchAddress(branchName, branches[branchName])
43
44
45# Define predict function
46def predict(model, test_X, batch_size=32):
47 # Set to eval mode
49
50 test_dataset = torch.utils.data.TensorDataset(torch.Tensor(test_X))
51 test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
52
53 predictions = []
54 with torch.no_grad():
55 for i, data in enumerate(test_loader):
56 X = data[0]
57 outputs = model(X)
58 predictions.append(outputs)
59 preds = torch.cat(predictions)
60
61 return preds.numpy()
62
63
64load_model_custom_objects = {"optimizer": None, "criterion": None, "train_func": None, "predict_func": predict}
65
66
67# Book methods
68reader.BookMVA('PyTorch', TString('dataset/weights/TMVAClassification_PyTorch.weights.xml'))
69
70
71# Print some example classifications
72print('Some signal example classifications:')
73for i in range(20):
75 print(reader.EvaluateMVA('PyTorch'))
76print('')
77
78print('Some background example classifications:')
79for i in range(20):
81 print(reader.EvaluateMVA('PyTorch'))
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
The Reader class serves to use the MVAs in a specific analysis context.
Definition Reader.h:64
Basic string class.
Definition TString.h:139