// @(#)root/mlp:$Id$ // Author: Christophe.Delaere@cern.ch 20/07/03 /************************************************************************* * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TMultiLayerPerceptron This class describes a neural network. There are facilities to train the network and use the output. The input layer is made of inactive neurons (returning the optionally normalized input) and output neurons are linear. The type of hidden neurons is free, the default being sigmoids. (One should still try to pass normalized inputs, e.g. between [0.,1]) The basic input is a TTree and two (training and test) TEventLists. Input and output neurons are assigned a value computed for each event with the same possibilities as for TTree::Draw(). Events may be weighted individually or via TTree::SetWeight(). 6 learning methods are available: kStochastic, kBatch, kSteepestDescent, kRibierePolak, kFletcherReeves and kBFGS. This implementation, written by C. Delaere, is *inspired* from the mlpfit package from J.Schwindling et al. with some extensions: - the algorithms are globally the same - in TMultilayerPerceptron, there is no limitation on the number of layers/neurons, while MLPFIT was limited to 2 hidden layers - TMultilayerPerceptron allows you to save the network in a root file, and provides more export functionalities - TMultilayerPerceptron gives more flexibility regarding the normalization of inputs/outputs - TMultilayerPerceptron provides, thanks to Andrea Bocci, the possibility to use cross-entropy errors, which allows to train a network for pattern classification based on Bayesian posterior probability. ### Introduction Neural Networks are more and more used in various fields for data analysis and classification, both for research and commercial institutions. Some randomly chosen examples are: - image analysis - financial movements predictions and analysis - sales forecast and product shipping optimisation - in particles physics: mainly for classification tasks (signal over background discrimination) More than 50% of neural networks are multilayer perceptrons. This implementation of multilayer perceptrons is inspired from the MLPfit package originally written by Jerome Schwindling. MLPfit remains one of the fastest tool for neural networks studies, and this ROOT add-on will not try to compete on that. A clear and flexible Object Oriented implementation has been chosen over a faster but more difficult to maintain code. Nevertheless, the time penalty does not exceed a factor 2. ### The MLP The multilayer perceptron is a simple feed-forward network with the following structure: \image html mlp.png It is made of neurons characterized by a bias and weighted links between them (let's call those links synapses). The input neurons receive the inputs, normalize them and forward them to the first hidden layer. Each neuron in any subsequent layer first computes a linear combination of the outputs of the previous layer. The output of the neuron is then function of that combination with f being linear for output neurons or a sigmoid for hidden layers. This is useful because of two theorems: 1. A linear combination of sigmoids can approximate any continuous function. 2. Trained with output = 1 for the signal and 0 for the background, the approximated function of inputs X is the probability of signal, knowing X. ### Learning methods The aim of all learning methods is to minimize the total error on a set of weighted examples. The error is defined as the sum in quadrature, divided by two, of the error on each individual output neuron. In all methods implemented, one needs to compute the first derivative of that error with respect to the weights. Exploiting the well-known properties of the derivative, especially the derivative of compound functions, one can write: - for a neuron: product of the local derivative with the weighted sum on the outputs of the derivatives. - for a synapse: product of the input with the local derivative of the output neuron. This computation is called back-propagation of the errors. A loop over all examples is called an epoch. Six learning methods are implemented. #### Stochastic minimization: is the most trivial learning method. This is the Robbins-Monro stochastic approximation applied to multilayer perceptrons. The weights are updated after each example according to the formula: \f$w_{ij}(t+1) = w_{ij}(t) + \Delta w_{ij}(t)\f$ with \f$\Delta w_{ij}(t) = - \eta(d e_p / d w_{ij} + \delta) + \epsilon \Delta w_{ij}(t-1)\f$ The parameters for this method are Eta, EtaDecay, Delta and Epsilon. #### Steepest descent with fixed step size (batch learning): It is the same as the stochastic minimization, but the weights are updated after considering all the examples, with the total derivative dEdw. The parameters for this method are Eta, EtaDecay, Delta and Epsilon. #### Steepest descent algorithm: Weights are set to the minimum along the line defined by the gradient. The only parameter for this method is Tau. Lower tau = higher precision = slower search. A value Tau = 3 seems reasonable. #### Conjugate gradients with the Polak-Ribiere updating formula: Weights are set to the minimum along the line defined by the conjugate gradient. Parameters are Tau and Reset, which defines the epochs where the direction is reset to the steepest descent. #### Conjugate gradients with the Fletcher-Reeves updating formula: Weights are set to the minimum along the line defined by the conjugate gradient. Parameters are Tau and Reset, which defines the epochs where the direction is reset to the steepest descent. #### Broyden, Fletcher, Goldfarb, Shanno (BFGS) method: Implies the computation of a NxN matrix computation, but seems more powerful at least for less than 300 weights. Parameters are Tau and Reset, which defines the epochs where the direction is reset to the steepest descent. ### How to use it... TMLP is build from 3 classes: TNeuron, TSynapse and TMultiLayerPerceptron. Only TMultiLayerPerceptron should be used explicitly by the user. TMultiLayerPerceptron will take examples from a TTree given in the constructor. The network is described by a simple string: The input/output layers are defined by giving the expression for each neuron, separated by comas. Hidden layers are just described by the number of neurons. The layers are separated by colons. In addition, input/output layer formulas can be preceded by '@' (e.g "@out") if one wants to also normalize the data from the TTree. Input and outputs are taken from the TTree given as second argument. Expressions are evaluated as for TTree::Draw(), arrays are expended in distinct neurons, one for each index. This can only be done for fixed-size arrays. If the formula ends with "!", softmax functions are used for the output layer. One defines the training and test datasets by TEventLists. Example: ~~~ {.cpp} TMultiLayerPerceptron("x,y:10:5:f",inputTree); ~~~ Both the TTree and the TEventLists can be defined in the constructor, or later with the suited setter method. The lists used for training and test can be defined either explicitly, or via a string containing the formula to be used to define them, exactly as for a TCut. The learning method is defined using the TMultiLayerPerceptron::SetLearningMethod() . Learning methods are : - TMultiLayerPerceptron::kStochastic, - TMultiLayerPerceptron::kBatch, - TMultiLayerPerceptron::kSteepestDescent, - TMultiLayerPerceptron::kRibierePolak, - TMultiLayerPerceptron::kFletcherReeves, - TMultiLayerPerceptron::kBFGS A weight can be assigned to events, either in the constructor, either with TMultiLayerPerceptron::SetEventWeight(). In addition, the TTree weight is taken into account. Finally, one starts the training with TMultiLayerPerceptron::Train(Int_t nepoch, Option_t* options). The first argument is the number of epochs while option is a string that can contain: "text" (simple text output) , "graph" (evoluting graphical training curves), "update=X" (step for the text/graph output update) or "+" (will skip the randomisation and start from the previous values). All combinations are available. Example: ~~~ {.cpp} net.Train(100,"text, graph, update=10"); ~~~ When the neural net is trained, it can be used directly ( TMultiLayerPerceptron::Evaluate() ) or exported to a standalone C++ code ( TMultiLayerPerceptron::Export() ). Finally, note that even if this implementation is inspired from the mlpfit code, the feature lists are not exactly matching: - mlpfit hybrid learning method is not implemented - output neurons can be normalized, this is not the case for mlpfit - the neural net is exported in C++, FORTRAN or PYTHON - the drawResult() method allows a fast check of the learning procedure In addition, the paw version of mlpfit had additional limitations on the number of neurons, hidden layers and inputs/outputs that does not apply to TMultiLayerPerceptron. */ #include "TMultiLayerPerceptron.h" #include "TSynapse.h" #include "TNeuron.h" #include "TClass.h" #include "TTree.h" #include "TEventList.h" #include "TRandom3.h" #include "TTimeStamp.h" #include "TRegexp.h" #include "TCanvas.h" #include "TH2.h" #include "TGraph.h" #include "TLegend.h" #include "TMultiGraph.h" #include "TDirectory.h" #include "TSystem.h" #include #include #include "TMath.h" #include "TTreeFormula.h" #include "TTreeFormulaManager.h" #include "TMarker.h" #include "TLine.h" #include "TText.h" #include "TObjString.h" #include ClassImp(TMultiLayerPerceptron); //////////////////////////////////////////////////////////////////////////////// /// Default constructor TMultiLayerPerceptron::TMultiLayerPerceptron() { if(!TClass::GetClass("TTreePlayer")) gSystem->Load("libTreePlayer"); fNetwork.SetOwner(true); fFirstLayer.SetOwner(false); fLastLayer.SetOwner(false); fSynapses.SetOwner(true); fData = nullptr; fCurrentTree = -1; fCurrentTreeWeight = 1; fStructure = ""; fWeight = "1"; fTraining = nullptr; fTrainingOwner = false; fTest = nullptr; fTestOwner = false; fEventWeight = nullptr; fManager = nullptr; fLearningMethod = TMultiLayerPerceptron::kBFGS; fEta = .1; fEtaDecay = 1; fDelta = 0; fEpsilon = 0; fTau = 3; fLastAlpha = 0; fReset = 50; fType = TNeuron::kSigmoid; fOutType = TNeuron::kLinear; fextF = ""; fextD = ""; } //////////////////////////////////////////////////////////////////////////////// /// The network is described by a simple string: /// The input/output layers are defined by giving /// the branch names separated by comas. /// Hidden layers are just described by the number of neurons. /// The layers are separated by colons. /// /// Ex: "x,y:10:5:f" /// /// The output can be prepended by '@' if the variable has to be /// normalized. /// The output can be followed by '!' to use Softmax neurons for the /// output layer only. /// /// Ex: "x,y:10:5:c1,c2,c3!" /// /// Input and outputs are taken from the TTree given as second argument. /// training and test are the two TEventLists defining events /// to be used during the neural net training. /// Both the TTree and the TEventLists can be defined in the constructor, /// or later with the suited setter method. TMultiLayerPerceptron::TMultiLayerPerceptron(const char * layout, TTree * data, TEventList * training, TEventList * test, TNeuron::ENeuronType type, const char* extF, const char* extD) { if(!TClass::GetClass("TTreePlayer")) gSystem->Load("libTreePlayer"); fNetwork.SetOwner(true); fFirstLayer.SetOwner(false); fLastLayer.SetOwner(false); fSynapses.SetOwner(true); fStructure = layout; fData = data; fCurrentTree = -1; fCurrentTreeWeight = 1; fTraining = training; fTrainingOwner = false; fTest = test; fTestOwner = false; fWeight = "1"; fType = type; fOutType = TNeuron::kLinear; fextF = extF; fextD = extD; fEventWeight = nullptr; fManager = nullptr; if (data) { BuildNetwork(); AttachData(); } fLearningMethod = TMultiLayerPerceptron::kBFGS; fEta = .1; fEpsilon = 0; fDelta = 0; fEtaDecay = 1; fTau = 3; fLastAlpha = 0; fReset = 50; } //////////////////////////////////////////////////////////////////////////////// /// The network is described by a simple string: /// The input/output layers are defined by giving /// the branch names separated by comas. /// Hidden layers are just described by the number of neurons. /// The layers are separated by colons. /// /// Ex: "x,y:10:5:f" /// /// The output can be prepended by '@' if the variable has to be /// normalized. /// The output can be followed by '!' to use Softmax neurons for the /// output layer only. /// /// Ex: "x,y:10:5:c1,c2,c3!" /// /// Input and outputs are taken from the TTree given as second argument. /// training and test are the two TEventLists defining events /// to be used during the neural net training. /// Both the TTree and the TEventLists can be defined in the constructor, /// or later with the suited setter method. TMultiLayerPerceptron::TMultiLayerPerceptron(const char * layout, const char * weight, TTree * data, TEventList * training, TEventList * test, TNeuron::ENeuronType type, const char* extF, const char* extD) { if(!TClass::GetClass("TTreePlayer")) gSystem->Load("libTreePlayer"); fNetwork.SetOwner(true); fFirstLayer.SetOwner(false); fLastLayer.SetOwner(false); fSynapses.SetOwner(true); fStructure = layout; fData = data; fCurrentTree = -1; fCurrentTreeWeight = 1; fTraining = training; fTrainingOwner = false; fTest = test; fTestOwner = false; fWeight = weight; fType = type; fOutType = TNeuron::kLinear; fextF = extF; fextD = extD; fEventWeight = nullptr; fManager = nullptr; if (data) { BuildNetwork(); AttachData(); } fLearningMethod = TMultiLayerPerceptron::kBFGS; fEta = .1; fEtaDecay = 1; fDelta = 0; fEpsilon = 0; fTau = 3; fLastAlpha = 0; fReset = 50; } //////////////////////////////////////////////////////////////////////////////// /// The network is described by a simple string: /// The input/output layers are defined by giving /// the branch names separated by comas. /// Hidden layers are just described by the number of neurons. /// The layers are separated by colons. /// /// Ex: "x,y:10:5:f" /// /// The output can be prepended by '@' if the variable has to be /// normalized. /// The output can be followed by '!' to use Softmax neurons for the /// output layer only. /// /// Ex: "x,y:10:5:c1,c2,c3!" /// /// Input and outputs are taken from the TTree given as second argument. /// training and test are two cuts (see TTreeFormula) defining events /// to be used during the neural net training and testing. /// /// Example: "Entry$%2", "(Entry$+1)%2". /// /// Both the TTree and the cut can be defined in the constructor, /// or later with the suited setter method. TMultiLayerPerceptron::TMultiLayerPerceptron(const char * layout, TTree * data, const char * training, const char * test, TNeuron::ENeuronType type, const char* extF, const char* extD) { if(!TClass::GetClass("TTreePlayer")) gSystem->Load("libTreePlayer"); fNetwork.SetOwner(true); fFirstLayer.SetOwner(false); fLastLayer.SetOwner(false); fSynapses.SetOwner(true); fStructure = layout; fData = data; fCurrentTree = -1; fCurrentTreeWeight = 1; fTraining = new TEventList(Form("fTrainingList_%zu",(size_t)this)); fTrainingOwner = true; fTest = new TEventList(Form("fTestList_%zu",(size_t)this)); fTestOwner = true; fWeight = "1"; TString testcut = test; if(testcut=="") testcut = Form("!(%s)",training); fType = type; fOutType = TNeuron::kLinear; fextF = extF; fextD = extD; fEventWeight = nullptr; fManager = nullptr; if (data) { BuildNetwork(); data->Draw(Form(">>fTrainingList_%zu",(size_t)this),training,"goff"); data->Draw(Form(">>fTestList_%zu",(size_t)this),(const char *)testcut,"goff"); AttachData(); } else { Warning("TMultiLayerPerceptron::TMultiLayerPerceptron","Data not set. Cannot define datasets"); } fLearningMethod = TMultiLayerPerceptron::kBFGS; fEta = .1; fEtaDecay = 1; fDelta = 0; fEpsilon = 0; fTau = 3; fLastAlpha = 0; fReset = 50; } //////////////////////////////////////////////////////////////////////////////// /// The network is described by a simple string: /// The input/output layers are defined by giving /// the branch names separated by comas. /// Hidden layers are just described by the number of neurons. /// The layers are separated by colons. /// /// Ex: "x,y:10:5:f" /// /// The output can be prepended by '@' if the variable has to be /// normalized. /// The output can be followed by '!' to use Softmax neurons for the /// output layer only. /// /// Ex: "x,y:10:5:c1,c2,c3!" /// /// Input and outputs are taken from the TTree given as second argument. /// training and test are two cuts (see TTreeFormula) defining events /// to be used during the neural net training and testing. /// /// Example: "Entry$%2", "(Entry$+1)%2". /// /// Both the TTree and the cut can be defined in the constructor, /// or later with the suited setter method. TMultiLayerPerceptron::TMultiLayerPerceptron(const char * layout, const char * weight, TTree * data, const char * training, const char * test, TNeuron::ENeuronType type, const char* extF, const char* extD) { if(!TClass::GetClass("TTreePlayer")) gSystem->Load("libTreePlayer"); fNetwork.SetOwner(true); fFirstLayer.SetOwner(false); fLastLayer.SetOwner(false); fSynapses.SetOwner(true); fStructure = layout; fData = data; fCurrentTree = -1; fCurrentTreeWeight = 1; fTraining = new TEventList(Form("fTrainingList_%zu",(size_t)this)); fTrainingOwner = true; fTest = new TEventList(Form("fTestList_%zu",(size_t)this)); fTestOwner = true; fWeight = weight; TString testcut = test; if(testcut=="") testcut = Form("!(%s)",training); fType = type; fOutType = TNeuron::kLinear; fextF = extF; fextD = extD; fEventWeight = nullptr; fManager = nullptr; if (data) { BuildNetwork(); data->Draw(Form(">>fTrainingList_%zu",(size_t)this),training,"goff"); data->Draw(Form(">>fTestList_%zu",(size_t)this),(const char *)testcut,"goff"); AttachData(); } else { Warning("TMultiLayerPerceptron::TMultiLayerPerceptron","Data not set. Cannot define datasets"); } fLearningMethod = TMultiLayerPerceptron::kBFGS; fEta = .1; fEtaDecay = 1; fDelta = 0; fEpsilon = 0; fTau = 3; fLastAlpha = 0; fReset = 50; } //////////////////////////////////////////////////////////////////////////////// /// Destructor TMultiLayerPerceptron::~TMultiLayerPerceptron() { if(fTraining && fTrainingOwner) delete fTraining; if(fTest && fTestOwner) delete fTest; } //////////////////////////////////////////////////////////////////////////////// /// Set the data source void TMultiLayerPerceptron::SetData(TTree * data) { if (fData) { std::cerr << "Error: data already defined." << std::endl; return; } fData = data; if (data) { BuildNetwork(); AttachData(); } } //////////////////////////////////////////////////////////////////////////////// /// Set the event weight void TMultiLayerPerceptron::SetEventWeight(const char * branch) { fWeight=branch; if (fData) { if (fEventWeight) { fManager->Remove(fEventWeight); delete fEventWeight; } fManager->Add((fEventWeight = new TTreeFormula("NNweight",fWeight.Data(),fData))); } } //////////////////////////////////////////////////////////////////////////////// /// Sets the Training dataset. /// Those events will be used for the minimization void TMultiLayerPerceptron::SetTrainingDataSet(TEventList* train) { if(fTraining && fTrainingOwner) delete fTraining; fTraining = train; fTrainingOwner = false; } //////////////////////////////////////////////////////////////////////////////// /// Sets the Test dataset. /// Those events will not be used for the minimization but for control void TMultiLayerPerceptron::SetTestDataSet(TEventList* test) { if(fTest && fTestOwner) delete fTest; fTest = test; fTestOwner = false; } //////////////////////////////////////////////////////////////////////////////// /// Sets the Training dataset. /// Those events will be used for the minimization. /// Note that the tree must be already defined. void TMultiLayerPerceptron::SetTrainingDataSet(const char * train) { if(fTraining && fTrainingOwner) delete fTraining; fTraining = new TEventList(Form("fTrainingList_%zu",(size_t)this)); fTrainingOwner = true; if (fData) { fData->Draw(Form(">>fTrainingList_%zu",(size_t)this),train,"goff"); } else { Warning("TMultiLayerPerceptron::TMultiLayerPerceptron","Data not set. Cannot define datasets"); } } //////////////////////////////////////////////////////////////////////////////// /// Sets the Test dataset. /// Those events will not be used for the minimization but for control. /// Note that the tree must be already defined. void TMultiLayerPerceptron::SetTestDataSet(const char * test) { if(fTest && fTestOwner) {delete fTest; fTest=nullptr;} if(fTest) if(strncmp(fTest->GetName(),Form("fTestList_%zu",(size_t)this),10)) delete fTest; fTest = new TEventList(Form("fTestList_%zu",(size_t)this)); fTestOwner = true; if (fData) { fData->Draw(Form(">>fTestList_%zu",(size_t)this),test,"goff"); } else { Warning("TMultiLayerPerceptron::TMultiLayerPerceptron","Data not set. Cannot define datasets"); } } //////////////////////////////////////////////////////////////////////////////// /// Sets the learning method. /// Available methods are: kStochastic, kBatch, /// kSteepestDescent, kRibierePolak, kFletcherReeves and kBFGS. /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetLearningMethod(TMultiLayerPerceptron::ELearningMethod method) { fLearningMethod = method; } //////////////////////////////////////////////////////////////////////////////// /// Sets Eta - used in stochastic minimisation /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetEta(Double_t eta) { fEta = eta; } //////////////////////////////////////////////////////////////////////////////// /// Sets Epsilon - used in stochastic minimisation /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetEpsilon(Double_t eps) { fEpsilon = eps; } //////////////////////////////////////////////////////////////////////////////// /// Sets Delta - used in stochastic minimisation /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetDelta(Double_t delta) { fDelta = delta; } //////////////////////////////////////////////////////////////////////////////// /// Sets EtaDecay - Eta *= EtaDecay at each epoch /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetEtaDecay(Double_t ed) { fEtaDecay = ed; } //////////////////////////////////////////////////////////////////////////////// /// Sets Tau - used in line search /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetTau(Double_t tau) { fTau = tau; } //////////////////////////////////////////////////////////////////////////////// /// Sets number of epochs between two resets of the /// search direction to the steepest descent. /// (look at the constructor for the complete description /// of learning methods and parameters) void TMultiLayerPerceptron::SetReset(Int_t reset) { fReset = reset; } //////////////////////////////////////////////////////////////////////////////// /// Load an entry into the network void TMultiLayerPerceptron::GetEntry(Int_t entry) const { if (!fData) return; fData->GetEntry(entry); if (fData->GetTreeNumber() != fCurrentTree) { ((TMultiLayerPerceptron*)this)->fCurrentTree = fData->GetTreeNumber(); fManager->Notify(); ((TMultiLayerPerceptron*)this)->fCurrentTreeWeight = fData->GetWeight(); } Int_t nentries = fNetwork.GetEntriesFast(); for (Int_t i=0;iSetNewEvent(); } } //////////////////////////////////////////////////////////////////////////////// /// Train the network. /// nEpoch is the number of iterations. /// option can contain: /// - "text" (simple text output) /// - "graph" (evoluting graphical training curves) /// - "update=X" (step for the text/graph output update) /// - "+" will skip the randomisation and start from the previous values. /// - "current" (draw in the current canvas) /// - "minErrorTrain" (stop when NN error on the training sample gets below minE /// - "minErrorTest" (stop when NN error on the test sample gets below minE /// All combinations are available. void TMultiLayerPerceptron::Train(Int_t nEpoch, Option_t * option, Double_t minE) { Int_t i; TString opt = option; opt.ToLower(); // Decode options and prepare training. Int_t verbosity = 0; Bool_t newCanvas = true; Bool_t minE_Train = false; Bool_t minE_Test = false; if (opt.Contains("text")) verbosity += 1; if (opt.Contains("graph")) verbosity += 2; Int_t displayStepping = 1; if (opt.Contains("update=")) { TRegexp reg("update=[0-9]*"); TString out = opt(reg); displayStepping = atoi(out.Data() + 7); } if (opt.Contains("current")) newCanvas = false; if (opt.Contains("minerrortrain")) minE_Train = true; if (opt.Contains("minerrortest")) minE_Test = true; TVirtualPad *canvas = nullptr; TMultiGraph *residual_plot = nullptr; TGraph *train_residual_plot = nullptr; TGraph *test_residual_plot = nullptr; if ((!fData) || (!fTraining) || (!fTest)) { Error("Train","Training/Test samples still not defined. Cannot train the neural network"); return; } Info("Train","Using %d train and %d test entries.", fTraining->GetN(), fTest->GetN()); // Text and Graph outputs if (verbosity % 2) std::cout << "Training the Neural Network" << std::endl; if (verbosity / 2) { residual_plot = new TMultiGraph; if(newCanvas) canvas = new TCanvas("NNtraining", "Neural Net training"); else { canvas = gPad; if(!canvas) canvas = new TCanvas("NNtraining", "Neural Net training"); } train_residual_plot = new TGraph(nEpoch); test_residual_plot = new TGraph(nEpoch); canvas->SetLeftMargin(0.14); train_residual_plot->SetLineColor(4); test_residual_plot->SetLineColor(2); residual_plot->Add(train_residual_plot); residual_plot->Add(test_residual_plot); residual_plot->Draw("LA"); if (residual_plot->GetXaxis()) residual_plot->GetXaxis()->SetTitle("Epoch"); if (residual_plot->GetYaxis()) residual_plot->GetYaxis()->SetTitle("Error"); } // If the option "+" is not set, one has to randomize the weights first if (!opt.Contains("+")) Randomize(); // Initialisation fLastAlpha = 0; Int_t els = fNetwork.GetEntriesFast() + fSynapses.GetEntriesFast(); Double_t *buffer = new Double_t[els]; Double_t *dir = new Double_t[els]; for (i = 0; i < els; i++) buffer[i] = 0; Int_t matrix_size = fLearningMethod==TMultiLayerPerceptron::kBFGS ? els : 1; TMatrixD bfgsh(matrix_size, matrix_size); TMatrixD gamma(matrix_size, 1); TMatrixD delta(matrix_size, 1); // Epoch loop. Here is the training itself. Double_t training_E = 1e10; Double_t test_E = 1e10; for (Int_t iepoch = 0; (iepoch < nEpoch) && (!minE_Train || training_E>minE) && (!minE_Test || test_E>minE) ; iepoch++) { switch (fLearningMethod) { case TMultiLayerPerceptron::kStochastic: { MLP_Stochastic(buffer); break; } case TMultiLayerPerceptron::kBatch: { ComputeDEDw(); MLP_Batch(buffer); break; } case TMultiLayerPerceptron::kSteepestDescent: { ComputeDEDw(); SteepestDir(dir); if (LineSearch(dir, buffer)) MLP_Batch(buffer); break; } case TMultiLayerPerceptron::kRibierePolak: { ComputeDEDw(); if (!(iepoch % fReset)) { SteepestDir(dir); } else { Double_t norm = 0; Double_t onorm = 0; for (i = 0; i < els; i++) onorm += dir[i] * dir[i]; Double_t prod = 0; Int_t idx = 0; TNeuron *neuron = nullptr; TSynapse *synapse = nullptr; Int_t nentries = fNetwork.GetEntriesFast(); for (i=0;iGetDEDw(); norm += neuron->GetDEDw() * neuron->GetDEDw(); } nentries = fSynapses.GetEntriesFast(); for (i=0;iGetDEDw(); norm += synapse->GetDEDw() * synapse->GetDEDw(); } ConjugateGradientsDir(dir, (norm - prod) / onorm); } if (LineSearch(dir, buffer)) MLP_Batch(buffer); break; } case TMultiLayerPerceptron::kFletcherReeves: { ComputeDEDw(); if (!(iepoch % fReset)) { SteepestDir(dir); } else { Double_t norm = 0; Double_t onorm = 0; for (i = 0; i < els; i++) onorm += dir[i] * dir[i]; TNeuron *neuron = nullptr; TSynapse *synapse = nullptr; Int_t nentries = fNetwork.GetEntriesFast(); for (i=0;iGetDEDw() * neuron->GetDEDw(); } nentries = fSynapses.GetEntriesFast(); for (i=0;iGetDEDw() * synapse->GetDEDw(); } ConjugateGradientsDir(dir, norm / onorm); } if (LineSearch(dir, buffer)) MLP_Batch(buffer); break; } case TMultiLayerPerceptron::kBFGS: { SetGammaDelta(gamma, delta, buffer); if (!(iepoch % fReset)) { SteepestDir(dir); bfgsh.UnitMatrix(); } else { if (GetBFGSH(bfgsh, gamma, delta)) { SteepestDir(dir); bfgsh.UnitMatrix(); } else { BFGSDir(bfgsh, dir); } } if (DerivDir(dir) > 0) { SteepestDir(dir); bfgsh.UnitMatrix(); } if (LineSearch(dir, buffer)) { bfgsh.UnitMatrix(); SteepestDir(dir); if (LineSearch(dir, buffer)) { Error("TMultiLayerPerceptron::Train()","Line search fail"); iepoch = nEpoch; } } break; } } // Security: would the learning lead to non real numbers, // the learning should stop now. if (TMath::IsNaN(GetError(TMultiLayerPerceptron::kTraining))) { Error("TMultiLayerPerceptron::Train()","Stop."); iepoch = nEpoch; } // Process other ROOT events. Time penalty is less than // 1/1000 sec/evt on a mobile AMD Athlon(tm) XP 1500+ gSystem->ProcessEvents(); training_E = TMath::Sqrt(GetError(TMultiLayerPerceptron::kTraining) / fTraining->GetN()); test_E = TMath::Sqrt(GetError(TMultiLayerPerceptron::kTest) / fTest->GetN()); // Intermediate graph and text output if ((verbosity % 2) && ((!(iepoch % displayStepping)) || (iepoch == nEpoch - 1))) { std::cout << "Epoch: " << iepoch << " learn=" << training_E << " test=" << test_E << std::endl; } if (verbosity / 2) { train_residual_plot->SetPoint(iepoch, iepoch,training_E); test_residual_plot->SetPoint(iepoch, iepoch,test_E); if (!iepoch) { Double_t trp = train_residual_plot->GetY()[iepoch]; Double_t tep = test_residual_plot->GetY()[iepoch]; for (i = 1; i < nEpoch; i++) { train_residual_plot->SetPoint(i, i, trp); test_residual_plot->SetPoint(i, i, tep); } } if ((!(iepoch % displayStepping)) || (iepoch == nEpoch - 1)) { if (residual_plot->GetYaxis()) { residual_plot->GetYaxis()->UnZoom(); residual_plot->GetYaxis()->SetTitleOffset(1.4); residual_plot->GetYaxis()->SetDecimals(); } canvas->Modified(); canvas->Update(); } } } // Cleaning delete [] buffer; delete [] dir; // Final Text and Graph outputs if (verbosity % 2) std::cout << "Training done." << std::endl; if (verbosity / 2) { TLegend *legend = new TLegend(.75, .80, .95, .95); legend->AddEntry(residual_plot->GetListOfGraphs()->At(0), "Training sample", "L"); legend->AddEntry(residual_plot->GetListOfGraphs()->At(1), "Test sample", "L"); legend->Draw(); } } //////////////////////////////////////////////////////////////////////////////// /// Computes the output for a given event. /// Look at the output neuron designed by index. Double_t TMultiLayerPerceptron::Result(Int_t event, Int_t index) const { GetEntry(event); TNeuron *out = (TNeuron *) (fLastLayer.At(index)); if (out) return out->GetValue(); else return 0; } //////////////////////////////////////////////////////////////////////////////// /// Error on the output for a given event Double_t TMultiLayerPerceptron::GetError(Int_t event) const { GetEntry(event); Double_t error = 0; // look at 1st output neuron to determine type and error function Int_t nEntries = fLastLayer.GetEntriesFast(); if (nEntries == 0) return 0.0; switch (fOutType) { case (TNeuron::kSigmoid): error = GetCrossEntropyBinary(); break; case (TNeuron::kSoftmax): error = GetCrossEntropy(); break; case (TNeuron::kLinear): error = GetSumSquareError(); break; default: // default to sum-of-squares error error = GetSumSquareError(); } error *= fEventWeight->EvalInstance(); error *= fCurrentTreeWeight; return error; } //////////////////////////////////////////////////////////////////////////////// /// Error on the whole dataset Double_t TMultiLayerPerceptron::GetError(TMultiLayerPerceptron::EDataSet set) const { TEventList *list = ((set == TMultiLayerPerceptron::kTraining) ? fTraining : fTest); Double_t error = 0; Int_t i; if (list) { Int_t nEvents = list->GetN(); for (i = 0; i < nEvents; i++) { error += GetError(list->GetEntry(i)); } } else if (fData) { Int_t nEvents = (Int_t) fData->GetEntries(); for (i = 0; i < nEvents; i++) { error += GetError(i); } } return error; } //////////////////////////////////////////////////////////////////////////////// /// Error on the output for a given event Double_t TMultiLayerPerceptron::GetSumSquareError() const { Double_t error = 0; for (Int_t i = 0; i < fLastLayer.GetEntriesFast(); i++) { TNeuron *neuron = (TNeuron *) fLastLayer[i]; error += neuron->GetError() * neuron->GetError(); } return (error / 2.); } //////////////////////////////////////////////////////////////////////////////// /// Cross entropy error for sigmoid output neurons, for a given event Double_t TMultiLayerPerceptron::GetCrossEntropyBinary() const { Double_t error = 0; for (Int_t i = 0; i < fLastLayer.GetEntriesFast(); i++) { TNeuron *neuron = (TNeuron *) fLastLayer[i]; Double_t output = neuron->GetValue(); // sigmoid output and target Double_t target = neuron->GetTarget(); // values lie in [0,1] if (target < DBL_EPSILON) { if (output == 1.0) error = DBL_MAX; else error -= TMath::Log(1 - output); } else if ((1 - target) < DBL_EPSILON) { if (output == 0.0) error = DBL_MAX; else error -= TMath::Log(output); } else { if (output == 0.0 || output == 1.0) error = DBL_MAX; else error -= target * TMath::Log(output / target) + (1-target) * TMath::Log((1 - output)/(1 - target)); } } return error; } //////////////////////////////////////////////////////////////////////////////// /// Cross entropy error for a softmax output neuron, for a given event Double_t TMultiLayerPerceptron::GetCrossEntropy() const { Double_t error = 0; for (Int_t i = 0; i < fLastLayer.GetEntriesFast(); i++) { TNeuron *neuron = (TNeuron *) fLastLayer[i]; Double_t output = neuron->GetValue(); // softmax output and target Double_t target = neuron->GetTarget(); // values lie in [0,1] if (target > DBL_EPSILON) { // (target == 0) => dE = 0 if (output == 0.0) error = DBL_MAX; else error -= target * TMath::Log(output / target); } } return error; } //////////////////////////////////////////////////////////////////////////////// /// Compute the DEDw = sum on all training events of dedw for each weight /// normalized by the number of events. void TMultiLayerPerceptron::ComputeDEDw() const { Int_t i,j; Int_t nentries = fSynapses.GetEntriesFast(); TSynapse *synapse; for (i=0;iSetDEDw(0.); } TNeuron *neuron; nentries = fNetwork.GetEntriesFast(); for (i=0;iSetDEDw(0.); } Double_t eventWeight = 1.; if (fTraining) { Int_t nEvents = fTraining->GetN(); for (i = 0; i < nEvents; i++) { GetEntry(fTraining->GetEntry(i)); eventWeight = fEventWeight->EvalInstance(); eventWeight *= fCurrentTreeWeight; nentries = fSynapses.GetEntriesFast(); for (j=0;jSetDEDw(synapse->GetDEDw() + (synapse->GetDeDw()*eventWeight)); } nentries = fNetwork.GetEntriesFast(); for (j=0;jSetDEDw(neuron->GetDEDw() + (neuron->GetDeDw()*eventWeight)); } } nentries = fSynapses.GetEntriesFast(); for (j=0;jSetDEDw(synapse->GetDEDw() / (Double_t) nEvents); } nentries = fNetwork.GetEntriesFast(); for (j=0;jSetDEDw(neuron->GetDEDw() / (Double_t) nEvents); } } else if (fData) { Int_t nEvents = (Int_t) fData->GetEntries(); for (i = 0; i < nEvents; i++) { GetEntry(i); eventWeight = fEventWeight->EvalInstance(); eventWeight *= fCurrentTreeWeight; nentries = fSynapses.GetEntriesFast(); for (j=0;jSetDEDw(synapse->GetDEDw() + (synapse->GetDeDw()*eventWeight)); } nentries = fNetwork.GetEntriesFast(); for (j=0;jSetDEDw(neuron->GetDEDw() + (neuron->GetDeDw()*eventWeight)); } } nentries = fSynapses.GetEntriesFast(); for (j=0;jSetDEDw(synapse->GetDEDw() / (Double_t) nEvents); } nentries = fNetwork.GetEntriesFast(); for (j=0;jSetDEDw(neuron->GetDEDw() / (Double_t) nEvents); } } } //////////////////////////////////////////////////////////////////////////////// /// Randomize the weights void TMultiLayerPerceptron::Randomize() const { Int_t nentries = fSynapses.GetEntriesFast(); Int_t j; TSynapse *synapse; TNeuron *neuron; TTimeStamp ts; TRandom3 gen(ts.GetSec()); for (j=0;jSetWeight(gen.Rndm() - 0.5); } nentries = fNetwork.GetEntriesFast(); for (j=0;jSetWeight(gen.Rndm() - 0.5); } } //////////////////////////////////////////////////////////////////////////////// /// Connects the TTree to Neurons in input and output /// layers. The formulas associated to each neuron are created /// and reported to the network formula manager. /// By default, the branch is not normalised since this would degrade /// performance for classification jobs. /// Normalisation can be requested by putting '@' in front of the formula. void TMultiLayerPerceptron::AttachData() { Int_t j = 0; TNeuron *neuron = nullptr; Bool_t normalize = false; fManager = new TTreeFormulaManager; // Set the size of the internal array of parameters of the formula Int_t maxop, maxpar, maxconst; ROOT::v5::TFormula::GetMaxima(maxop, maxpar, maxconst); ROOT::v5::TFormula::SetMaxima(10, 10, 10); //first layer const TString input = TString(fStructure(0, fStructure.First(':'))); const TObjArray *inpL = input.Tokenize(", "); Int_t nentries = fFirstLayer.GetEntriesFast(); // make sure nentries == entries in inpL R__ASSERT(nentries == inpL->GetLast()+1); for (j=0;jAt(j))->GetString(); neuron = (TNeuron *) fFirstLayer.UncheckedAt(j); if (brName[0]=='@') normalize = true; fManager->Add(neuron->UseBranch(fData,brName.Data() + (normalize?1:0))); if(!normalize) neuron->SetNormalisation(0., 1.); } delete inpL; // last layer TString output = TString( fStructure(fStructure.Last(':') + 1, fStructure.Length() - fStructure.Last(':'))); const TObjArray *outL = output.Tokenize(", "); nentries = fLastLayer.GetEntriesFast(); // make sure nentries == entries in outL R__ASSERT(nentries == outL->GetLast()+1); for (j=0;jAt(j))->GetString(); neuron = (TNeuron *) fLastLayer.UncheckedAt(j); if (brName[0]=='@') normalize = true; fManager->Add(neuron->UseBranch(fData,brName.Data() + (normalize?1:0))); if(!normalize) neuron->SetNormalisation(0., 1.); } delete outL; fManager->Add((fEventWeight = new TTreeFormula("NNweight",fWeight.Data(),fData))); //fManager->Sync(); // Set the old values ROOT::v5::TFormula::SetMaxima(maxop, maxpar, maxconst); } //////////////////////////////////////////////////////////////////////////////// /// Expand the structure of the first layer void TMultiLayerPerceptron::ExpandStructure() { TString input = TString(fStructure(0, fStructure.First(':'))); const TObjArray *inpL = input.Tokenize(", "); Int_t nneurons = inpL->GetLast()+1; TString hiddenAndOutput = TString( fStructure(fStructure.First(':') + 1, fStructure.Length() - fStructure.First(':'))); TString newInput; Int_t i = 0; // loop on input neurons for (i = 0; iAt(i))->GetString(); TTreeFormula f("sizeTestFormula",name,fData); // Variable size arrays are unreliable if(f.GetMultiplicity()==1 && f.GetNdata()>1) { Warning("TMultiLayerPerceptron::ExpandStructure()","Variable size arrays cannot be used to build implicitly an input layer. The index 0 will be assumed."); } // Check if we are coping with an array... then expand // The array operator used is {}. It is detected in TNeuron, and // passed directly as instance index of the TTreeFormula, // so that complex compounds made of arrays can be used without // parsing the details. else if(f.GetNdata()>1) { for(Int_t j=0; j