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