Logo ROOT   6.08/02
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
MethodDNN.cxx
Go to the documentation of this file.
1 // @(#)root/tmva $Id$
2 // Author: Peter Speckmayer
3 
4 /**********************************************************************************
5  * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
6  * Package: TMVA *
7  * Class : MethodDNN *
8  * Web : http://tmva.sourceforge.net *
9  * *
10  * Description: *
11  * A neural network implementation *
12  * *
13  * Authors (alphabetical): *
14  * Simon Pfreundschuh <s.pfreundschuh@gmail.com> - CERN, Switzerland *
15  * Peter Speckmayer <peter.speckmayer@gmx.ch> - CERN, Switzerland *
16  * *
17  * Copyright (c) 2005-2015: *
18  * CERN, Switzerland *
19  * U. of Victoria, Canada *
20  * MPI-K Heidelberg, Germany *
21  * U. of Bonn, Germany *
22  * *
23  * Redistribution and use in source and binary forms, with or without *
24  * modification, are permitted according to the terms listed in LICENSE *
25  * (http://tmva.sourceforge.net/LICENSE) *
26  **********************************************************************************/
27 
28 //______________________________________________________________________________
29 //
30 // Deep Neural Network Implementation
31 //______________________________________________________________________________
32 
33 #include "TString.h"
34 #include "TTree.h"
35 #include "TFile.h"
36 #include "TFormula.h"
37 
38 #include "TMVA/ClassifierFactory.h"
39 #include "TMVA/Configurable.h"
40 #include "TMVA/IMethod.h"
41 #include "TMVA/MsgLogger.h"
42 #include "TMVA/MethodBase.h"
43 #include "TMVA/MethodDNN.h"
44 #include "TMVA/Timer.h"
45 #include "TMVA/Types.h"
46 #include "TMVA/Tools.h"
47 #include "TMVA/Config.h"
48 #include "TMVA/Ranking.h"
49 
50 #include "TMVA/DNN/Net.h"
52 
53 #include "TMVA/NeuralNet.h"
54 #include "TMVA/Monitoring.h"
55 
56 #include <algorithm>
57 #include <iostream>
58 #include <string>
59 #include <iomanip>
60 
61 REGISTER_METHOD(DNN)
62 
63 ClassImp(TMVA::MethodDNN)
64 
65 using TMVA::DNN::EActivationFunction;
66 using TMVA::DNN::ELossFunction;
67 using TMVA::DNN::EInitialization;
68 using TMVA::DNN::EOutputFunction;
69 
70 namespace TMVA
71 {
72 
73 //______________________________________________________________________________
74 TMVA::MethodDNN::MethodDNN(const TString& jobName,
75  const TString& methodTitle,
76  DataSetInfo& theData,
77  const TString& theOption)
78  : MethodBase( jobName, Types::kDNN, methodTitle, theData, theOption),
79  fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
80  fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
81  fTrainingSettings(), fResume(false), fSettings()
82 {
83  // standard constructor
84 }
85 
86 //______________________________________________________________________________
88  const TString& theWeightFile)
89  : MethodBase( Types::kDNN, theData, theWeightFile),
90  fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
91  fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
92  fTrainingSettings(), fResume(false), fSettings()
93 {
94  // constructor from a weight file
95 }
96 
97 //______________________________________________________________________________
99 {
100  // destructor
101  // nothing to be done
102 }
103 
104 //______________________________________________________________________________
106  UInt_t numberClasses,
107  UInt_t /*numberTargets*/ )
108 {
109  // MLP can handle classification with 2 classes and regression with
110  // one regression-target
111  if (type == Types::kClassification && numberClasses == 2 ) return kTRUE;
112  if (type == Types::kMulticlass ) return kTRUE;
113  if (type == Types::kRegression ) return kTRUE;
114 
115  return kFALSE;
116 }
117 
118 //______________________________________________________________________________
120 {
121  // default initializations
122 }
123 
124 //______________________________________________________________________________
126 {
127  // Options to be set in the option string:
128  //
129  // LearningRate <float> DNN learning rate parameter.
130  // DecayRate <float> Decay rate for learning parameter.
131  // TestRate <int> Period of validation set error computation.
132  // BatchSize <int> Number of event per batch.
133 
134  DeclareOptionRef(fLayoutString="SOFTSIGN|(N+100)*2,LINEAR",
135  "Layout",
136  "Layou of the network.");
137 
138  DeclareOptionRef(fErrorStrategy="CROSSENTROPY",
139  "ErrorStrategy",
140  "Loss function: Mean squared error (regression)"
141  " or cross entropy (binary classifcation).");
142  AddPreDefVal(TString("CROSSENTROPY"));
143  AddPreDefVal(TString("SUMOFSQUARES"));
144 
145  DeclareOptionRef(fWeightInitializationString="XAVIER",
146  "WeightInitialization",
147  "Weight initialization strategy");
148  AddPreDefVal(TString("XAVIER"));
149  AddPreDefVal(TString("XAVIERUNIFORM"));
150 
151  DeclareOptionRef(fArchitectureString="STANDARD",
152  "Architecture",
153  "Which architecture to perfrom the training on.");
154  AddPreDefVal(TString("STANDARD"));
155  AddPreDefVal(TString("CPU"));
156  AddPreDefVal(TString("GPU"));
157  AddPreDefVal(TString("OPENCL"));
158 
159  DeclareOptionRef(
160  fTrainingStrategyString = "LearningRate=1e-1,"
161  "Momentum=0.3,"
162  "Repetitions=3,"
163  "ConvergenceSteps=50,"
164  "BatchSize=30,"
165  "TestRepetitions=7,"
166  "WeightDecay=0.0,"
167  "Renormalize=L2,"
168  "DropConfig=0.0,"
169  "DropRepetitions=5|LearningRate=1e-4,"
170  "Momentum=0.3,"
171  "Repetitions=3,"
172  "ConvergenceSteps=50,"
173  "BatchSize=20,"
174  "TestRepetitions=7,"
175  "WeightDecay=0.001,"
176  "Renormalize=L2,"
177  "DropConfig=0.0+0.5+0.5,"
178  "DropRepetitions=5,"
179  "Multithreading=True",
180  "TrainingStrategy",
181  "Defines the training strategies.");
182 }
183 
184 //______________________________________________________________________________
185 auto TMVA::MethodDNN::ParseLayoutString(TString layoutString)
186  -> LayoutVector_t
187 {
188  // parse layout specification string and return a vector, each entry
189  // containing the number of neurons to go in each successive layer
190  LayoutVector_t layout;
191  const TString layerDelimiter(",");
192  const TString subDelimiter("|");
193 
194  const size_t inputSize = GetNvar();
195 
196  TObjArray* layerStrings = layoutString.Tokenize(layerDelimiter);
197  TIter nextLayer (layerStrings);
198  TObjString* layerString = (TObjString*)nextLayer ();
199 
200  for (; layerString != nullptr; layerString = (TObjString*) nextLayer()) {
201  int numNodes = 0;
202  EActivationFunction activationFunction = EActivationFunction::kTanh;
203 
204  TObjArray* subStrings = layerString->GetString().Tokenize(subDelimiter);
205  TIter nextToken (subStrings);
206  TObjString* token = (TObjString *) nextToken();
207  int idxToken = 0;
208  for (; token != nullptr; token = (TObjString *) nextToken()) {
209  switch (idxToken)
210  {
211  case 0:
212  {
213  TString strActFnc (token->GetString ());
214  if (strActFnc == "RELU") {
215  activationFunction = DNN::EActivationFunction::kRelu;
216  } else if (strActFnc == "TANH") {
217  activationFunction = DNN::EActivationFunction::kTanh;
218  } else if (strActFnc == "SYMMRELU") {
219  activationFunction = DNN::EActivationFunction::kSymmRelu;
220  } else if (strActFnc == "SOFTSIGN") {
221  activationFunction = DNN::EActivationFunction::kSoftSign;
222  } else if (strActFnc == "SIGMOID") {
223  activationFunction = DNN::EActivationFunction::kSigmoid;
224  } else if (strActFnc == "LINEAR") {
225  activationFunction = DNN::EActivationFunction::kIdentity;
226  } else if (strActFnc == "GAUSS") {
227  activationFunction = DNN::EActivationFunction::kGauss;
228  }
229  }
230  break;
231  case 1: // number of nodes
232  {
233  TString strNumNodes (token->GetString ());
234  TString strN ("x");
235  strNumNodes.ReplaceAll ("N", strN);
236  strNumNodes.ReplaceAll ("n", strN);
237  TFormula fml ("tmp",strNumNodes);
238  numNodes = fml.Eval (inputSize);
239  }
240  break;
241  }
242  ++idxToken;
243  }
244  layout.push_back(std::make_pair(numNodes, activationFunction));
245  }
246  return layout;
247 }
248 
249 // parse key value pairs in blocks -> return vector of blocks with map of key value pairs
250 //______________________________________________________________________________
251 auto TMVA::MethodDNN::ParseKeyValueString(TString parseString,
252  TString blockDelim,
253  TString tokenDelim)
255 {
256  KeyValueVector_t blockKeyValues;
257  const TString keyValueDelim ("=");
258 
259  TObjArray* blockStrings = parseString.Tokenize (blockDelim);
260  TIter nextBlock (blockStrings);
261  TObjString* blockString = (TObjString *) nextBlock();
262 
263  for (; blockString != nullptr; blockString = (TObjString *) nextBlock())
264  {
265  blockKeyValues.push_back (std::map<TString,TString>());
266  std::map<TString,TString>& currentBlock = blockKeyValues.back ();
267 
268  TObjArray* subStrings = blockString->GetString ().Tokenize (tokenDelim);
269  TIter nextToken (subStrings);
270  TObjString* token = (TObjString*)nextToken ();
271 
272  for (; token != nullptr; token = (TObjString *)nextToken())
273  {
274  TString strKeyValue (token->GetString ());
275  int delimPos = strKeyValue.First (keyValueDelim.Data ());
276  if (delimPos <= 0)
277  continue;
278 
279  TString strKey = TString (strKeyValue (0, delimPos));
280  strKey.ToUpper();
281  TString strValue = TString (strKeyValue (delimPos+1, strKeyValue.Length ()));
282 
283  strKey.Strip (TString::kBoth, ' ');
284  strValue.Strip (TString::kBoth, ' ');
285 
286  currentBlock.insert (std::make_pair (strKey, strValue));
287  }
288  }
289  return blockKeyValues;
290 }
291 
292 //______________________________________________________________________________
293 TString fetchValue (const std::map<TString, TString>& keyValueMap, TString key)
294 {
295  key.ToUpper ();
296  std::map<TString, TString>::const_iterator it = keyValueMap.find (key);
297  if (it == keyValueMap.end()) {
298  return TString ("");
299  }
300  return it->second;
301 }
302 
303 //______________________________________________________________________________
304 template <typename T>
305 T fetchValue(const std::map<TString,TString>& keyValueMap,
306  TString key,
307  T defaultValue);
308 
309 //______________________________________________________________________________
310 template <>
311 int fetchValue(const std::map<TString,TString>& keyValueMap,
312  TString key,
313  int defaultValue)
314 {
315  TString value (fetchValue (keyValueMap, key));
316  if (value == "") {
317  return defaultValue;
318  }
319  return value.Atoi ();
320 }
321 
322 //______________________________________________________________________________
323 template <>
324 double fetchValue (const std::map<TString,TString>& keyValueMap,
325  TString key, double defaultValue)
326 {
327  TString value (fetchValue (keyValueMap, key));
328  if (value == "") {
329  return defaultValue;
330  }
331  return value.Atof ();
332 }
333 
334 //______________________________________________________________________________
335 template <>
336 TString fetchValue (const std::map<TString,TString>& keyValueMap,
337  TString key, TString defaultValue)
338 {
339  TString value (fetchValue (keyValueMap, key));
340  if (value == "") {
341  return defaultValue;
342  }
343  return value;
344 }
345 
346 //______________________________________________________________________________
347 template <>
348 bool fetchValue (const std::map<TString,TString>& keyValueMap,
349  TString key, bool defaultValue)
350 {
351  TString value (fetchValue (keyValueMap, key));
352  if (value == "") {
353  return defaultValue;
354  }
355  value.ToUpper ();
356  if (value == "TRUE" || value == "T" || value == "1") {
357  return true;
358  }
359  return false;
360 }
361 
362 //______________________________________________________________________________
363 template <>
364 std::vector<double> fetchValue(const std::map<TString, TString> & keyValueMap,
365  TString key,
366  std::vector<double> defaultValue)
367 {
368  TString parseString (fetchValue (keyValueMap, key));
369  if (parseString == "") {
370  return defaultValue;
371  }
372  parseString.ToUpper ();
373  std::vector<double> values;
374 
375  const TString tokenDelim ("+");
376  TObjArray* tokenStrings = parseString.Tokenize (tokenDelim);
377  TIter nextToken (tokenStrings);
378  TObjString* tokenString = (TObjString*)nextToken ();
379  for (; tokenString != NULL; tokenString = (TObjString*)nextToken ()) {
380  std::stringstream sstr;
381  double currentValue;
382  sstr << tokenString->GetString ().Data ();
383  sstr >> currentValue;
384  values.push_back (currentValue);
385  }
386  return values;
387 }
388 
389 //______________________________________________________________________________
391 {
392  if (IgnoreEventsWithNegWeightsInTraining()) {
393  Log() << kINFO
394  << "Will ignore negative events in training!"
395  << Endl;
396  }
397 
398  //
399  // Set network structure.
400  //
401 
402  fLayout = TMVA::MethodDNN::ParseLayoutString (fLayoutString);
403  size_t inputSize = GetNVariables ();
404  size_t outputSize = 1;
405  if (GetNTargets() != 0) {
406  outputSize = GetNTargets();
407  } else if (DataInfo().GetNClasses() > 2) {
408  outputSize = DataInfo().GetNClasses();
409  }
410 
411  fNet.SetBatchSize(1);
412  fNet.SetInputWidth(inputSize);
413 
414  auto itLayout = std::begin (fLayout);
415  auto itLayoutEnd = std::end (fLayout)-1;
416  for ( ; itLayout != itLayoutEnd; ++itLayout) {
417  fNet.AddLayer((*itLayout).first, (*itLayout).second);
418  }
419  fNet.AddLayer(outputSize, EActivationFunction::kIdentity);
420 
421  //
422  // Loss function and output.
423  //
424 
425  fOutputFunction = EOutputFunction::kSigmoid;
426  if (fAnalysisType == Types::kClassification)
427  {
428  if (fErrorStrategy == "SUMOFSQUARES") {
429  fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
430  }
431  if (fErrorStrategy == "CROSSENTROPY") {
432  fNet.SetLossFunction(ELossFunction::kCrossEntropy);
433  }
434  fOutputFunction = EOutputFunction::kSigmoid;
435  } else if (fAnalysisType == Types::kRegression) {
436  if (fErrorStrategy != "SUMOFSQUARES") {
437  Log () << kWARNING << "For regression only SUMOFSQUARES is a valid "
438  << " neural net error function. Setting error function to "
439  << " SUMOFSQUARES now." << Endl;
440  }
441  fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
442  fOutputFunction = EOutputFunction::kIdentity;
443  } else if (fAnalysisType == Types::kMulticlass) {
444  if (fErrorStrategy == "SUMOFSQUARES") {
445  fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
446  }
447  if (fErrorStrategy == "CROSSENTROPY") {
448  fNet.SetLossFunction(ELossFunction::kCrossEntropy);
449  }
450  if (fErrorStrategy == "MUTUALEXCLUSIVE") {
451  fNet.SetLossFunction(ELossFunction::kSoftmaxCrossEntropy);
452  }
453  fOutputFunction = EOutputFunction::kSoftmax;
454  }
455 
456  //
457  // Initialization
458  //
459 
460  if (fWeightInitializationString == "XAVIER") {
461  fWeightInitialization = DNN::EInitialization::kGauss;
462  }
463  else if (fWeightInitializationString == "XAVIERUNIFORM") {
464  fWeightInitialization = DNN::EInitialization::kUniform;
465  }
466  else {
467  fWeightInitialization = DNN::EInitialization::kGauss;
468  }
469 
470  //
471  // Training settings.
472  //
473 
474  KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
475  TString ("|"),
476  TString (","));
477  for (auto& block : strategyKeyValues) {
478  TTrainingSettings settings;
479 
480  settings.convergenceSteps = fetchValue(block, "ConvergenceSteps", 100);
481  settings.batchSize = fetchValue(block, "BatchSize", 30);
482  settings.testInterval = fetchValue(block, "TestRepetitions", 7);
483  settings.weightDecay = fetchValue(block, "WeightDecay", 0.0);
484  settings.learningRate = fetchValue(block, "LearningRate", 1e-5);
485  settings.momentum = fetchValue(block, "Momentum", 0.3);
486  settings.dropoutProbabilities = fetchValue(block, "DropConfig",
487  std::vector<Double_t>());
488 
489  TString regularization = fetchValue(block, "Regularization",
490  TString ("NONE"));
491  if (regularization == "L1") {
493  } else if (regularization == "L2") {
495  }
496 
497  TString strMultithreading = fetchValue(block, "Multithreading",
498  TString ("True"));
499  if (strMultithreading.BeginsWith ("T")) {
500  settings.multithreading = true;
501  } else {
502  settings.multithreading = false;
503  }
504 
505  fTrainingSettings.push_back(settings);
506  }
507 }
508 
509 //______________________________________________________________________________
511 {
512  if (fInteractive && fInteractive->NotInitialized()){
513  std::vector<TString> titles = {"Error on training set", "Error on test set"};
514  fInteractive->Init(titles);
515  // JsMVA progress bar maximum (100%)
516  fIPyMaxIter = 100;
517  }
518 
519  if (fArchitectureString == "GPU") {
520  TrainGpu();
521  if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
522  ExitFromTraining();
523  return;
524  } else if (fArchitectureString == "OpenCL") {
525  Log() << kFATAL << "OpenCL backend not yes supported." << Endl;
526  return;
527  } else if (fArchitectureString == "CPU") {
528  TrainCpu();
529  if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
530  ExitFromTraining();
531  return;
532  }
533 
534  Log() << kINFO << "Using Standard Implementation.";
535 
536  std::vector<Pattern> trainPattern;
537  std::vector<Pattern> testPattern;
538 
539  const std::vector<TMVA::Event*>& eventCollectionTraining = GetEventCollection (Types::kTraining);
540  const std::vector<TMVA::Event*>& eventCollectionTesting = GetEventCollection (Types::kTesting);
541 
542  for (auto &event : eventCollectionTraining) {
543  const std::vector<Float_t>& values = event->GetValues();
544  if (fAnalysisType == Types::kClassification) {
545  double outputValue = event->GetClass () == 0 ? 0.9 : 0.1;
546  trainPattern.push_back(Pattern (values.begin(),
547  values.end(),
548  outputValue,
549  event->GetWeight()));
550  trainPattern.back().addInput(1.0);
551  } else if (fAnalysisType == Types::kMulticlass) {
552  std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
553  oneHot[event->GetClass()] = 1.0;
554  trainPattern.push_back(Pattern (values.begin(), values.end(),
555  oneHot.cbegin(), oneHot.cend(),
556  event->GetWeight()));
557  trainPattern.back().addInput(1.0);
558  } else {
559  const std::vector<Float_t>& targets = event->GetTargets ();
560  trainPattern.push_back(Pattern(values.begin(),
561  values.end(),
562  targets.begin(),
563  targets.end(),
564  event->GetWeight ()));
565  trainPattern.back ().addInput (1.0); // bias node
566  }
567  }
568 
569  for (auto &event : eventCollectionTesting) {
570  const std::vector<Float_t>& values = event->GetValues();
571  if (fAnalysisType == Types::kClassification) {
572  double outputValue = event->GetClass () == 0 ? 0.9 : 0.1;
573  testPattern.push_back(Pattern (values.begin(),
574  values.end(),
575  outputValue,
576  event->GetWeight()));
577  testPattern.back().addInput(1.0);
578  } else if (fAnalysisType == Types::kMulticlass) {
579  std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
580  oneHot[event->GetClass()] = 1.0;
581  testPattern.push_back(Pattern (values.begin(), values.end(),
582  oneHot.cbegin(), oneHot.cend(),
583  event->GetWeight()));
584  testPattern.back().addInput(1.0);
585  } else {
586  const std::vector<Float_t>& targets = event->GetTargets ();
587  testPattern.push_back(Pattern(values.begin(),
588  values.end(),
589  targets.begin(),
590  targets.end(),
591  event->GetWeight ()));
592  testPattern.back ().addInput (1.0); // bias node
593  }
594  }
595 
596  TMVA::DNN::Net net;
597  std::vector<double> weights;
598 
599  net.SetIpythonInteractive(fInteractive, &fExitFromTraining, &fIPyMaxIter, &fIPyCurrentIter);
600 
601  net.setInputSize(fNet.GetInputWidth() + 1);
602  net.setOutputSize(fNet.GetOutputWidth() + 1);
603 
604  for (size_t i = 0; i < fNet.GetDepth(); i++) {
605  EActivationFunction f = fNet.GetLayer(i).GetActivationFunction();
606  EnumFunction g = EnumFunction::LINEAR;
607  switch(f) {
608  case EActivationFunction::kIdentity: g = EnumFunction::LINEAR; break;
609  case EActivationFunction::kRelu: g = EnumFunction::RELU; break;
610  case EActivationFunction::kSigmoid: g = EnumFunction::SIGMOID; break;
611  case EActivationFunction::kTanh: g = EnumFunction::TANH; break;
612  case EActivationFunction::kSymmRelu: g = EnumFunction::SYMMRELU; break;
613  case EActivationFunction::kSoftSign: g = EnumFunction::SOFTSIGN; break;
614  case EActivationFunction::kGauss: g = EnumFunction::GAUSS; break;
615  }
616  if (i < fNet.GetDepth() - 1) {
617  net.addLayer(Layer(fNet.GetLayer(i).GetWidth(), g));
618  } else {
619  ModeOutputValues h = ModeOutputValues::DIRECT;
620  switch(fOutputFunction) {
621  case EOutputFunction::kIdentity: h = ModeOutputValues::DIRECT; break;
622  case EOutputFunction::kSigmoid: h = ModeOutputValues::SIGMOID; break;
623  case EOutputFunction::kSoftmax: h = ModeOutputValues::SOFTMAX; break;
624  }
625  net.addLayer(Layer(fNet.GetLayer(i).GetWidth(), g, h));
626  }
627  }
628 
629  switch(fNet.GetLossFunction()) {
630  case ELossFunction::kMeanSquaredError:
631  net.setErrorFunction(ModeErrorFunction::SUMOFSQUARES);
632  break;
634  net.setErrorFunction(ModeErrorFunction::CROSSENTROPY);
635  break;
636  case ELossFunction::kSoftmaxCrossEntropy:
637  net.setErrorFunction(ModeErrorFunction::CROSSENTROPY_MUTUALEXCLUSIVE);
638  break;
639  }
640 
641  switch(fWeightInitialization) {
642  case EInitialization::kGauss:
643  net.initializeWeights(WeightInitializationStrategy::XAVIER,
644  std::back_inserter(weights));
645  break;
646  case EInitialization::kUniform:
647  net.initializeWeights(WeightInitializationStrategy::XAVIERUNIFORM,
648  std::back_inserter(weights));
649  break;
650  default:
651  net.initializeWeights(WeightInitializationStrategy::XAVIER,
652  std::back_inserter(weights));
653  break;
654  }
655 
656  int idxSetting = 0;
657  for (auto s : fTrainingSettings) {
658 
660  switch(s.regularization) {
662  case ERegularization::kL1: r = EnumRegularization::L1; break;
663  case ERegularization::kL2: r = EnumRegularization::L2; break;
664  }
665 
666  Settings * settings = new Settings(TString(), s.convergenceSteps, s.batchSize,
667  s.testInterval, s.weightDecay, r,
668  MinimizerType::fSteepest, s.learningRate,
669  s.momentum, 1, s.multithreading);
670  std::shared_ptr<Settings> ptrSettings(settings);
671  ptrSettings->setMonitoring (0);
672  Log() << kINFO
673  << "Training with learning rate = " << ptrSettings->learningRate ()
674  << ", momentum = " << ptrSettings->momentum ()
675  << ", repetitions = " << ptrSettings->repetitions ()
676  << Endl;
677 
678  ptrSettings->setProgressLimits ((idxSetting)*100.0/(fSettings.size ()),
679  (idxSetting+1)*100.0/(fSettings.size ()));
680 
681  const std::vector<double>& dropConfig = ptrSettings->dropFractions ();
682  if (!dropConfig.empty ()) {
683  Log () << kINFO << "Drop configuration" << Endl
684  << " drop repetitions = " << ptrSettings->dropRepetitions()
685  << Endl;
686  }
687 
688  int idx = 0;
689  for (auto f : dropConfig) {
690  Log () << kINFO << " Layer " << idx << " = " << f << Endl;
691  ++idx;
692  }
693  Log () << kINFO << Endl;
694 
695  DNN::Steepest minimizer(ptrSettings->learningRate(),
696  ptrSettings->momentum(),
697  ptrSettings->repetitions());
698  net.train(weights, trainPattern, testPattern, minimizer, *ptrSettings.get());
699  ptrSettings.reset();
700  Log () << kINFO << Endl;
701  idxSetting++;
702  }
703  size_t weightIndex = 0;
704  for (size_t l = 0; l < fNet.GetDepth(); l++) {
705  auto & layerWeights = fNet.GetLayer(l).GetWeights();
706  for (Int_t j = 0; j < layerWeights.GetNcols(); j++) {
707  for (Int_t i = 0; i < layerWeights.GetNrows(); i++) {
708  layerWeights(i,j) = weights[weightIndex];
709  weightIndex++;
710  }
711  }
712  auto & layerBiases = fNet.GetLayer(l).GetBiases();
713  if (l == 0) {
714  for (Int_t i = 0; i < layerBiases.GetNrows(); i++) {
715  layerBiases(i,0) = weights[weightIndex];
716  weightIndex++;
717  }
718  } else {
719  for (Int_t i = 0; i < layerBiases.GetNrows(); i++) {
720  layerBiases(i,0) = 0.0;
721  }
722  }
723  }
724  if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
725  ExitFromTraining();
726 }
727 
728 //______________________________________________________________________________
730 {
731 
732 #ifdef DNNCUDA // Included only if DNNCUDA flag is set.
733 
734  size_t nTrainingSamples = GetEventCollection(Types::kTraining).size();
735  size_t nTestSamples = GetEventCollection(Types::kTesting).size();
736 
737  Log() << kINFO << "Start of neural network training on GPU." << Endl;
738 
739  size_t trainingPhase = 1;
740  fNet.Initialize(fWeightInitialization);
741  for (TTrainingSettings & settings : fTrainingSettings) {
742 
743  if (fInteractive){
744  fInteractive->ClearGraphs();
745  }
746 
747  TNet<TCuda<>> net(settings.batchSize, fNet);
748  net.SetWeightDecay(settings.weightDecay);
749  net.SetRegularization(settings.regularization);
750 
751  // Need to convert dropoutprobabilities to conventions used
752  // by backend implementation.
753  std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
754  for (auto & p : dropoutVector) {
755  p = 1.0 - p;
756  }
757  net.SetDropoutProbabilities(dropoutVector);
758 
759  net.InitializeGradients();
760  auto testNet = net.CreateClone(settings.batchSize);
761 
762  Log() << kINFO << "Training phase " << trainingPhase << " of "
763  << fTrainingSettings.size() << ":" << Endl;
764  trainingPhase++;
765 
766  using DataLoader_t = TDataLoader<TMVAInput_t, TCuda<>>;
767 
768  size_t nThreads = 1;
769  DataLoader_t trainingData(GetEventCollection(Types::kTraining),
770  nTrainingSamples,
771  net.GetBatchSize(),
772  net.GetInputWidth(),
773  net.GetOutputWidth(), nThreads);
774  DataLoader_t testData(GetEventCollection(Types::kTesting),
775  nTestSamples,
776  testNet.GetBatchSize(),
777  net.GetInputWidth(),
778  net.GetOutputWidth(), nThreads);
779  DNN::TGradientDescent<TCuda<>> minimizer(settings.learningRate,
780  settings.convergenceSteps,
781  settings.testInterval);
782 
783  std::vector<TNet<TCuda<>>> nets{};
784  std::vector<TBatch<TCuda<>>> batches{};
785  nets.reserve(nThreads);
786  for (size_t i = 0; i < nThreads; i++) {
787  nets.push_back(net);
788  for (size_t j = 0; j < net.GetDepth(); j++)
789  {
790  auto &masterLayer = net.GetLayer(j);
791  auto &layer = nets.back().GetLayer(j);
792  TCuda<>::Copy(layer.GetWeights(),
793  masterLayer.GetWeights());
794  TCuda<>::Copy(layer.GetBiases(),
795  masterLayer.GetBiases());
796  }
797  }
798 
799  bool converged = false;
800  size_t stepCount = 0;
801  size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
802 
803  std::chrono::time_point<std::chrono::system_clock> start, end;
804  start = std::chrono::system_clock::now();
805 
806  if (!fInteractive) {
807  Log() << std::setw(10) << "Epoch" << " | "
808  << std::setw(12) << "Train Err."
809  << std::setw(12) << "Test Err."
810  << std::setw(12) << "GFLOP/s"
811  << std::setw(12) << "Conv. Steps" << Endl;
812  std::string separator(62, '-');
813  Log() << separator << Endl;
814  }
815 
816  while (!converged)
817  {
818  stepCount++;
819 
820  // Perform minimization steps for a full epoch.
821  trainingData.Shuffle();
822  for (size_t i = 0; i < batchesInEpoch; i += nThreads) {
823  batches.clear();
824  for (size_t j = 0; j < nThreads; j++) {
825  batches.reserve(nThreads);
826  batches.push_back(trainingData.GetBatch());
827  }
828  if (settings.momentum > 0.0) {
829  minimizer.StepMomentum(net, nets, batches, settings.momentum);
830  } else {
831  minimizer.Step(net, nets, batches);
832  }
833  }
834 
835  if ((stepCount % minimizer.GetTestInterval()) == 0) {
836 
837  // Compute test error.
838  Double_t testError = 0.0;
839  for (auto batch : testData) {
840  auto inputMatrix = batch.GetInput();
841  auto outputMatrix = batch.GetOutput();
842  testError += testNet.Loss(inputMatrix, outputMatrix);
843  }
844  testError /= (Double_t) (nTestSamples / settings.batchSize);
845 
846  end = std::chrono::system_clock::now();
847 
848  // Compute training error.
849  Double_t trainingError = 0.0;
850  for (auto batch : trainingData) {
851  auto inputMatrix = batch.GetInput();
852  auto outputMatrix = batch.GetOutput();
853  trainingError += net.Loss(inputMatrix, outputMatrix);
854  }
855  trainingError /= (Double_t) (nTrainingSamples / settings.batchSize);
856 
857  // Compute numerical throughput.
858  std::chrono::duration<double> elapsed_seconds = end - start;
859  double seconds = elapsed_seconds.count();
860  double nFlops = (double) (settings.testInterval * batchesInEpoch);
861  nFlops *= net.GetNFlops() * 1e-9;
862 
863  converged = minimizer.HasConverged(testError);
864  start = std::chrono::system_clock::now();
865 
866  if (fInteractive) {
867  fInteractive->AddPoint(stepCount, trainingError, testError);
868  fIPyCurrentIter = 100.0 * minimizer.GetConvergenceCount()
869  / minimizer.GetConvergenceSteps ();
870  if (fExitFromTraining) break;
871  } else {
872  Log() << std::setw(10) << stepCount << " | "
873  << std::setw(12) << trainingError
874  << std::setw(12) << testError
875  << std::setw(12) << nFlops / seconds
876  << std::setw(12) << minimizer.GetConvergenceCount() << Endl;
877  if (converged) {
878  Log() << Endl;
879  }
880  }
881  }
882  }
883  for (size_t l = 0; l < net.GetDepth(); l++) {
884  fNet.GetLayer(l).GetWeights() = (TMatrixT<Double_t>) net.GetLayer(l).GetWeights();
885  fNet.GetLayer(l).GetBiases() = (TMatrixT<Double_t>) net.GetLayer(l).GetBiases();
886  }
887  }
888 
889 #else // DNNCUDA flag not set.
890 
891  Log() << kFATAL << "CUDA backend not enabled. Please make sure "
892  "you have CUDA installed and it was successfully "
893  "detected by CMAKE." << Endl;
894 #endif // DNNCUDA
895 }
896 
897 //______________________________________________________________________________
899 {
900 
901 #ifdef DNNCPU // Included only if DNNCPU flag is set.
902 
903  size_t nTrainingSamples = GetEventCollection(Types::kTraining).size();
904  size_t nTestSamples = GetEventCollection(Types::kTesting).size();
905 
906  Log() << kINFO << "Start of neural network training on CPU." << Endl << Endl;
907 
908  fNet.Initialize(fWeightInitialization);
909 
910  size_t trainingPhase = 1;
911  for (TTrainingSettings & settings : fTrainingSettings) {
912 
913  if (fInteractive){
914  fInteractive->ClearGraphs();
915  }
916 
917  Log() << "Training phase " << trainingPhase << " of "
918  << fTrainingSettings.size() << ":" << Endl;
919  trainingPhase++;
920 
921  TNet<TCpu<>> net(settings.batchSize, fNet);
922  net.SetWeightDecay(settings.weightDecay);
923  net.SetRegularization(settings.regularization);
924  // Need to convert dropoutprobabilities to conventions used
925  // by backend implementation.
926  std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
927  for (auto & p : dropoutVector) {
928  p = 1.0 - p;
929  }
930  net.SetDropoutProbabilities(dropoutVector);
931  net.SetDropoutProbabilities(settings.dropoutProbabilities);
932  net.InitializeGradients();
933  auto testNet = net.CreateClone(settings.batchSize);
934 
935  using DataLoader_t = TDataLoader<TMVAInput_t, TCpu<>>;
936 
937  size_t nThreads = 1;
938  DataLoader_t trainingData(GetEventCollection(Types::kTraining),
939  nTrainingSamples,
940  net.GetBatchSize(),
941  net.GetInputWidth(),
942  net.GetOutputWidth(), nThreads);
943  DataLoader_t testData(GetEventCollection(Types::kTesting),
944  nTestSamples,
945  testNet.GetBatchSize(),
946  net.GetInputWidth(),
947  net.GetOutputWidth(), nThreads);
948  DNN::TGradientDescent<TCpu<>> minimizer(settings.learningRate,
949  settings.convergenceSteps,
950  settings.testInterval);
951 
952  std::vector<TNet<TCpu<>>> nets{};
953  std::vector<TBatch<TCpu<>>> batches{};
954  nets.reserve(nThreads);
955  for (size_t i = 0; i < nThreads; i++) {
956  nets.push_back(net);
957  for (size_t j = 0; j < net.GetDepth(); j++)
958  {
959  auto &masterLayer = net.GetLayer(j);
960  auto &layer = nets.back().GetLayer(j);
961  TCpu<>::Copy(layer.GetWeights(),
962  masterLayer.GetWeights());
963  TCpu<>::Copy(layer.GetBiases(),
964  masterLayer.GetBiases());
965  }
966  }
967 
968  bool converged = false;
969  size_t stepCount = 0;
970  size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
971 
972  std::chrono::time_point<std::chrono::system_clock> start, end;
973  start = std::chrono::system_clock::now();
974 
975  if (fInteractive) {
976  Log() << std::setw(10) << "Epoch" << " | "
977  << std::setw(12) << "Train Err."
978  << std::setw(12) << "Test Err."
979  << std::setw(12) << "GFLOP/s"
980  << std::setw(12) << "Conv. Steps" << Endl;
981  std::string separator(62, '-');
982  Log() << separator << Endl;
983  }
984 
985  while (!converged)
986  {
987  stepCount++;
988  // Perform minimization steps for a full epoch.
989  trainingData.Shuffle();
990  for (size_t i = 0; i < batchesInEpoch; i += nThreads) {
991  batches.clear();
992  for (size_t j = 0; j < nThreads; j++) {
993  batches.reserve(nThreads);
994  batches.push_back(trainingData.GetBatch());
995  }
996  if (settings.momentum > 0.0) {
997  minimizer.StepMomentum(net, nets, batches, settings.momentum);
998  } else {
999  minimizer.Step(net, nets, batches);
1000  }
1001  }
1002 
1003  if ((stepCount % minimizer.GetTestInterval()) == 0) {
1004 
1005  // Compute test error.
1006  Double_t testError = 0.0;
1007  for (auto batch : testData) {
1008  auto inputMatrix = batch.GetInput();
1009  auto outputMatrix = batch.GetOutput();
1010  testError += testNet.Loss(inputMatrix, outputMatrix);
1011  }
1012  testError /= (Double_t) (nTestSamples / settings.batchSize);
1013 
1014  end = std::chrono::system_clock::now();
1015 
1016  // Compute training error.
1017  Double_t trainingError = 0.0;
1018  for (auto batch : trainingData) {
1019  auto inputMatrix = batch.GetInput();
1020  auto outputMatrix = batch.GetOutput();
1021  trainingError += net.Loss(inputMatrix, outputMatrix);
1022  }
1023  trainingError /= (Double_t) (nTrainingSamples / settings.batchSize);
1024 
1025  if (fInteractive){
1026  fInteractive->AddPoint(stepCount, trainingError, testError);
1027  fIPyCurrentIter = 100*(double)minimizer.GetConvergenceCount() /(double)settings.convergenceSteps;
1028  if (fExitFromTraining) break;
1029  }
1030 
1031  // Compute numerical throughput.
1032  std::chrono::duration<double> elapsed_seconds = end - start;
1033  double seconds = elapsed_seconds.count();
1034  double nFlops = (double) (settings.testInterval * batchesInEpoch);
1035  nFlops *= net.GetNFlops() * 1e-9;
1036 
1037  converged = minimizer.HasConverged(testError);
1038  start = std::chrono::system_clock::now();
1039 
1040  if (fInteractive) {
1041  fInteractive->AddPoint(stepCount, trainingError, testError);
1042  fIPyCurrentIter = 100.0 * minimizer.GetConvergenceCount()
1043  / minimizer.GetConvergenceSteps ();
1044  if (fExitFromTraining) break;
1045  } else {
1046  Log() << std::setw(10) << stepCount << " | "
1047  << std::setw(12) << trainingError
1048  << std::setw(12) << testError
1049  << std::setw(12) << nFlops / seconds
1050  << std::setw(12) << minimizer.GetConvergenceCount() << Endl;
1051  if (converged) {
1052  Log() << Endl;
1053  }
1054  }
1055  }
1056  }
1057 
1058 
1059  for (size_t l = 0; l < net.GetDepth(); l++) {
1060  auto & layer = fNet.GetLayer(l);
1061  layer.GetWeights() = (TMatrixT<Double_t>) net.GetLayer(l).GetWeights();
1062  layer.GetBiases() = (TMatrixT<Double_t>) net.GetLayer(l).GetBiases();
1063  }
1064  }
1065 
1066 #else // DNNCPU flag not set.
1067  Log() << kFATAL << "Multi-core CPU backend not enabled. Please make sure "
1068  "you have a BLAS implementation and it was successfully "
1069  "detected by CMake as well that the imt CMake flag is set." << Endl;
1070 #endif // DNNCPU
1071 }
1072 
1073 //______________________________________________________________________________
1075 {
1076  size_t nVariables = GetEvent()->GetNVariables();
1077  Matrix_t X(1, nVariables);
1078  Matrix_t YHat(1, 1);
1079 
1080  const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1081  for (size_t i = 0; i < nVariables; i++) {
1082  X(0,i) = inputValues[i];
1083  }
1084 
1085  fNet.Prediction(YHat, X, fOutputFunction);
1086  return YHat(0,0);
1087 }
1088 
1089 //______________________________________________________________________________
1090 const std::vector<Float_t> & TMVA::MethodDNN::GetRegressionValues()
1091 {
1092  size_t nVariables = GetEvent()->GetNVariables();
1093  Matrix_t X(1, nVariables);
1094 
1095  const Event *ev = GetEvent();
1096  const std::vector<Float_t>& inputValues = ev->GetValues();
1097  for (size_t i = 0; i < nVariables; i++) {
1098  X(0,i) = inputValues[i];
1099  }
1100 
1101  size_t nTargets = std::max(1u, ev->GetNTargets());
1102  Matrix_t YHat(1, nTargets);
1103  std::vector<Float_t> output(nTargets);
1104  auto net = fNet.CreateClone(1);
1105  net.Prediction(YHat, X, fOutputFunction);
1106 
1107  for (size_t i = 0; i < nTargets; i++)
1108  output[i] = YHat(0, i);
1109 
1110  if (fRegressionReturnVal == NULL) {
1111  fRegressionReturnVal = new std::vector<Float_t>();
1112  }
1113  fRegressionReturnVal->clear();
1114 
1115  Event * evT = new Event(*ev);
1116  for (size_t i = 0; i < nTargets; ++i) {
1117  evT->SetTarget(i, output[i]);
1118  }
1119 
1120  const Event* evT2 = GetTransformationHandler().InverseTransform(evT);
1121  for (size_t i = 0; i < nTargets; ++i) {
1122  fRegressionReturnVal->push_back(evT2->GetTarget(i));
1123  }
1124  delete evT;
1125  return *fRegressionReturnVal;
1126 }
1127 
1128 const std::vector<Float_t> & TMVA::MethodDNN::GetMulticlassValues()
1129 {
1130  size_t nVariables = GetEvent()->GetNVariables();
1131  Matrix_t X(1, nVariables);
1132  Matrix_t YHat(1, DataInfo().GetNClasses());
1133  if (fMulticlassReturnVal == NULL) {
1134  fMulticlassReturnVal = new std::vector<Float_t>(DataInfo().GetNClasses());
1135  }
1136 
1137  const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1138  for (size_t i = 0; i < nVariables; i++) {
1139  X(0,i) = inputValues[i];
1140  }
1141 
1142  fNet.Prediction(YHat, X, fOutputFunction);
1143  for (size_t i = 0; i < (size_t) YHat.GetNcols(); i++) {
1144  (*fMulticlassReturnVal)[i] = YHat(0, i);
1145  }
1146  return *fMulticlassReturnVal;
1147 }
1148 
1149 //______________________________________________________________________________
1150 void TMVA::MethodDNN::AddWeightsXMLTo( void* parent ) const
1151 {
1152  void* nn = gTools().xmlengine().NewChild(parent, 0, "Weights");
1153  Int_t inputWidth = fNet.GetInputWidth();
1154  Int_t depth = fNet.GetDepth();
1155  char lossFunction = static_cast<char>(fNet.GetLossFunction());
1156  gTools().xmlengine().NewAttr(nn, 0, "InputWidth",
1157  gTools().StringFromInt(inputWidth));
1158  gTools().xmlengine().NewAttr(nn, 0, "Depth", gTools().StringFromInt(depth));
1159  gTools().xmlengine().NewAttr(nn, 0, "LossFunction", TString(lossFunction));
1160  gTools().xmlengine().NewAttr(nn, 0, "OutputFunction",
1161  TString(static_cast<char>(fOutputFunction)));
1162 
1163  for (Int_t i = 0; i < depth; i++) {
1164  const auto& layer = fNet.GetLayer(i);
1165  auto layerxml = gTools().xmlengine().NewChild(nn, 0, "Layer");
1166  int activationFunction = static_cast<int>(layer.GetActivationFunction());
1167  gTools().xmlengine().NewAttr(layerxml, 0, "ActivationFunction",
1168  TString::Itoa(activationFunction, 10));
1169  WriteMatrixXML(layerxml, "Weights", layer.GetWeights());
1170  WriteMatrixXML(layerxml, "Biases", layer.GetBiases());
1171  }
1172 }
1173 
1174 //______________________________________________________________________________
1176 {
1177  auto netXML = gTools().GetChild(rootXML, "Weights");
1178  if (!netXML){
1179  netXML = rootXML;
1180  }
1181 
1182  fNet.Clear();
1183  fNet.SetBatchSize(1);
1184 
1185  size_t inputWidth, depth;
1186  gTools().ReadAttr(netXML, "InputWidth", inputWidth);
1187  gTools().ReadAttr(netXML, "Depth", depth);
1188  char lossFunctionChar;
1189  gTools().ReadAttr(netXML, "LossFunction", lossFunctionChar);
1190  char outputFunctionChar;
1191  gTools().ReadAttr(netXML, "OutputFunction", outputFunctionChar);
1192 
1193  fNet.SetInputWidth(inputWidth);
1194  fNet.SetLossFunction(static_cast<ELossFunction>(lossFunctionChar));
1195  fOutputFunction = static_cast<EOutputFunction>(outputFunctionChar);
1196 
1197  size_t previousWidth = inputWidth;
1198  auto layerXML = gTools().xmlengine().GetChild(netXML, "Layer");
1199  for (size_t i = 0; i < depth; i++) {
1200  TString fString;
1201  EActivationFunction f;
1202 
1203  // Read activation function.
1204  gTools().ReadAttr(layerXML, "ActivationFunction", fString);
1205  f = static_cast<EActivationFunction>(fString.Atoi());
1206 
1207  // Read number of neurons.
1208  size_t width;
1209  auto matrixXML = gTools().GetChild(layerXML, "Weights");
1210  gTools().ReadAttr(matrixXML, "rows", width);
1211 
1212  fNet.AddLayer(width, f);
1213  TMatrixT<Double_t> weights(width, previousWidth);
1214  TMatrixT<Double_t> biases(width, 1);
1215  ReadMatrixXML(layerXML, "Weights", weights);
1216  ReadMatrixXML(layerXML, "Biases", biases);
1217  fNet.GetLayer(i).GetWeights() = weights;
1218  fNet.GetLayer(i).GetBiases() = biases;
1219 
1220  layerXML = gTools().GetNextChild(layerXML);
1221  previousWidth = width;
1222  }
1223 }
1224 
1225 //______________________________________________________________________________
1226 void TMVA::MethodDNN::ReadWeightsFromStream( std::istream & /*istr*/)
1227 {
1228 }
1229 
1230 //______________________________________________________________________________
1232 {
1233  fRanking = new Ranking( GetName(), "Importance" );
1234  for (UInt_t ivar=0; ivar<GetNvar(); ivar++) {
1235  fRanking->AddRank( Rank( GetInputLabel(ivar), 1.0));
1236  }
1237  return fRanking;
1238 }
1239 
1240 //______________________________________________________________________________
1241 void TMVA::MethodDNN::MakeClassSpecific( std::ostream& /*fout*/,
1242  const TString& /*className*/ ) const
1243 {
1244 }
1245 
1246 //______________________________________________________________________________
1248 {
1249  // get help message text
1250  //
1251  // typical length of text line:
1252  // "|--------------------------------------------------------------|"
1253  TString col = gConfig().WriteOptionsReference() ? TString() : gTools().Color("bold");
1254  TString colres = gConfig().WriteOptionsReference() ? TString() : gTools().Color("reset");
1255 
1256  Log() << Endl;
1257  Log() << col << "--- Short description:" << colres << Endl;
1258  Log() << Endl;
1259  Log() << "The DNN neural network is a feedforward" << Endl;
1260  Log() << "multilayer perceptron impementation. The DNN has a user-" << Endl;
1261  Log() << "defined hidden layer architecture, where the number of input (output)" << Endl;
1262  Log() << "nodes is determined by the input variables (output classes, i.e., " << Endl;
1263  Log() << "signal and one background, regression or multiclass). " << Endl;
1264  Log() << Endl;
1265  Log() << col << "--- Performance optimisation:" << colres << Endl;
1266  Log() << Endl;
1267 
1268  const char* txt = "The DNN supports various options to improve performance in terms of training speed and \n \
1269 reduction of overfitting: \n \
1270 \n \
1271  - different training settings can be stacked. Such that the initial training \n\
1272  is done with a large learning rate and a large drop out fraction whilst \n \
1273  in a later stage learning rate and drop out can be reduced. \n \
1274  - drop out \n \
1275  [recommended: \n \
1276  initial training stage: 0.0 for the first layer, 0.5 for later layers. \n \
1277  later training stage: 0.1 or 0.0 for all layers \n \
1278  final training stage: 0.0] \n \
1279  Drop out is a technique where a at each training cycle a fraction of arbitrary \n \
1280  nodes is disabled. This reduces co-adaptation of weights and thus reduces overfitting. \n \
1281  - L1 and L2 regularization are available \n \
1282  - Minibatches \n \
1283  [recommended 10 - 150] \n \
1284  Arbitrary mini-batch sizes can be chosen. \n \
1285  - Multithreading \n \
1286  [recommended: True] \n \
1287  Multithreading can be turned on. The minibatches are distributed to the available \n \
1288  cores. The algorithm is lock-free (\"Hogwild!\"-style) for each cycle. \n \
1289  \n \
1290  Options: \n \
1291  \"Layout\": \n \
1292  - example: \"TANH|(N+30)*2,TANH|(N+30),LINEAR\" \n \
1293  - meaning: \n \
1294  . two hidden layers (separated by \",\") \n \
1295  . the activation function is TANH (other options: RELU, SOFTSIGN, LINEAR) \n \
1296  . the activation function for the output layer is LINEAR \n \
1297  . the first hidden layer has (N+30)*2 nodes where N is the number of input neurons \n \
1298  . the second hidden layer has N+30 nodes, where N is the number of input neurons \n \
1299  . the number of nodes in the output layer is determined by the number of output nodes \n \
1300  and can therefore not be chosen freely. \n \
1301  \n \
1302  \"ErrorStrategy\": \n \
1303  - SUMOFSQUARES \n \
1304  The error of the neural net is determined by a sum-of-squares error function \n \
1305  For regression, this is the only possible choice. \n \
1306  - CROSSENTROPY \n \
1307  The error of the neural net is determined by a cross entropy function. The \n \
1308  output values are automatically (internally) transformed into probabilities \n \
1309  using a sigmoid function. \n \
1310  For signal/background classification this is the default choice. \n \
1311  For multiclass using cross entropy more than one or no output classes \n \
1312  can be equally true or false (e.g. Event 0: A and B are true, Event 1: \n \
1313  A and C is true, Event 2: C is true, ...) \n \
1314  - MUTUALEXCLUSIVE \n \
1315  In multiclass settings, exactly one of the output classes can be true (e.g. either A or B or C) \n \
1316  \n \
1317  \"WeightInitialization\" \n \
1318  - XAVIER \n \
1319  [recommended] \n \
1320  \"Xavier Glorot & Yoshua Bengio\"-style of initializing the weights. The weights are chosen randomly \n \
1321  such that the variance of the values of the nodes is preserved for each layer. \n \
1322  - XAVIERUNIFORM \n \
1323  The same as XAVIER, but with uniformly distributed weights instead of gaussian weights \n \
1324  - LAYERSIZE \n \
1325  Random values scaled by the layer size \n \
1326  \n \
1327  \"TrainingStrategy\" \n \
1328  - example: \"LearningRate=1e-1,Momentum=0.3,ConvergenceSteps=50,BatchSize=30,TestRepetitions=7,WeightDecay=0.0,Renormalize=L2,DropConfig=0.0,DropRepetitions=5|LearningRate=1e-4,Momentum=0.3,ConvergenceSteps=50,BatchSize=20,TestRepetitions=7,WeightDecay=0.001,Renormalize=L2,DropFraction=0.0,DropRepetitions=5\" \n \
1329  - explanation: two stacked training settings separated by \"|\" \n \
1330  . first training setting: \"LearningRate=1e-1,Momentum=0.3,ConvergenceSteps=50,BatchSize=30,TestRepetitions=7,WeightDecay=0.0,Renormalize=L2,DropConfig=0.0,DropRepetitions=5\" \n \
1331  . second training setting : \"LearningRate=1e-4,Momentum=0.3,ConvergenceSteps=50,BatchSize=20,TestRepetitions=7,WeightDecay=0.001,Renormalize=L2,DropFractions=0.0,DropRepetitions=5\" \n \
1332  . LearningRate : \n \
1333  - recommended for classification: 0.1 initially, 1e-4 later \n \
1334  - recommended for regression: 1e-4 and less \n \
1335  . Momentum : \n \
1336  preserve a fraction of the momentum for the next training batch [fraction = 0.0 - 1.0] \n \
1337  . Repetitions : \n \
1338  train \"Repetitions\" repetitions with the same minibatch before switching to the next one \n \
1339  . ConvergenceSteps : \n \
1340  Assume that convergence is reached after \"ConvergenceSteps\" cycles where no improvement \n \
1341  of the error on the test samples has been found. (Mind that only at each \"TestRepetitions\" \n \
1342  cycle the test sampes are evaluated and thus the convergence is checked) \n \
1343  . BatchSize \n \
1344  Size of the mini-batches. \n \
1345  . TestRepetitions \n \
1346  Perform testing the neural net on the test samples each \"TestRepetitions\" cycle \n \
1347  . WeightDecay \n \
1348  If \"Renormalize\" is set to L1 or L2, \"WeightDecay\" provides the renormalization factor \n \
1349  . Renormalize \n \
1350  NONE, L1 (|w|) or L2 (w^2) \n \
1351  . DropConfig \n \
1352  Drop a fraction of arbitrary nodes of each of the layers according to the values given \n \
1353  in the DropConfig. \n \
1354  [example: DropConfig=0.0+0.5+0.3 \n \
1355  meaning: drop no nodes in layer 0 (input layer), half of the nodes in layer 1 and 30% of the nodes \n \
1356  in layer 2 \n \
1357  recommended: leave all the nodes turned on for the input layer (layer 0) \n \
1358  turn off half of the nodes in later layers for the initial training; leave all nodes \n \
1359  turned on (0.0) in later training stages] \n \
1360  . DropRepetitions \n \
1361  Each \"DropRepetitions\" cycle the configuration of which nodes are dropped is changed \n \
1362  [recommended : 1] \n \
1363  . Multithreading \n \
1364  turn on multithreading [recommended: True] \n \
1365  \n";
1366  Log () << txt << Endl;
1367 }
1368 
1369 } // namespace TMVA
Config & gConfig()
Definition: Config.cxx:43
std::string GetName(const std::string &scope_name)
Definition: Cppyy.cxx:140
size_t GetOutputWidth() const
Definition: Net.h:143
An array of TObjects.
Definition: TObjArray.h:39
TXMLEngine & xmlengine()
Definition: Tools.h:278
static TString Itoa(Int_t value, Int_t base)
Converts an Int_t to a TString with respect to the base specified (2-36).
Definition: TString.cxx:2069
MsgLogger & Endl(MsgLogger &ml)
Definition: MsgLogger.h:162
void ProcessOptions()
Definition: MethodDNN.cxx:390
Double_t Eval(Double_t x) const
Definition: TFormula.cxx:2546
Double_t Log(Double_t x)
Definition: TMath.h:526
Collectable string class.
Definition: TObjString.h:32
UInt_t GetNTargets() const
accessor to the number of targets
Definition: Event.cxx:316
Steepest Gradient Descent algorithm (SGD)
Definition: NeuralNet.h:334
double T(double x)
Definition: ChebyshevPol.h:34
void SetDropoutProbabilities(const std::vector< Double_t > &probabilities)
Definition: Net.h:380
TH1 * h
Definition: legend2.C:5
EAnalysisType
Definition: Types.h:129
void GetHelpMessage() const
Definition: MethodDNN.cxx:1247
void setErrorFunction(ModeErrorFunction eErrorFunction)
which error function is to be used
Definition: NeuralNet.h:1103
size_t GetBatchSize() const
Definition: Net.h:137
typename Architecture_t::Matrix_t Matrix_t
Definition: MethodDNN.h:83
Scalar_t GetNFlops()
Definition: Net.h:349
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
void MakeClassSpecific(std::ostream &, const TString &) const
Definition: MethodDNN.cxx:1241
const Bool_t kFALSE
Definition: Rtypes.h:92
Definition: Pattern.h:7
void setOutputSize(size_t sizeOutput)
set the output size of the DNN
Definition: NeuralNet.h:1100
void SetWeightDecay(Scalar_t weightDecay)
Definition: Net.h:151
neural net
Definition: NeuralNet.h:1068
size_t GetDepth() const
Definition: Net.h:136
EInitialization
Definition: Functions.h:70
Tools & gTools()
Definition: Tools.cxx:79
std::vector< std::map< TString, TString >> KeyValueVector_t
Definition: MethodDNN.h:88
void ReadWeightsFromStream(std::istream &i)
Definition: MethodDNN.cxx:1226
static const std::string separator("@@@")
void SetIpythonInteractive(IPythonInteractive *fI, bool *fE, UInt_t *M, UInt_t *C)
Definition: NeuralNet.h:1290
std::vector< Double_t > dropoutProbabilities
Definition: MethodDNN.h:99
void ReadWeightsFromXML(void *wghtnode)
Definition: MethodDNN.cxx:1175
void * GetChild(void *parent, const char *childname=0)
get child node
Definition: Tools.cxx:1158
void setInputSize(size_t sizeInput)
set the input size of the DNN
Definition: NeuralNet.h:1099
Generic neural network class.
Definition: Net.h:49
void initializeWeights(WeightInitializationStrategy eInitStrategy, OutIterator itWeight)
initialize the weights with the given strategy
Definition: NeuralNet.icc:1468
virtual ~MethodDNN()
Definition: MethodDNN.cxx:98
TString GetString() const
Definition: TObjString.h:50
TRandom2 r(17)
TDataLoader.
Definition: DataLoader.h:73
The F O R M U L A class.
Definition: TFormula.h:89
const Ranking * CreateRanking()
Definition: MethodDNN.cxx:1231
void SetRegularization(ERegularization R)
Definition: Net.h:149
unsigned int UInt_t
Definition: RtypesCore.h:42
size_t GetInputWidth() const
Definition: Net.h:142
const Handle_t kNone
Definition: GuiTypes.h:89
virtual Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets)
Definition: MethodDNN.cxx:105
auto regularization(const typename Architecture_t::Matrix_t &A, ERegularization R) -> decltype(Architecture_t::L1Regularization(A))
Evaluate the regularization functional for a given weight matrix.
Definition: Functions.h:213
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
Definition: Event.cxx:356
TLine * l
Definition: textangle.C:4
void ReadAttr(void *node, const char *, T &value)
Definition: Tools.h:296
Settings for the training of the neural net.
Definition: NeuralNet.h:736
TNet< Architecture_t, TSharedLayer< Architecture_t > > CreateClone(size_t batchSize)
Create a clone that uses the same weight and biases matrices but potentially a difference batch size...
Definition: Net.h:211
Layer defines the layout of a layer.
Definition: NeuralNet.h:676
std::vector< std::pair< int, EActivationFunction >> LayoutVector_t
Definition: MethodDNN.h:87
XMLAttrPointer_t NewAttr(XMLNodePointer_t xmlnode, XMLNsPointer_t, const char *name, const char *value)
creates new attribute for xmlnode, namespaces are not supported for attributes
Definition: TXMLEngine.cxx:488
KeyValueVector_t ParseKeyValueString(TString parseString, TString blockDelim, TString tokenDelim)
Definition: MethodDNN.cxx:251
#define NONE
Definition: Rotated.cxx:52
void Copy(void *source, void *dest)
#define ClassImp(name)
Definition: Rtypes.h:279
double f(double x)
ModeOutputValues
Definition: NeuralNet.h:179
double Double_t
Definition: RtypesCore.h:55
TString fetchValue(const std::map< TString, TString > &keyValueMap, TString key)
Definition: MethodDNN.cxx:293
double train(std::vector< double > &weights, std::vector< Pattern > &trainPattern, const std::vector< Pattern > &testPattern, Minimizer &minimizer, Settings &settings)
start the training
Definition: NeuralNet.icc:705
EOutputFunction
Enum that represents output functions.
Definition: Functions.h:43
int type
Definition: TGX11.cxx:120
ELossFunction
Enum that represents objective functions for the net, i.e.
Definition: Functions.h:54
void * GetNextChild(void *prevchild, const char *childname=0)
XML helpers.
Definition: Tools.cxx:1170
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Definition: TRolke.cxx:630
void DeclareOptions()
Definition: MethodDNN.cxx:125
const TString & Color(const TString &)
human readable color strings
Definition: Tools.cxx:837
Float_t GetTarget(UInt_t itgt) const
Definition: Event.h:104
#define REGISTER_METHOD(CLASS)
for example
void addLayer(Layer &layer)
add a layer (layout)
Definition: NeuralNet.h:1101
std::vector< Float_t > & GetValues()
Definition: Event.h:96
virtual Double_t GetMvaValue(Double_t *err=0, Double_t *errUpper=0)
Definition: MethodDNN.cxx:1074
void InitializeGradients()
Initialize the gradients in the net to zero.
Definition: Net.h:262
XMLNodePointer_t GetChild(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
returns first child of xml node
Definition: TXMLEngine.cxx:993
MethodDNN(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption)
Definition: MethodDNN.cxx:74
XMLNodePointer_t NewChild(XMLNodePointer_t parent, XMLNsPointer_t ns, const char *name, const char *content=0)
create new child element for parent node
Definition: TXMLEngine.cxx:614
LayoutVector_t ParseLayoutString(TString layerSpec)
Definition: MethodDNN.cxx:185
#define NULL
Definition: Rtypes.h:82
EActivationFunction
Enum that represents layer activation functions.
Definition: Functions.h:31
Bool_t WriteOptionsReference() const
Definition: Config.h:66
const int nn
EnumRegularization
Definition: NeuralNet.h:173
virtual const std::vector< Float_t > & GetMulticlassValues()
Definition: MethodDNN.cxx:1128
const Bool_t kTRUE
Definition: Rtypes.h:91
virtual const std::vector< Float_t > & GetRegressionValues()
Definition: MethodDNN.cxx:1090
void AddWeightsXMLTo(void *parent) const
Definition: MethodDNN.cxx:1150
Scalar_t Loss(const Matrix_t &Y, bool includeRegularization=false) const
Evaluate the loss function of the net using the activations that are currently stored in the output l...
Definition: Net.h:305
Layer_t & GetLayer(size_t i)
Definition: Net.h:138
if(line.BeginsWith("/*"))
Definition: HLFactory.cxx:443