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
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):
71 print('True/MVA value: {}/{}'.format(branches['fvalue'][0],reader.EvaluateMVA('PyTorch')))
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format
The Reader class serves to use the MVAs in a specific analysis context.
Definition Reader.h:64
Basic string class.
Definition TString.h:139