Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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 * *
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 * (see tmva/doc/LICENSE) *
26 **********************************************************************************/
27
28/*! \class TMVA::MethodDNN
29\ingroup TMVA
30Deep Neural Network Implementation.
31*/
32
33#include "TMVA/MethodDNN.h"
34
35#include "TString.h"
36#include "TFormula.h"
37#include "TObjString.h"
38
40#include "TMVA/Configurable.h"
41#include "TMVA/IMethod.h"
42#include "TMVA/MsgLogger.h"
43#include "TMVA/MethodBase.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#ifdef R__HAS_TMVACPU
58#endif
59#ifdef R__HAS_TMVAGPU
61#endif
62
63#include <algorithm>
64#include <iostream>
65#include <string>
66#include <iomanip>
67#include <chrono>
68
70
71
72namespace TMVA
73{
74 using namespace DNN;
75
76 ////////////////////////////////////////////////////////////////////////////////
77 /// standard constructor
78
79 TMVA::MethodDNN::MethodDNN(const TString &jobName, const TString &methodTitle, DataSetInfo &theData,
80 const TString &theOption)
81 : MethodBase(jobName, Types::kDNN, methodTitle, theData, theOption), fWeightInitialization(), fOutputFunction(),
82 fLayoutString(), fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
83 fArchitectureString(), fTrainingSettings(), fResume(false), fSettings()
84 {
85}
86
87////////////////////////////////////////////////////////////////////////////////
88/// constructor from a weight file
89
92 : MethodBase( Types::kDNN, theData, theWeightFile),
93 fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
94 fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
95 fTrainingSettings(), fResume(false), fSettings()
96{
97 fWeightInitialization = DNN::EInitialization::kGauss;
98 fOutputFunction = DNN::EOutputFunction::kSigmoid;
99}
100
101////////////////////////////////////////////////////////////////////////////////
102/// destructor
103
105{
108}
109
110////////////////////////////////////////////////////////////////////////////////
111/// MLP can handle classification with 2 classes and regression with
112/// one regression-target
113
116 UInt_t /*numberTargets*/ )
117{
118 if (type == Types::kClassification && numberClasses == 2 ) return kTRUE;
119 if (type == Types::kMulticlass ) return kTRUE;
120 if (type == Types::kRegression ) return kTRUE;
121
122 return kFALSE;
123}
124
125////////////////////////////////////////////////////////////////////////////////
126/// default initializations
127
129 Log() << kWARNING
130 << "MethodDNN is deprecated and it will be removed in future ROOT version. "
131 "Please use MethodDL ( TMVA::kDL)"
132 << Endl;
133
134}
135
136////////////////////////////////////////////////////////////////////////////////
137/// Options to be set in the option string:
138///
139/// - LearningRate <float> DNN learning rate parameter.
140/// - DecayRate <float> Decay rate for learning parameter.
141/// - TestRate <int> Period of validation set error computation.
142/// - BatchSize <int> Number of event per batch.
143///
144/// - ValidationSize <string> How many events to use for validation. "0.2"
145/// or "20%" indicates that a fifth of the
146/// training data should be used. "100"
147/// indicates that 100 events should be used.
148
150{
151
152 DeclareOptionRef(fLayoutString="SOFTSIGN|(N+100)*2,LINEAR",
153 "Layout",
154 "Layout of the network.");
155
156 DeclareOptionRef(fValidationSize = "20%", "ValidationSize",
157 "Part of the training data to use for "
158 "validation. Specify as 0.2 or 20% to use a "
159 "fifth of the data set as validation set. "
160 "Specify as 100 to use exactly 100 events. "
161 "(Default: 20%)");
162
163 DeclareOptionRef(fErrorStrategy="CROSSENTROPY",
164 "ErrorStrategy",
165 "Loss function: Mean squared error (regression)"
166 " or cross entropy (binary classification).");
167 AddPreDefVal(TString("CROSSENTROPY"));
168 AddPreDefVal(TString("SUMOFSQUARES"));
169 AddPreDefVal(TString("MUTUALEXCLUSIVE"));
170
171 DeclareOptionRef(fWeightInitializationString="XAVIER",
172 "WeightInitialization",
173 "Weight initialization strategy");
174 AddPreDefVal(TString("XAVIER"));
175 AddPreDefVal(TString("XAVIERUNIFORM"));
176
177 DeclareOptionRef(fArchitectureString = "CPU", "Architecture", "Which architecture to perform the training on.");
178 AddPreDefVal(TString("STANDARD"));
179 AddPreDefVal(TString("CPU"));
180 AddPreDefVal(TString("GPU"));
181 AddPreDefVal(TString("OPENCL"));
182
183 DeclareOptionRef(
184 fTrainingStrategyString = "LearningRate=1e-1,"
185 "Momentum=0.3,"
186 "Repetitions=3,"
187 "ConvergenceSteps=50,"
188 "BatchSize=30,"
189 "TestRepetitions=7,"
190 "WeightDecay=0.0,"
191 "Renormalize=L2,"
192 "DropConfig=0.0,"
193 "DropRepetitions=5|LearningRate=1e-4,"
194 "Momentum=0.3,"
195 "Repetitions=3,"
196 "ConvergenceSteps=50,"
197 "BatchSize=20,"
198 "TestRepetitions=7,"
199 "WeightDecay=0.001,"
200 "Renormalize=L2,"
201 "DropConfig=0.0+0.5+0.5,"
202 "DropRepetitions=5,"
203 "Multithreading=True",
204 "TrainingStrategy",
205 "Defines the training strategies.");
206}
207
208////////////////////////////////////////////////////////////////////////////////
209/// parse layout specification string and return a vector, each entry
210/// containing the number of neurons to go in each successive layer
211
213 -> LayoutVector_t
214{
215 LayoutVector_t layout;
216 const TString layerDelimiter(",");
217 const TString subDelimiter("|");
218
219 const size_t inputSize = GetNvar();
220
224
225 for (; layerString != nullptr; layerString = (TObjString*) nextLayer()) {
226 int numNodes = 0;
227 EActivationFunction activationFunction = EActivationFunction::kTanh;
228
229 TObjArray* subStrings = layerString->GetString().Tokenize(subDelimiter);
231 TObjString* token = (TObjString *) nextToken();
232 int idxToken = 0;
233 for (; token != nullptr; token = (TObjString *) nextToken()) {
234 switch (idxToken)
235 {
236 case 0:
237 {
238 TString strActFnc (token->GetString ());
239 if (strActFnc == "RELU") {
240 activationFunction = DNN::EActivationFunction::kRelu;
241 } else if (strActFnc == "TANH") {
242 activationFunction = DNN::EActivationFunction::kTanh;
243 } else if (strActFnc == "SYMMRELU") {
244 activationFunction = DNN::EActivationFunction::kSymmRelu;
245 } else if (strActFnc == "SOFTSIGN") {
246 activationFunction = DNN::EActivationFunction::kSoftSign;
247 } else if (strActFnc == "SIGMOID") {
248 activationFunction = DNN::EActivationFunction::kSigmoid;
249 } else if (strActFnc == "LINEAR") {
250 activationFunction = DNN::EActivationFunction::kIdentity;
251 } else if (strActFnc == "GAUSS") {
252 activationFunction = DNN::EActivationFunction::kGauss;
253 }
254 }
255 break;
256 case 1: // number of nodes
257 {
258 TString strNumNodes (token->GetString ());
259 TString strN ("x");
260 strNumNodes.ReplaceAll ("N", strN);
261 strNumNodes.ReplaceAll ("n", strN);
262 TFormula fml ("tmp",strNumNodes);
263 numNodes = fml.Eval (inputSize);
264 }
265 break;
266 }
267 ++idxToken;
268 }
269 layout.push_back(std::make_pair(numNodes, activationFunction));
270 }
271 return layout;
272}
273
274////////////////////////////////////////////////////////////////////////////////
275/// parse key value pairs in blocks -> return vector of blocks with map of key value pairs
276
280 -> KeyValueVector_t
281{
282 KeyValueVector_t blockKeyValues;
283 const TString keyValueDelim ("=");
284
288
289 for (; blockString != nullptr; blockString = (TObjString *) nextBlock())
290 {
291 blockKeyValues.push_back (std::map<TString,TString>());
292 std::map<TString,TString>& currentBlock = blockKeyValues.back ();
293
294 TObjArray* subStrings = blockString->GetString ().Tokenize (tokenDelim);
296 TObjString* token = (TObjString*)nextToken ();
297
298 for (; token != nullptr; token = (TObjString *)nextToken())
299 {
300 TString strKeyValue (token->GetString ());
301 int delimPos = strKeyValue.First (keyValueDelim.Data ());
302 if (delimPos <= 0)
303 continue;
304
306 strKey.ToUpper();
308
309 strKey.Strip (TString::kBoth, ' ');
310 strValue.Strip (TString::kBoth, ' ');
311
312 currentBlock.insert (std::make_pair (strKey, strValue));
313 }
314 }
315 return blockKeyValues;
316}
317
318////////////////////////////////////////////////////////////////////////////////
319
320TString fetchValue (const std::map<TString, TString>& keyValueMap, TString key)
321{
322 key.ToUpper ();
323 std::map<TString, TString>::const_iterator it = keyValueMap.find (key);
324 if (it == keyValueMap.end()) {
325 return TString ("");
326 }
327 return it->second;
328}
329
330////////////////////////////////////////////////////////////////////////////////
331
332template <typename T>
333T fetchValue(const std::map<TString,TString>& keyValueMap,
334 TString key,
335 T defaultValue);
336
337////////////////////////////////////////////////////////////////////////////////
338
339template <>
340int fetchValue(const std::map<TString,TString>& keyValueMap,
341 TString key,
342 int defaultValue)
343{
345 if (value == "") {
346 return defaultValue;
347 }
348 return value.Atoi ();
349}
350
351////////////////////////////////////////////////////////////////////////////////
352
353template <>
354double fetchValue (const std::map<TString,TString>& keyValueMap,
355 TString key, double defaultValue)
356{
358 if (value == "") {
359 return defaultValue;
360 }
361 return value.Atof ();
362}
363
364////////////////////////////////////////////////////////////////////////////////
365
366template <>
367TString fetchValue (const std::map<TString,TString>& keyValueMap,
368 TString key, TString defaultValue)
369{
371 if (value == "") {
372 return defaultValue;
373 }
374 return value;
375}
376
377////////////////////////////////////////////////////////////////////////////////
378
379template <>
380bool fetchValue (const std::map<TString,TString>& keyValueMap,
381 TString key, bool defaultValue)
382{
384 if (value == "") {
385 return defaultValue;
386 }
387 value.ToUpper ();
388 if (value == "TRUE" || value == "T" || value == "1") {
389 return true;
390 }
391 return false;
392}
393
394////////////////////////////////////////////////////////////////////////////////
395
396template <>
397std::vector<double> fetchValue(const std::map<TString, TString> & keyValueMap,
398 TString key,
399 std::vector<double> defaultValue)
400{
402 if (parseString == "") {
403 return defaultValue;
404 }
405 parseString.ToUpper ();
406 std::vector<double> values;
407
408 const TString tokenDelim ("+");
412 for (; tokenString != NULL; tokenString = (TObjString*)nextToken ()) {
413 std::stringstream sstr;
414 double currentValue;
415 sstr << tokenString->GetString ().Data ();
417 values.push_back (currentValue);
418 }
419 return values;
420}
421
422////////////////////////////////////////////////////////////////////////////////
423
425{
426 if (IgnoreEventsWithNegWeightsInTraining()) {
427 Log() << kINFO
428 << "Will ignore negative events in training!"
429 << Endl;
430 }
431
432 if (fArchitectureString == "STANDARD") {
433 Log() << kERROR << "The STANDARD architecture has been deprecated. "
434 "Please use Architecture=CPU or Architecture=CPU."
435 "See the TMVA Users' Guide for instructions if you "
436 "encounter problems."
437 << Endl;
438 Log() << kFATAL << "The STANDARD architecture has been deprecated. "
439 "Please use Architecture=CPU or Architecture=CPU."
440 "See the TMVA Users' Guide for instructions if you "
441 "encounter problems."
442 << Endl;
443 }
444
445 if (fArchitectureString == "OPENCL") {
446 Log() << kERROR << "The OPENCL architecture has not been implemented yet. "
447 "Please use Architecture=CPU or Architecture=CPU for the "
448 "time being. See the TMVA Users' Guide for instructions "
449 "if you encounter problems."
450 << Endl;
451 Log() << kFATAL << "The OPENCL architecture has not been implemented yet. "
452 "Please use Architecture=CPU or Architecture=CPU for the "
453 "time being. See the TMVA Users' Guide for instructions "
454 "if you encounter problems."
455 << Endl;
456 }
457
458 if (fArchitectureString == "GPU") {
459#ifndef DNNCUDA // Included only if DNNCUDA flag is _not_ set.
460 Log() << kERROR << "CUDA backend not enabled. Please make sure "
461 "you have CUDA installed and it was successfully "
462 "detected by CMAKE."
463 << Endl;
464 Log() << kFATAL << "CUDA backend not enabled. Please make sure "
465 "you have CUDA installed and it was successfully "
466 "detected by CMAKE."
467 << Endl;
468#endif // DNNCUDA
469 }
470
471 if (fArchitectureString == "CPU") {
472#ifndef DNNCPU // Included only if DNNCPU flag is _not_ set.
473 Log() << kERROR << "Multi-core CPU backend not enabled. Please make sure "
474 "you have a BLAS implementation and it was successfully "
475 "detected by CMake as well that the imt CMake flag is set."
476 << Endl;
477 Log() << kFATAL << "Multi-core CPU backend not enabled. Please make sure "
478 "you have a BLAS implementation and it was successfully "
479 "detected by CMake as well that the imt CMake flag is set."
480 << Endl;
481#endif // DNNCPU
482 }
483
484 //
485 // Set network structure.
486 //
487
488 fLayout = TMVA::MethodDNN::ParseLayoutString (fLayoutString);
489 size_t inputSize = GetNVariables ();
490 size_t outputSize = 1;
491 if (fAnalysisType == Types::kRegression && GetNTargets() != 0) {
492 outputSize = GetNTargets();
493 } else if (fAnalysisType == Types::kMulticlass && DataInfo().GetNClasses() >= 2) {
494 outputSize = DataInfo().GetNClasses();
495 }
496
497 fNet.SetBatchSize(1);
498 fNet.SetInputWidth(inputSize);
499
500 auto itLayout = std::begin (fLayout);
501 auto itLayoutEnd = std::end (fLayout)-1;
502 for ( ; itLayout != itLayoutEnd; ++itLayout) {
503 fNet.AddLayer((*itLayout).first, (*itLayout).second);
504 }
505 fNet.AddLayer(outputSize, EActivationFunction::kIdentity);
506
507 //
508 // Loss function and output.
509 //
510
511 fOutputFunction = EOutputFunction::kSigmoid;
512 if (fAnalysisType == Types::kClassification)
513 {
514 if (fErrorStrategy == "SUMOFSQUARES") {
515 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
516 }
517 if (fErrorStrategy == "CROSSENTROPY") {
518 fNet.SetLossFunction(ELossFunction::kCrossEntropy);
519 }
520 fOutputFunction = EOutputFunction::kSigmoid;
521 } else if (fAnalysisType == Types::kRegression) {
522 if (fErrorStrategy != "SUMOFSQUARES") {
523 Log () << kWARNING << "For regression only SUMOFSQUARES is a valid "
524 << " neural net error function. Setting error function to "
525 << " SUMOFSQUARES now." << Endl;
526 }
527 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
528 fOutputFunction = EOutputFunction::kIdentity;
529 } else if (fAnalysisType == Types::kMulticlass) {
530 if (fErrorStrategy == "SUMOFSQUARES") {
531 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
532 }
533 if (fErrorStrategy == "CROSSENTROPY") {
534 fNet.SetLossFunction(ELossFunction::kCrossEntropy);
535 }
536 if (fErrorStrategy == "MUTUALEXCLUSIVE") {
537 fNet.SetLossFunction(ELossFunction::kSoftmaxCrossEntropy);
538 }
539 fOutputFunction = EOutputFunction::kSoftmax;
540 }
541
542 //
543 // Initialization
544 //
545
546 if (fWeightInitializationString == "XAVIER") {
547 fWeightInitialization = DNN::EInitialization::kGauss;
548 }
549 else if (fWeightInitializationString == "XAVIERUNIFORM") {
550 fWeightInitialization = DNN::EInitialization::kUniform;
551 }
552 else {
553 fWeightInitialization = DNN::EInitialization::kGauss;
554 }
555
556 //
557 // Training settings.
558 //
559
560 // Force validation of the ValidationSize option
561 GetNumValidationSamples();
562
563 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
564 TString ("|"),
565 TString (","));
566
567 std::cout << "Parsed Training DNN string " << fTrainingStrategyString << std::endl;
568 std::cout << "STring has size " << strategyKeyValues.size() << std::endl;
569 for (auto& block : strategyKeyValues) {
571
572 settings.convergenceSteps = fetchValue(block, "ConvergenceSteps", 100);
573 settings.batchSize = fetchValue(block, "BatchSize", 30);
574 settings.testInterval = fetchValue(block, "TestRepetitions", 7);
575 settings.weightDecay = fetchValue(block, "WeightDecay", 0.0);
576 settings.learningRate = fetchValue(block, "LearningRate", 1e-5);
577 settings.momentum = fetchValue(block, "Momentum", 0.3);
578 settings.dropoutProbabilities = fetchValue(block, "DropConfig",
579 std::vector<Double_t>());
580
581 TString regularization = fetchValue(block, "Regularization",
582 TString ("NONE"));
583 if (regularization == "L1") {
584 settings.regularization = DNN::ERegularization::kL1;
585 } else if (regularization == "L2") {
586 settings.regularization = DNN::ERegularization::kL2;
587 } else {
588 settings.regularization = DNN::ERegularization::kNone;
589 }
590
591 TString strMultithreading = fetchValue(block, "Multithreading",
592 TString ("True"));
593 if (strMultithreading.BeginsWith ("T")) {
594 settings.multithreading = true;
595 } else {
596 settings.multithreading = false;
597 }
598
599 fTrainingSettings.push_back(settings);
600 }
601}
602
603////////////////////////////////////////////////////////////////////////////////
604/// Validation of the ValidationSize option. Allowed formats are 20%, 0.2 and
605/// 100 etc.
606/// - 20% and 0.2 selects 20% of the training set as validation data.
607/// - 100 selects 100 events as the validation data.
608///
609/// @return number of samples in validation set
610///
611
613{
615 UInt_t trainingSetSize = GetEventCollection(Types::kTraining).size();
616
617 // Parsing + Validation
618 // --------------------
619 if (fValidationSize.EndsWith("%")) {
620 // Relative spec. format 20%
621 TString intValStr = TString(fValidationSize.Strip(TString::kTrailing, '%'));
622
623 if (intValStr.IsFloat()) {
624 Double_t valSizeAsDouble = fValidationSize.Atof() / 100.0;
625 nValidationSamples = GetEventCollection(Types::kTraining).size() * valSizeAsDouble;
626 } else {
627 Log() << kFATAL << "Cannot parse number \"" << fValidationSize
628 << "\". Expected string like \"20%\" or \"20.0%\"." << Endl;
629 }
630 } else if (fValidationSize.IsFloat()) {
631 Double_t valSizeAsDouble = fValidationSize.Atof();
632
633 if (valSizeAsDouble < 1.0) {
634 // Relative spec. format 0.2
635 nValidationSamples = GetEventCollection(Types::kTraining).size() * valSizeAsDouble;
636 } else {
637 // Absolute spec format 100 or 100.0
639 }
640 } else {
641 Log() << kFATAL << "Cannot parse number \"" << fValidationSize << "\". Expected string like \"0.2\" or \"100\"."
642 << Endl;
643 }
644
645 // Value validation
646 // ----------------
647 if (nValidationSamples < 0) {
648 Log() << kFATAL << "Validation size \"" << fValidationSize << "\" is negative." << Endl;
649 }
650
651 if (nValidationSamples == 0) {
652 Log() << kFATAL << "Validation size \"" << fValidationSize << "\" is zero." << Endl;
653 }
654
656 Log() << kFATAL << "Validation size \"" << fValidationSize
657 << "\" is larger than or equal in size to training set (size=\"" << trainingSetSize << "\")." << Endl;
658 }
659
660 return nValidationSamples;
661}
662
663////////////////////////////////////////////////////////////////////////////////
664
666{
667 for (TTrainingSettings & settings : fTrainingSettings) {
668 size_t nValidationSamples = GetNumValidationSamples();
669 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
671
672 if (nTrainingSamples < settings.batchSize ||
673 nValidationSamples < settings.batchSize ||
674 nTestSamples < settings.batchSize) {
675 Log() << kFATAL << "Number of samples in the datasets are train: "
676 << nTrainingSamples << " valid: " << nValidationSamples
677 << " test: " << nTestSamples << ". "
678 << "One of these is smaller than the batch size of "
679 << settings.batchSize << ". Please increase the batch"
680 << " size to be at least the same size as the smallest"
681 << " of these values." << Endl;
682 }
683 }
684
685 if (fArchitectureString == "GPU") {
686 TrainGpu();
687 return;
688 } else if (fArchitectureString == "OpenCL") {
689 Log() << kFATAL << "OpenCL backend not yet supported." << Endl;
690 return;
691 } else if (fArchitectureString == "CPU") {
692 TrainCpu();
693 return;
694 }
695
696 Log() << kINFO << "Using Standard Implementation.";
697
698 std::vector<Pattern> trainPattern;
699 std::vector<Pattern> testPattern;
700
701 size_t nValidationSamples = GetNumValidationSamples();
702 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
703
704 const std::vector<TMVA::Event *> &allData = GetEventCollection(Types::kTraining);
705 const std::vector<TMVA::Event *> eventCollectionTraining{allData.begin(), allData.begin() + nTrainingSamples};
706 const std::vector<TMVA::Event *> eventCollectionTesting{allData.begin() + nTrainingSamples, allData.end()};
707
708 for (auto &event : eventCollectionTraining) {
709 const std::vector<Float_t>& values = event->GetValues();
710 if (fAnalysisType == Types::kClassification) {
711 double outputValue = event->GetClass () == 0 ? 0.9 : 0.1;
712 trainPattern.push_back(Pattern (values.begin(),
713 values.end(),
715 event->GetWeight()));
716 trainPattern.back().addInput(1.0);
717 } else if (fAnalysisType == Types::kMulticlass) {
718 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
719 oneHot[event->GetClass()] = 1.0;
720 trainPattern.push_back(Pattern (values.begin(), values.end(),
721 oneHot.cbegin(), oneHot.cend(),
722 event->GetWeight()));
723 trainPattern.back().addInput(1.0);
724 } else {
725 const std::vector<Float_t>& targets = event->GetTargets ();
726 trainPattern.push_back(Pattern(values.begin(),
727 values.end(),
728 targets.begin(),
729 targets.end(),
730 event->GetWeight ()));
731 trainPattern.back ().addInput (1.0); // bias node
732 }
733 }
734
735 for (auto &event : eventCollectionTesting) {
736 const std::vector<Float_t>& values = event->GetValues();
737 if (fAnalysisType == Types::kClassification) {
738 double outputValue = event->GetClass () == 0 ? 0.9 : 0.1;
739 testPattern.push_back(Pattern (values.begin(),
740 values.end(),
742 event->GetWeight()));
743 testPattern.back().addInput(1.0);
744 } else if (fAnalysisType == Types::kMulticlass) {
745 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
746 oneHot[event->GetClass()] = 1.0;
747 testPattern.push_back(Pattern (values.begin(), values.end(),
748 oneHot.cbegin(), oneHot.cend(),
749 event->GetWeight()));
750 testPattern.back().addInput(1.0);
751 } else {
752 const std::vector<Float_t>& targets = event->GetTargets ();
753 testPattern.push_back(Pattern(values.begin(),
754 values.end(),
755 targets.begin(),
756 targets.end(),
757 event->GetWeight ()));
758 testPattern.back ().addInput (1.0); // bias node
759 }
760 }
761
763 std::vector<double> weights;
764
765 net.setInputSize(fNet.GetInputWidth() + 1);
766 net.setOutputSize(fNet.GetOutputWidth() + 1);
767
768 for (size_t i = 0; i < fNet.GetDepth(); i++) {
769 EActivationFunction f = fNet.GetLayer(i).GetActivationFunction();
770 EnumFunction g = EnumFunction::LINEAR;
771 switch(f) {
772 case EActivationFunction::kIdentity: g = EnumFunction::LINEAR; break;
773 case EActivationFunction::kRelu: g = EnumFunction::RELU; break;
774 case EActivationFunction::kSigmoid: g = EnumFunction::SIGMOID; break;
775 case EActivationFunction::kTanh: g = EnumFunction::TANH; break;
776 case EActivationFunction::kFastTanh: g = EnumFunction::TANH; break;
777 case EActivationFunction::kSymmRelu: g = EnumFunction::SYMMRELU; break;
778 case EActivationFunction::kSoftSign: g = EnumFunction::SOFTSIGN; break;
779 case EActivationFunction::kGauss: g = EnumFunction::GAUSS; break;
780 }
781 if (i < fNet.GetDepth() - 1) {
782 net.addLayer(Layer(fNet.GetLayer(i).GetWidth(), g));
783 } else {
784 ModeOutputValues h = ModeOutputValues::DIRECT;
785 switch(fOutputFunction) {
786 case EOutputFunction::kIdentity: h = ModeOutputValues::DIRECT; break;
787 case EOutputFunction::kSigmoid: h = ModeOutputValues::SIGMOID; break;
788 case EOutputFunction::kSoftmax: h = ModeOutputValues::SOFTMAX; break;
789 }
790 net.addLayer(Layer(fNet.GetLayer(i).GetWidth(), g, h));
791 }
792 }
793
794 switch(fNet.GetLossFunction()) {
795 case ELossFunction::kMeanSquaredError:
796 net.setErrorFunction(ModeErrorFunction::SUMOFSQUARES);
797 break;
798 case ELossFunction::kCrossEntropy:
799 net.setErrorFunction(ModeErrorFunction::CROSSENTROPY);
800 break;
801 case ELossFunction::kSoftmaxCrossEntropy:
802 net.setErrorFunction(ModeErrorFunction::CROSSENTROPY_MUTUALEXCLUSIVE);
803 break;
804 }
805
806 switch(fWeightInitialization) {
807 case EInitialization::kGauss:
808 net.initializeWeights(WeightInitializationStrategy::XAVIER,
809 std::back_inserter(weights));
810 break;
811 case EInitialization::kUniform:
812 net.initializeWeights(WeightInitializationStrategy::XAVIERUNIFORM,
813 std::back_inserter(weights));
814 break;
815 default:
816 net.initializeWeights(WeightInitializationStrategy::XAVIER,
817 std::back_inserter(weights));
818 break;
819 }
820
821 int idxSetting = 0;
822 for (auto s : fTrainingSettings) {
823
824 EnumRegularization r = EnumRegularization::NONE;
825 switch(s.regularization) {
826 case ERegularization::kNone: r = EnumRegularization::NONE; break;
827 case ERegularization::kL1: r = EnumRegularization::L1; break;
828 case ERegularization::kL2: r = EnumRegularization::L2; break;
829 }
830
831 Settings * settings = new Settings(TString(), s.convergenceSteps, s.batchSize,
832 s.testInterval, s.weightDecay, r,
833 MinimizerType::fSteepest, s.learningRate,
834 s.momentum, 1, s.multithreading);
835 std::shared_ptr<Settings> ptrSettings(settings);
836 ptrSettings->setMonitoring (0);
837 Log() << kINFO
838 << "Training with learning rate = " << ptrSettings->learningRate ()
839 << ", momentum = " << ptrSettings->momentum ()
840 << ", repetitions = " << ptrSettings->repetitions ()
841 << Endl;
842
843 ptrSettings->setProgressLimits ((idxSetting)*100.0/(fSettings.size ()),
844 (idxSetting+1)*100.0/(fSettings.size ()));
845
846 const std::vector<double>& dropConfig = ptrSettings->dropFractions ();
847 if (!dropConfig.empty ()) {
848 Log () << kINFO << "Drop configuration" << Endl
849 << " drop repetitions = " << ptrSettings->dropRepetitions()
850 << Endl;
851 }
852
853 int idx = 0;
854 for (auto f : dropConfig) {
855 Log () << kINFO << " Layer " << idx << " = " << f << Endl;
856 ++idx;
857 }
858 Log () << kINFO << Endl;
859
860 DNN::Steepest minimizer(ptrSettings->learningRate(),
861 ptrSettings->momentum(),
862 ptrSettings->repetitions());
863 net.train(weights, trainPattern, testPattern, minimizer, *ptrSettings.get());
864 ptrSettings.reset();
865 Log () << kINFO << Endl;
866 idxSetting++;
867 }
868 size_t weightIndex = 0;
869 for (size_t l = 0; l < fNet.GetDepth(); l++) {
870 auto & layerWeights = fNet.GetLayer(l).GetWeights();
871 for (Int_t j = 0; j < layerWeights.GetNcols(); j++) {
872 for (Int_t i = 0; i < layerWeights.GetNrows(); i++) {
873 layerWeights(i,j) = weights[weightIndex];
874 weightIndex++;
875 }
876 }
877 auto & layerBiases = fNet.GetLayer(l).GetBiases();
878 if (l == 0) {
879 for (Int_t i = 0; i < layerBiases.GetNrows(); i++) {
880 layerBiases(i,0) = weights[weightIndex];
881 weightIndex++;
882 }
883 } else {
884 for (Int_t i = 0; i < layerBiases.GetNrows(); i++) {
885 layerBiases(i,0) = 0.0;
886 }
887 }
888 }
889}
890
891////////////////////////////////////////////////////////////////////////////////
892
894{
895
896#ifdef DNNCUDA // Included only if DNNCUDA flag is set.
897 Log() << kINFO << "Start of neural network training on GPU." << Endl << Endl;
898
899 size_t nValidationSamples = GetNumValidationSamples();
900 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
902
903 Log() << kDEBUG << "Using " << nValidationSamples << " validation samples." << Endl;
904 Log() << kDEBUG << "Using " << nTestSamples << " training samples." << Endl;
905
906 size_t trainingPhase = 1;
907 fNet.Initialize(fWeightInitialization);
908 for (TTrainingSettings & settings : fTrainingSettings) {
909
910 TNet<TCuda<>> net(settings.batchSize, fNet);
911 net.SetWeightDecay(settings.weightDecay);
912 net.SetRegularization(settings.regularization);
913
914 // Need to convert dropoutprobabilities to conventions used
915 // by backend implementation.
916 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
917 for (auto & p : dropoutVector) {
918 p = 1.0 - p;
919 }
920 net.SetDropoutProbabilities(dropoutVector);
921
922 net.InitializeGradients();
923 auto testNet = net.CreateClone(settings.batchSize);
924
925 Log() << kINFO << "Training phase " << trainingPhase << " of "
926 << fTrainingSettings.size() << ":" << Endl;
928
930
931 // Split training data into training and validation set
932 const std::vector<Event *> &allData = GetEventCollection(Types::kTraining);
933 const std::vector<Event *> trainingInputData =
934 std::vector<Event *>(allData.begin(), allData.begin() + nTrainingSamples);
935 const std::vector<Event *> testInputData =
936 std::vector<Event *>(allData.begin() + nTrainingSamples, allData.end());
937
938 if (trainingInputData.size() != nTrainingSamples) {
939 Log() << kFATAL << "Inconsistent training sample size" << Endl;
940 }
941 if (testInputData.size() != nTestSamples) {
942 Log() << kFATAL << "Inconsistent test sample size" << Endl;
943 }
944
945 size_t nThreads = 1;
946 TMVAInput_t trainingTuple = std::tie(trainingInputData, DataInfo());
947 TMVAInput_t testTuple = std::tie(testInputData, DataInfo());
949 net.GetBatchSize(), net.GetInputWidth(),
950 net.GetOutputWidth(), nThreads);
952 net.GetInputWidth(), net.GetOutputWidth(),
953 nThreads);
954 DNN::TGradientDescent<TCuda<>> minimizer(settings.learningRate,
955 settings.convergenceSteps,
956 settings.testInterval);
957
958 std::vector<TNet<TCuda<>>> nets{};
959 std::vector<TBatch<TCuda<>>> batches{};
960 nets.reserve(nThreads);
961 for (size_t i = 0; i < nThreads; i++) {
962 nets.push_back(net);
963 for (size_t j = 0; j < net.GetDepth(); j++)
964 {
965 auto &masterLayer = net.GetLayer(j);
966 auto &layer = nets.back().GetLayer(j);
967 TCuda<>::Copy(layer.GetWeights(),
968 masterLayer.GetWeights());
969 TCuda<>::Copy(layer.GetBiases(),
970 masterLayer.GetBiases());
971 }
972 }
973
974 bool converged = false;
975 size_t stepCount = 0;
976 size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
977
978 std::chrono::time_point<std::chrono::system_clock> start, end;
979 start = std::chrono::system_clock::now();
980
981 Log() << std::setw(10) << "Epoch" << " | "
982 << std::setw(12) << "Train Err."
983 << std::setw(12) << "Test Err."
984 << std::setw(12) << "GFLOP/s"
985 << std::setw(12) << "Conv. Steps" << Endl;
986 std::string separator(62, '-');
987 Log() << separator << Endl;
988
989 while (!converged)
990 {
991 stepCount++;
992
993 // Perform minimization steps for a full epoch.
994 trainingData.Shuffle();
995 for (size_t i = 0; i < batchesInEpoch; i += nThreads) {
996 batches.clear();
997 for (size_t j = 0; j < nThreads; j++) {
998 batches.reserve(nThreads);
999 batches.push_back(trainingData.GetBatch());
1000 }
1001 if (settings.momentum > 0.0) {
1002 minimizer.StepMomentum(net, nets, batches, settings.momentum);
1003 } else {
1004 minimizer.Step(net, nets, batches);
1005 }
1006 }
1007
1008 if ((stepCount % minimizer.GetTestInterval()) == 0) {
1009
1010 // Compute test error.
1011 Double_t testError = 0.0;
1012 for (auto batch : testData) {
1013 auto inputMatrix = batch.GetInput();
1014 auto outputMatrix = batch.GetOutput();
1015 testError += testNet.Loss(inputMatrix, outputMatrix);
1016 }
1017 testError /= (Double_t) (nTestSamples / settings.batchSize);
1018
1019 //Log the loss value
1020 fTrainHistory.AddValue("testError",stepCount,testError);
1021
1022 end = std::chrono::system_clock::now();
1023
1024 // Compute training error.
1025 Double_t trainingError = 0.0;
1026 for (auto batch : trainingData) {
1027 auto inputMatrix = batch.GetInput();
1028 auto outputMatrix = batch.GetOutput();
1029 trainingError += net.Loss(inputMatrix, outputMatrix);
1030 }
1032 //Log the loss value
1033 fTrainHistory.AddValue("trainingError",stepCount,trainingError);
1034
1035 // Compute numerical throughput.
1036 std::chrono::duration<double> elapsed_seconds = end - start;
1037 double seconds = elapsed_seconds.count();
1038 double nFlops = (double) (settings.testInterval * batchesInEpoch);
1039 nFlops *= net.GetNFlops() * 1e-9;
1040
1041 converged = minimizer.HasConverged(testError);
1042 start = std::chrono::system_clock::now();
1043
1044 Log() << std::setw(10) << stepCount << " | "
1045 << std::setw(12) << trainingError
1046 << std::setw(12) << testError
1047 << std::setw(12) << nFlops / seconds
1048 << std::setw(12) << minimizer.GetConvergenceCount() << Endl;
1049 if (converged) {
1050 Log() << Endl;
1051 }
1052 }
1053 }
1054 for (size_t l = 0; l < net.GetDepth(); l++) {
1055 fNet.GetLayer(l).GetWeights() = (TMatrixT<Scalar_t>) net.GetLayer(l).GetWeights();
1056 fNet.GetLayer(l).GetBiases() = (TMatrixT<Scalar_t>) net.GetLayer(l).GetBiases();
1057 }
1058 }
1059
1060#else // DNNCUDA flag not set.
1061
1062 Log() << kFATAL << "CUDA backend not enabled. Please make sure "
1063 "you have CUDA installed and it was successfully "
1064 "detected by CMAKE." << Endl;
1065#endif // DNNCUDA
1066}
1067
1068////////////////////////////////////////////////////////////////////////////////
1069
1071{
1072
1073#ifdef DNNCPU // Included only if DNNCPU flag is set.
1074 Log() << kINFO << "Start of neural network training on CPU." << Endl << Endl;
1075
1076 size_t nValidationSamples = GetNumValidationSamples();
1077 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
1079
1080 Log() << kDEBUG << "Using " << nValidationSamples << " validation samples." << Endl;
1081 Log() << kDEBUG << "Using " << nTestSamples << " training samples." << Endl;
1082
1083 fNet.Initialize(fWeightInitialization);
1084
1085 size_t trainingPhase = 1;
1086 for (TTrainingSettings & settings : fTrainingSettings) {
1087
1088 Log() << "Training phase " << trainingPhase << " of "
1089 << fTrainingSettings.size() << ":" << Endl;
1090 trainingPhase++;
1091
1092 TNet<TCpu<>> net(settings.batchSize, fNet);
1093 net.SetWeightDecay(settings.weightDecay);
1094 net.SetRegularization(settings.regularization);
1095 // Need to convert dropoutprobabilities to conventions used
1096 // by backend implementation.
1097 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
1098 for (auto & p : dropoutVector) {
1099 p = 1.0 - p;
1100 }
1101 net.SetDropoutProbabilities(dropoutVector);
1102 net.InitializeGradients();
1103 auto testNet = net.CreateClone(settings.batchSize);
1104
1106
1107 // Split training data into training and validation set
1108 const std::vector<Event *> &allData = GetEventCollection(Types::kTraining);
1109 const std::vector<Event *> trainingInputData =
1110 std::vector<Event *>(allData.begin(), allData.begin() + nTrainingSamples);
1111 const std::vector<Event *> testInputData =
1112 std::vector<Event *>(allData.begin() + nTrainingSamples, allData.end());
1113
1114 if (trainingInputData.size() != nTrainingSamples) {
1115 Log() << kFATAL << "Inconsistent training sample size" << Endl;
1116 }
1117 if (testInputData.size() != nTestSamples) {
1118 Log() << kFATAL << "Inconsistent test sample size" << Endl;
1119 }
1120
1121 size_t nThreads = 1;
1122 TMVAInput_t trainingTuple = std::tie(trainingInputData, DataInfo());
1123 TMVAInput_t testTuple = std::tie(testInputData, DataInfo());
1125 net.GetBatchSize(), net.GetInputWidth(),
1126 net.GetOutputWidth(), nThreads);
1128 net.GetInputWidth(), net.GetOutputWidth(),
1129 nThreads);
1130 DNN::TGradientDescent<TCpu<>> minimizer(settings.learningRate,
1131 settings.convergenceSteps,
1132 settings.testInterval);
1133
1134 std::vector<TNet<TCpu<>>> nets{};
1135 std::vector<TBatch<TCpu<>>> batches{};
1136 nets.reserve(nThreads);
1137 for (size_t i = 0; i < nThreads; i++) {
1138 nets.push_back(net);
1139 for (size_t j = 0; j < net.GetDepth(); j++)
1140 {
1141 auto &masterLayer = net.GetLayer(j);
1142 auto &layer = nets.back().GetLayer(j);
1143 TCpu<>::Copy(layer.GetWeights(),
1144 masterLayer.GetWeights());
1145 TCpu<>::Copy(layer.GetBiases(),
1146 masterLayer.GetBiases());
1147 }
1148 }
1149
1150 bool converged = false;
1151 size_t stepCount = 0;
1152 size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
1153
1154 std::chrono::time_point<std::chrono::system_clock> start, end;
1155 start = std::chrono::system_clock::now();
1156
1157 Log() << std::setw(10) << "Epoch" << " | "
1158 << std::setw(12) << "Train Err."
1159 << std::setw(12) << "Test Err."
1160 << std::setw(12) << "GFLOP/s"
1161 << std::setw(12) << "Conv. Steps" << Endl;
1162 std::string separator(62, '-');
1163 Log() << separator << Endl;
1164
1165 while (!converged)
1166 {
1167 stepCount++;
1168 // Perform minimization steps for a full epoch.
1169 trainingData.Shuffle();
1170 for (size_t i = 0; i < batchesInEpoch; i += nThreads) {
1171 batches.clear();
1172 for (size_t j = 0; j < nThreads; j++) {
1173 batches.reserve(nThreads);
1174 batches.push_back(trainingData.GetBatch());
1175 }
1176 if (settings.momentum > 0.0) {
1177 minimizer.StepMomentum(net, nets, batches, settings.momentum);
1178 } else {
1179 minimizer.Step(net, nets, batches);
1180 }
1181 }
1182
1183 if ((stepCount % minimizer.GetTestInterval()) == 0) {
1184
1185 // Compute test error.
1186 Double_t testError = 0.0;
1187 for (auto batch : testData) {
1188 auto inputMatrix = batch.GetInput();
1189 auto outputMatrix = batch.GetOutput();
1190 auto weightMatrix = batch.GetWeights();
1191 testError += testNet.Loss(inputMatrix, outputMatrix, weightMatrix);
1192 }
1193 testError /= (Double_t) (nTestSamples / settings.batchSize);
1194
1195 //Log the loss value
1196 fTrainHistory.AddValue("testError",stepCount,testError);
1197
1198 end = std::chrono::system_clock::now();
1199
1200 // Compute training error.
1201 Double_t trainingError = 0.0;
1202 for (auto batch : trainingData) {
1203 auto inputMatrix = batch.GetInput();
1204 auto outputMatrix = batch.GetOutput();
1205 auto weightMatrix = batch.GetWeights();
1206 trainingError += net.Loss(inputMatrix, outputMatrix, weightMatrix);
1207 }
1209
1210 //Log the loss value
1211 fTrainHistory.AddValue("trainingError",stepCount,trainingError);
1212
1213 // Compute numerical throughput.
1214 std::chrono::duration<double> elapsed_seconds = end - start;
1215 double seconds = elapsed_seconds.count();
1216 double nFlops = (double) (settings.testInterval * batchesInEpoch);
1217 nFlops *= net.GetNFlops() * 1e-9;
1218
1219 converged = minimizer.HasConverged(testError);
1220 start = std::chrono::system_clock::now();
1221
1222 Log() << std::setw(10) << stepCount << " | "
1223 << std::setw(12) << trainingError
1224 << std::setw(12) << testError
1225 << std::setw(12) << nFlops / seconds
1226 << std::setw(12) << minimizer.GetConvergenceCount() << Endl;
1227 if (converged) {
1228 Log() << Endl;
1229 }
1230 }
1231 }
1232
1233
1234 for (size_t l = 0; l < net.GetDepth(); l++) {
1235 auto & layer = fNet.GetLayer(l);
1236 layer.GetWeights() = (TMatrixT<Scalar_t>) net.GetLayer(l).GetWeights();
1237 layer.GetBiases() = (TMatrixT<Scalar_t>) net.GetLayer(l).GetBiases();
1238 }
1239 }
1240
1241#else // DNNCPU flag not set.
1242 Log() << kFATAL << "Multi-core CPU backend not enabled. Please make sure "
1243 "you have a BLAS implementation and it was successfully "
1244 "detected by CMake as well that the imt CMake flag is set." << Endl;
1245#endif // DNNCPU
1246}
1247
1248////////////////////////////////////////////////////////////////////////////////
1249
1251{
1252 size_t nVariables = GetEvent()->GetNVariables();
1253 Matrix_t X(1, nVariables);
1254 Matrix_t YHat(1, 1);
1255
1256 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1257 for (size_t i = 0; i < nVariables; i++) {
1258 X(0,i) = inputValues[i];
1259 }
1260
1261 fNet.Prediction(YHat, X, fOutputFunction);
1262 return YHat(0,0);
1263}
1264
1265////////////////////////////////////////////////////////////////////////////////
1266
1267const std::vector<Float_t> & TMVA::MethodDNN::GetRegressionValues()
1268{
1269 size_t nVariables = GetEvent()->GetNVariables();
1270 Matrix_t X(1, nVariables);
1271
1272 const Event *ev = GetEvent();
1273 const std::vector<Float_t>& inputValues = ev->GetValues();
1274 for (size_t i = 0; i < nVariables; i++) {
1275 X(0,i) = inputValues[i];
1276 }
1277
1278 size_t nTargets = std::max(1u, ev->GetNTargets());
1280 std::vector<Float_t> output(nTargets);
1281 auto net = fNet.CreateClone(1);
1282 net.Prediction(YHat, X, fOutputFunction);
1283
1284 for (size_t i = 0; i < nTargets; i++)
1285 output[i] = YHat(0, i);
1286
1287 if (fRegressionReturnVal == NULL) {
1288 fRegressionReturnVal = new std::vector<Float_t>();
1289 }
1290 fRegressionReturnVal->clear();
1291
1292 Event * evT = new Event(*ev);
1293 for (size_t i = 0; i < nTargets; ++i) {
1294 evT->SetTarget(i, output[i]);
1295 }
1296
1297 const Event* evT2 = GetTransformationHandler().InverseTransform(evT);
1298 for (size_t i = 0; i < nTargets; ++i) {
1299 fRegressionReturnVal->push_back(evT2->GetTarget(i));
1300 }
1301 delete evT;
1302 return *fRegressionReturnVal;
1303}
1304
1305const std::vector<Float_t> & TMVA::MethodDNN::GetMulticlassValues()
1306{
1307 size_t nVariables = GetEvent()->GetNVariables();
1308 Matrix_t X(1, nVariables);
1309 Matrix_t YHat(1, DataInfo().GetNClasses());
1310 if (fMulticlassReturnVal == NULL) {
1311 fMulticlassReturnVal = new std::vector<Float_t>(DataInfo().GetNClasses());
1312 }
1313
1314 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1315 for (size_t i = 0; i < nVariables; i++) {
1316 X(0,i) = inputValues[i];
1317 }
1318
1319 fNet.Prediction(YHat, X, fOutputFunction);
1320 for (size_t i = 0; i < (size_t) YHat.GetNcols(); i++) {
1321 (*fMulticlassReturnVal)[i] = YHat(0, i);
1322 }
1323 return *fMulticlassReturnVal;
1324}
1325
1326////////////////////////////////////////////////////////////////////////////////
1327
1328void TMVA::MethodDNN::AddWeightsXMLTo( void* parent ) const
1329{
1330 void* nn = gTools().xmlengine().NewChild(parent, nullptr, "Weights");
1331 Int_t inputWidth = fNet.GetInputWidth();
1332 Int_t depth = fNet.GetDepth();
1333 char lossFunction = static_cast<char>(fNet.GetLossFunction());
1334 gTools().xmlengine().NewAttr(nn, nullptr, "InputWidth",
1335 gTools().StringFromInt(inputWidth));
1336 gTools().xmlengine().NewAttr(nn, nullptr, "Depth", gTools().StringFromInt(depth));
1337 gTools().xmlengine().NewAttr(nn, nullptr, "LossFunction", TString(lossFunction));
1338 gTools().xmlengine().NewAttr(nn, nullptr, "OutputFunction",
1339 TString(static_cast<char>(fOutputFunction)));
1340
1341 for (Int_t i = 0; i < depth; i++) {
1342 const auto& layer = fNet.GetLayer(i);
1343 auto layerxml = gTools().xmlengine().NewChild(nn, nullptr, "Layer");
1344 int activationFunction = static_cast<int>(layer.GetActivationFunction());
1345 gTools().xmlengine().NewAttr(layerxml, nullptr, "ActivationFunction",
1346 TString::Itoa(activationFunction, 10));
1347 WriteMatrixXML(layerxml, "Weights", layer.GetWeights());
1348 WriteMatrixXML(layerxml, "Biases", layer.GetBiases());
1349 }
1350}
1351
1352////////////////////////////////////////////////////////////////////////////////
1353
1355{
1356 auto netXML = gTools().GetChild(rootXML, "Weights");
1357 if (!netXML){
1358 netXML = rootXML;
1359 }
1360
1361 fNet.Clear();
1362 fNet.SetBatchSize(1);
1363
1364 size_t inputWidth, depth;
1365 gTools().ReadAttr(netXML, "InputWidth", inputWidth);
1366 gTools().ReadAttr(netXML, "Depth", depth);
1367 char lossFunctionChar;
1368 gTools().ReadAttr(netXML, "LossFunction", lossFunctionChar);
1369 char outputFunctionChar;
1370 gTools().ReadAttr(netXML, "OutputFunction", outputFunctionChar);
1371
1372 fNet.SetInputWidth(inputWidth);
1373 fNet.SetLossFunction(static_cast<ELossFunction>(lossFunctionChar));
1374 fOutputFunction = static_cast<EOutputFunction>(outputFunctionChar);
1375
1376 size_t previousWidth = inputWidth;
1377 auto layerXML = gTools().xmlengine().GetChild(netXML, "Layer");
1378 for (size_t i = 0; i < depth; i++) {
1379 TString fString;
1381
1382 // Read activation function.
1383 gTools().ReadAttr(layerXML, "ActivationFunction", fString);
1384 f = static_cast<EActivationFunction>(fString.Atoi());
1385
1386 // Read number of neurons.
1387 size_t width;
1388 auto matrixXML = gTools().GetChild(layerXML, "Weights");
1389 gTools().ReadAttr(matrixXML, "rows", width);
1390
1391 fNet.AddLayer(width, f);
1394 ReadMatrixXML(layerXML, "Weights", weights);
1395 ReadMatrixXML(layerXML, "Biases", biases);
1396 fNet.GetLayer(i).GetWeights() = weights;
1397 fNet.GetLayer(i).GetBiases() = biases;
1398
1401 }
1402}
1403
1404////////////////////////////////////////////////////////////////////////////////
1405
1406void TMVA::MethodDNN::ReadWeightsFromStream( std::istream & /*istr*/)
1407{
1408}
1409
1410////////////////////////////////////////////////////////////////////////////////
1411
1413{
1414 fRanking = new Ranking( GetName(), "Importance" );
1415 for (UInt_t ivar=0; ivar<GetNvar(); ivar++) {
1416 fRanking->AddRank( Rank( GetInputLabel(ivar), 1.0));
1417 }
1418 return fRanking;
1419}
1420
1421////////////////////////////////////////////////////////////////////////////////
1422
1423void TMVA::MethodDNN::MakeClassSpecific( std::ostream& /*fout*/,
1424 const TString& /*className*/ ) const
1425{
1426}
1427
1428////////////////////////////////////////////////////////////////////////////////
1429
1431{
1432 // get help message text
1433 //
1434 // typical length of text line:
1435 // "|--------------------------------------------------------------|"
1436 TString col = gConfig().WriteOptionsReference() ? TString() : gTools().Color("bold");
1438
1439 Log() << Endl;
1440 Log() << col << "--- Short description:" << colres << Endl;
1441 Log() << Endl;
1442 Log() << "The DNN neural network is a feedforward" << Endl;
1443 Log() << "multilayer perceptron implementation. The DNN has a user-" << Endl;
1444 Log() << "defined hidden layer architecture, where the number of input (output)" << Endl;
1445 Log() << "nodes is determined by the input variables (output classes, i.e., " << Endl;
1446 Log() << "signal and one background, regression or multiclass). " << Endl;
1447 Log() << Endl;
1448 Log() << col << "--- Performance optimisation:" << colres << Endl;
1449 Log() << Endl;
1450
1451 const char* txt = "The DNN supports various options to improve performance in terms of training speed and \n \
1452reduction of overfitting: \n \
1453\n \
1454 - different training settings can be stacked. Such that the initial training \n\
1455 is done with a large learning rate and a large drop out fraction whilst \n \
1456 in a later stage learning rate and drop out can be reduced. \n \
1457 - drop out \n \
1458 [recommended: \n \
1459 initial training stage: 0.0 for the first layer, 0.5 for later layers. \n \
1460 later training stage: 0.1 or 0.0 for all layers \n \
1461 final training stage: 0.0] \n \
1462 Drop out is a technique where a at each training cycle a fraction of arbitrary \n \
1463 nodes is disabled. This reduces co-adaptation of weights and thus reduces overfitting. \n \
1464 - L1 and L2 regularization are available \n \
1465 - Minibatches \n \
1466 [recommended 10 - 150] \n \
1467 Arbitrary mini-batch sizes can be chosen. \n \
1468 - Multithreading \n \
1469 [recommended: True] \n \
1470 Multithreading can be turned on. The minibatches are distributed to the available \n \
1471 cores. The algorithm is lock-free (\"Hogwild!\"-style) for each cycle. \n \
1472 \n \
1473 Options: \n \
1474 \"Layout\": \n \
1475 - example: \"TANH|(N+30)*2,TANH|(N+30),LINEAR\" \n \
1476 - meaning: \n \
1477 . two hidden layers (separated by \",\") \n \
1478 . the activation function is TANH (other options: RELU, SOFTSIGN, LINEAR) \n \
1479 . the activation function for the output layer is LINEAR \n \
1480 . the first hidden layer has (N+30)*2 nodes where N is the number of input neurons \n \
1481 . the second hidden layer has N+30 nodes, where N is the number of input neurons \n \
1482 . the number of nodes in the output layer is determined by the number of output nodes \n \
1483 and can therefore not be chosen freely. \n \
1484 \n \
1485 \"ErrorStrategy\": \n \
1486 - SUMOFSQUARES \n \
1487 The error of the neural net is determined by a sum-of-squares error function \n \
1488 For regression, this is the only possible choice. \n \
1489 - CROSSENTROPY \n \
1490 The error of the neural net is determined by a cross entropy function. The \n \
1491 output values are automatically (internally) transformed into probabilities \n \
1492 using a sigmoid function. \n \
1493 For signal/background classification this is the default choice. \n \
1494 For multiclass using cross entropy more than one or no output classes \n \
1495 can be equally true or false (e.g. Event 0: A and B are true, Event 1: \n \
1496 A and C is true, Event 2: C is true, ...) \n \
1497 - MUTUALEXCLUSIVE \n \
1498 In multiclass settings, exactly one of the output classes can be true (e.g. either A or B or C) \n \
1499 \n \
1500 \"WeightInitialization\" \n \
1501 - XAVIER \n \
1502 [recommended] \n \
1503 \"Xavier Glorot & Yoshua Bengio\"-style of initializing the weights. The weights are chosen randomly \n \
1504 such that the variance of the values of the nodes is preserved for each layer. \n \
1505 - XAVIERUNIFORM \n \
1506 The same as XAVIER, but with uniformly distributed weights instead of gaussian weights \n \
1507 - LAYERSIZE \n \
1508 Random values scaled by the layer size \n \
1509 \n \
1510 \"TrainingStrategy\" \n \
1511 - 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 \
1512 - explanation: two stacked training settings separated by \"|\" \n \
1513 . 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 \
1514 . 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 \
1515 . LearningRate : \n \
1516 - recommended for classification: 0.1 initially, 1e-4 later \n \
1517 - recommended for regression: 1e-4 and less \n \
1518 . Momentum : \n \
1519 preserve a fraction of the momentum for the next training batch [fraction = 0.0 - 1.0] \n \
1520 . Repetitions : \n \
1521 train \"Repetitions\" repetitions with the same minibatch before switching to the next one \n \
1522 . ConvergenceSteps : \n \
1523 Assume that convergence is reached after \"ConvergenceSteps\" cycles where no improvement \n \
1524 of the error on the test samples has been found. (Mind that only at each \"TestRepetitions\" \n \
1525 cycle the test samples are evaluated and thus the convergence is checked) \n \
1526 . BatchSize \n \
1527 Size of the mini-batches. \n \
1528 . TestRepetitions \n \
1529 Perform testing the neural net on the test samples each \"TestRepetitions\" cycle \n \
1530 . WeightDecay \n \
1531 If \"Renormalize\" is set to L1 or L2, \"WeightDecay\" provides the renormalization factor \n \
1532 . Renormalize \n \
1533 NONE, L1 (|w|) or L2 (w^2) \n \
1534 . DropConfig \n \
1535 Drop a fraction of arbitrary nodes of each of the layers according to the values given \n \
1536 in the DropConfig. \n \
1537 [example: DropConfig=0.0+0.5+0.3 \n \
1538 meaning: drop no nodes in layer 0 (input layer), half of the nodes in layer 1 and 30% of the nodes \n \
1539 in layer 2 \n \
1540 recommended: leave all the nodes turned on for the input layer (layer 0) \n \
1541 turn off half of the nodes in later layers for the initial training; leave all nodes \n \
1542 turned on (0.0) in later training stages] \n \
1543 . DropRepetitions \n \
1544 Each \"DropRepetitions\" cycle the configuration of which nodes are dropped is changed \n \
1545 [recommended : 1] \n \
1546 . Multithreading \n \
1547 turn on multithreading [recommended: True] \n \
1548 \n";
1549 Log () << txt << Endl;
1550}
1551
1552} // namespace TMVA
#define REGISTER_METHOD(CLASS)
for example
#define f(i)
Definition RSha256.hxx:104
#define g(i)
Definition RSha256.hxx:105
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:78
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
#define X(type, name)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
const_iterator begin() const
const_iterator end() const
The Formula class.
Definition TFormula.h:89
Bool_t WriteOptionsReference() const
Definition Config.h:65
Layer defines the layout of a layer.
Definition NeuralNet.h:671
neural net
Definition NeuralNet.h:1060
Settings for the training of the neural net.
Definition NeuralNet.h:728
Steepest Gradient Descent algorithm (SGD)
Definition NeuralNet.h:332
static void Copy(Matrix_t &B, const Matrix_t &A)
static void Copy(Matrix_t &B, const Matrix_t &A)
bool HasConverged()
Increases the minimization step counter by the test error evaluation period and uses the current inte...
Definition Minimizers.h:667
void Step(Net_t &net, Matrix_t &input, const Matrix_t &output, const Matrix_t &weights)
Perform a single optimization step on a given batch.
Definition Minimizers.h:331
size_t GetTestInterval() const
Definition Minimizers.h:163
void StepMomentum(Net_t &master, std::vector< Net_t > &nets, std::vector< TBatch< Architecture_t > > &batches, Scalar_t momentum)
Same as the Step(...) method for multiple batches but uses momentum.
Definition Minimizers.h:438
size_t GetConvergenceCount() const
Definition Minimizers.h:159
void AddWeightsXMLTo(void *parent) const override
void ProcessOptions() override
void Init() override
UInt_t GetNumValidationSamples()
typename Architecture_t::Matrix_t Matrix_t
Definition MethodDNN.h:82
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets) override
void MakeClassSpecific(std::ostream &, const TString &) const override
LayoutVector_t ParseLayoutString(TString layerSpec)
MethodDNN(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption)
const Ranking * CreateRanking() override
virtual ~MethodDNN()
const std::vector< Float_t > & GetMulticlassValues() override
std::vector< std::map< TString, TString > > KeyValueVector_t
Definition MethodDNN.h:87
void DeclareOptions() override
DNN::EInitialization fWeightInitialization
Definition MethodDNN.h:112
void GetHelpMessage() const override
void Train() override
const std::vector< Float_t > & GetRegressionValues() override
void ReadWeightsFromStream(std::istream &i) override
KeyValueVector_t ParseKeyValueString(TString parseString, TString blockDelim, TString tokenDelim)
DNN::EOutputFunction fOutputFunction
Definition MethodDNN.h:113
Double_t GetMvaValue(Double_t *err=nullptr, Double_t *errUpper=nullptr) override
void ReadWeightsFromXML(void *wghtnode) override
Ranking for variables in method (implementation)
Definition Ranking.h:48
const TString & Color(const TString &)
human readable color strings
Definition Tools.cxx:803
TXMLEngine & xmlengine()
Definition Tools.h:262
void ReadAttr(void *node, const char *, T &value)
read attribute from xml
Definition Tools.h:329
void * GetChild(void *parent, const char *childname=nullptr)
get child node
Definition Tools.cxx:1125
void * GetNextChild(void *prevchild, const char *childname=nullptr)
XML helpers.
Definition Tools.cxx:1137
@ kMulticlass
Definition Types.h:129
@ kClassification
Definition Types.h:127
@ kRegression
Definition Types.h:128
@ kTraining
Definition Types.h:143
@ kWARNING
Definition Types.h:59
@ kFATAL
Definition Types.h:61
An array of TObjects.
Definition TObjArray.h:31
Collectable string class.
Definition TObjString.h:28
const TString & GetString() const
Definition TObjString.h:46
Basic string class.
Definition TString.h:138
Int_t Atoi() const
Return integer value of string.
Definition TString.cxx:2068
@ kTrailing
Definition TString.h:284
@ kBoth
Definition TString.h:284
void ToUpper()
Change string to upper case.
Definition TString.cxx:1202
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:2172
XMLNodePointer_t NewChild(XMLNodePointer_t parent, XMLNsPointer_t ns, const char *name, const char *content=nullptr)
create new child element for parent node
XMLNodePointer_t GetChild(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
returns first child of xmlnode
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
EOutputFunction
Enum that represents output functions.
Definition Functions.h:46
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:238
EActivationFunction
Enum that represents layer activation functions.
Definition Functions.h:32
ELossFunction
Enum that represents objective functions for the net, i.e.
Definition Functions.h:57
std::tuple< const std::vector< Event * > &, const DataSetInfo & > TMVAInput_t
Definition DataLoader.h:39
create variable transformations
Config & gConfig()
Tools & gTools()
TString fetchValue(const std::map< TString, TString > &keyValueMap, TString key)
MsgLogger & Endl(MsgLogger &ml)
Definition MsgLogger.h:148
Double_t Log(Double_t x)
Returns the natural logarithm of x.
Definition TMath.h:769
TLine l
Definition textangle.C:4