Logo ROOT  
Reference Guide
Loading...
Searching...
No Matches
ApplicationRegressionPyTorch.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_tmva_pytorch
3## \notebook -nodraw
4## This tutorial shows how to apply a trained model to new data (regression).
5##
6## \macro_code
7##
8## \date 2020
9## \author Anirudh Dagar <anirudhdagar6@gmail.com> - IIT, Roorkee
10
11
12# PyTorch has to be imported before ROOT to avoid crashes because of clashing
13# std::regexp symbols that are exported by cppyy.
14# See also: https://github.com/wlav/cppyy/issues/227
15import torch
16
17from ROOT import TMVA, TFile, TString, gROOT
18from array import array
19from subprocess import call
20from os.path import isfile
21
22
23# Setup TMVA
26reader = TMVA.Reader("Color:!Silent")
27
28
29# Load data
30data = TFile.Open(str(gROOT.GetTutorialDir()) + "/machine_learning/data/tmva_reg_example.root")
31tree = data.Get('TreeR')
32
33branches = {}
34for branch in tree.GetListOfBranches():
35 branchName = branch.GetName()
36 branches[branchName] = array('f', [-999])
37 tree.SetBranchAddress(branchName, branches[branchName])
38 if branchName != 'fvalue':
39 reader.AddVariable(branchName, branches[branchName])
40
41
42# Book methods
43reader.BookMVA('PyTorch', TString('dataset/weights/TMVARegression_PyTorch.weights.xml'))
44
45
46# Define predict function
47def predict(model, test_X, batch_size=32):
48 # Set to eval mode
49 model.eval()
50
51 test_dataset = torch.utils.data.TensorDataset(torch.Tensor(test_X))
52 test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
53
54 predictions = []
55 with torch.no_grad():
56 for i, data in enumerate(test_loader):
57 X = data[0]
58 outputs = model(X)
59 predictions.append(outputs)
60 preds = torch.cat(predictions)
61
62 return preds.numpy()
63
64load_model_custom_objects = {"optimizer": None, "criterion": None, "train_func": None, "predict_func": predict}
65
66
67# Print some example regressions
68print('Some example regressions:')
69for i in range(20):
70 tree.GetEntry(i)
71 print('True/MVA value: {}/{}'.format(branches['fvalue'][0],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:3787
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:72
Basic string class.
Definition TString.h:138