74#pragma warning(disable : 4996)
76#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
89 TMVA::MethodDNN::MethodDNN(
const TString &jobName,
const TString &methodTitle, DataSetInfo &theData,
91 : MethodBase(jobName,
Types::kDNN, methodTitle, theData, theOption), fWeightInitialization(), fOutputFunction(),
92 fLayoutString(), fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
93 fArchitectureString(), fTrainingSettings(), fResume(
false), fSettings()
100TMVA::MethodDNN::MethodDNN(DataSetInfo& theData,
102 : MethodBase(
Types::kDNN, theData, theWeightFile),
103 fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
104 fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
105 fTrainingSettings(), fResume(
false), fSettings()
114TMVA::MethodDNN::~MethodDNN()
138void TMVA::MethodDNN::Init() {
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++."
159void TMVA::MethodDNN::DeclareOptions()
162 DeclareOptionRef(fLayoutString=
"SOFTSIGN|(N+100)*2,LINEAR",
164 "Layout of the network.");
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. "
173 DeclareOptionRef(fErrorStrategy=
"CROSSENTROPY",
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"));
181 DeclareOptionRef(fWeightInitializationString=
"XAVIER",
182 "WeightInitialization",
183 "Weight initialization strategy");
184 AddPreDefVal(
TString(
"XAVIER"));
185 AddPreDefVal(
TString(
"XAVIERUNIFORM"));
187 DeclareOptionRef(fArchitectureString =
"CPU",
"Architecture",
"Which architecture to perform the training on.");
188 AddPreDefVal(
TString(
"STANDARD"));
191 AddPreDefVal(
TString(
"OPENCL"));
194 fTrainingStrategyString =
"LearningRate=1e-1,"
197 "ConvergenceSteps=50,"
203 "DropRepetitions=5|LearningRate=1e-4,"
206 "ConvergenceSteps=50,"
211 "DropConfig=0.0+0.5+0.5,"
213 "Multithreading=True",
215 "Defines the training strategies.");
222auto TMVA::MethodDNN::ParseLayoutString(
TString layoutString)
225 LayoutVector_t layout;
226 const TString layerDelimiter(
",");
227 const TString subDelimiter(
"|");
229 const size_t inputSize = GetNvar();
232 TIter nextLayer (layerStrings);
235 for (; layerString !=
nullptr; layerString = (
TObjString*) nextLayer()) {
237 EActivationFunction activationFunction = EActivationFunction::kTanh;
240 TIter nextToken (subStrings);
243 for (; token !=
nullptr; token = (
TObjString *) nextToken()) {
249 if (strActFnc ==
"RELU") {
251 }
else if (strActFnc ==
"TANH") {
253 }
else if (strActFnc ==
"SYMMRELU") {
255 }
else if (strActFnc ==
"SOFTSIGN") {
257 }
else if (strActFnc ==
"SIGMOID") {
259 }
else if (strActFnc ==
"LINEAR") {
261 }
else if (strActFnc ==
"GAUSS") {
273 numNodes = fml.
Eval (inputSize);
279 layout.push_back(std::make_pair(numNodes, activationFunction));
287auto TMVA::MethodDNN::ParseKeyValueString(
TString parseString,
292 KeyValueVector_t blockKeyValues;
293 const TString keyValueDelim (
"=");
296 TIter nextBlock (blockStrings);
299 for (; blockString !=
nullptr; blockString = (
TObjString *) nextBlock())
301 blockKeyValues.push_back (std::map<TString,TString>());
302 std::map<TString,TString>& currentBlock = blockKeyValues.back ();
305 TIter nextToken (subStrings);
308 for (; token !=
nullptr; token = (
TObjString *)nextToken())
311 int delimPos = strKeyValue.
First (keyValueDelim.
Data ());
322 currentBlock.insert (std::make_pair (strKey, strValue));
325 return blockKeyValues;
333 std::map<TString, TString>::const_iterator it = keyValueMap.find (key);
334 if (it == keyValueMap.end()) {
358 return value.Atoi ();
364double fetchValue (
const std::map<TString,TString>& keyValueMap,
365 TString key,
double defaultValue)
371 return value.Atof ();
390bool fetchValue (
const std::map<TString,TString>& keyValueMap,
391 TString key,
bool defaultValue)
407std::vector<double>
fetchValue(
const std::map<TString, TString> & keyValueMap,
409 std::vector<double> defaultValue)
412 if (parseString ==
"") {
416 std::vector<double> values;
418 const TString tokenDelim (
"+");
420 TIter nextToken (tokenStrings);
422 for (; tokenString != NULL; tokenString = (
TObjString*)nextToken ()) {
423 std::stringstream sstr;
426 sstr >> currentValue;
427 values.push_back (currentValue);
434void TMVA::MethodDNN::ProcessOptions()
436 if (IgnoreEventsWithNegWeightsInTraining()) {
438 <<
"Will ignore negative events in training!"
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."
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."
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."
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."
468 if (fArchitectureString ==
"GPU") {
470 Log() <<
kERROR <<
"CUDA backend not enabled. Please make sure "
471 "you have CUDA installed and it was successfully "
474 Log() <<
kFATAL <<
"CUDA backend not enabled. Please make sure "
475 "you have CUDA installed and it was successfully "
481 if (fArchitectureString ==
"CPU") {
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."
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."
496 fLayout = TMVA::MethodDNN::ParseLayoutString (fLayoutString);
497 size_t inputSize = GetNVariables ();
498 size_t outputSize = 1;
500 outputSize = GetNTargets();
502 outputSize = DataInfo().GetNClasses();
505 fNet.SetBatchSize(1);
506 fNet.SetInputWidth(inputSize);
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);
513 fNet.AddLayer(outputSize, EActivationFunction::kIdentity);
519 fOutputFunction = EOutputFunction::kSigmoid;
522 if (fErrorStrategy ==
"SUMOFSQUARES") {
523 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
525 if (fErrorStrategy ==
"CROSSENTROPY") {
526 fNet.SetLossFunction(ELossFunction::kCrossEntropy);
528 fOutputFunction = EOutputFunction::kSigmoid;
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;
535 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
536 fOutputFunction = EOutputFunction::kIdentity;
538 if (fErrorStrategy ==
"SUMOFSQUARES") {
539 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
541 if (fErrorStrategy ==
"CROSSENTROPY") {
542 fNet.SetLossFunction(ELossFunction::kCrossEntropy);
544 if (fErrorStrategy ==
"MUTUALEXCLUSIVE") {
545 fNet.SetLossFunction(ELossFunction::kSoftmaxCrossEntropy);
547 fOutputFunction = EOutputFunction::kSoftmax;
554 if (fWeightInitializationString ==
"XAVIER") {
557 else if (fWeightInitializationString ==
"XAVIERUNIFORM") {
569 GetNumValidationSamples();
571 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
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;
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", 1
e-5);
585 settings.momentum =
fetchValue(block,
"Momentum", 0.3);
586 settings.dropoutProbabilities =
fetchValue(block,
"DropConfig",
587 std::vector<Double_t>());
602 settings.multithreading =
true;
604 settings.multithreading =
false;
607 fTrainingSettings.push_back(settings);
620UInt_t TMVA::MethodDNN::GetNumValidationSamples()
622 Int_t nValidationSamples = 0;
627 if (fValidationSize.EndsWith(
"%")) {
632 Double_t valSizeAsDouble = fValidationSize.Atof() / 100.0;
633 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
635 Log() <<
kFATAL <<
"Cannot parse number \"" << fValidationSize
636 <<
"\". Expected string like \"20%\" or \"20.0%\"." <<
Endl;
638 }
else if (fValidationSize.IsFloat()) {
639 Double_t valSizeAsDouble = fValidationSize.Atof();
641 if (valSizeAsDouble < 1.0) {
643 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
646 nValidationSamples = valSizeAsDouble;
649 Log() <<
kFATAL <<
"Cannot parse number \"" << fValidationSize <<
"\". Expected string like \"0.2\" or \"100\"."
655 if (nValidationSamples < 0) {
656 Log() <<
kFATAL <<
"Validation size \"" << fValidationSize <<
"\" is negative." <<
Endl;
659 if (nValidationSamples == 0) {
660 Log() <<
kFATAL <<
"Validation size \"" << fValidationSize <<
"\" is zero." <<
Endl;
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;
668 return nValidationSamples;
673void TMVA::MethodDNN::Train()
675 for (TTrainingSettings & settings : fTrainingSettings) {
676 size_t nValidationSamples = GetNumValidationSamples();
677 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
678 size_t nTestSamples = nValidationSamples;
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;
693 if (fArchitectureString ==
"GPU") {
696 }
else if (fArchitectureString ==
"OpenCL") {
697 Log() <<
kFATAL <<
"OpenCL backend not yet supported." <<
Endl;
699 }
else if (fArchitectureString ==
"CPU") {
704 Log() <<
kINFO <<
"Using Standard Implementation.";
706 std::vector<Pattern> trainPattern;
707 std::vector<Pattern> testPattern;
709 size_t nValidationSamples = GetNumValidationSamples();
710 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
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()};
716 for (
auto &
event : eventCollectionTraining) {
717 const std::vector<Float_t>& values =
event->GetValues();
719 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
720 trainPattern.push_back(
Pattern (values.begin(),
723 event->GetWeight()));
724 trainPattern.back().addInput(1.0);
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);
733 const std::vector<Float_t>& targets =
event->GetTargets ();
734 trainPattern.push_back(
Pattern(values.begin(),
738 event->GetWeight ()));
739 trainPattern.back ().addInput (1.0);
743 for (
auto &
event : eventCollectionTesting) {
744 const std::vector<Float_t>& values =
event->GetValues();
746 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
747 testPattern.push_back(
Pattern (values.begin(),
750 event->GetWeight()));
751 testPattern.back().addInput(1.0);
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);
760 const std::vector<Float_t>& targets =
event->GetTargets ();
761 testPattern.push_back(
Pattern(values.begin(),
765 event->GetWeight ()));
766 testPattern.back ().addInput (1.0);
771 std::vector<double> weights;
776 for (
size_t i = 0; i < fNet.GetDepth(); i++) {
777 EActivationFunction
f = fNet.GetLayer(i).GetActivationFunction();
778 EnumFunction
g = EnumFunction::LINEAR;
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;
789 if (i < fNet.GetDepth() - 1) {
790 net.
addLayer(Layer(fNet.GetLayer(i).GetWidth(),
g));
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;
798 net.
addLayer(Layer(fNet.GetLayer(i).GetWidth(),
g,
h));
802 switch(fNet.GetLossFunction()) {
803 case ELossFunction::kMeanSquaredError:
806 case ELossFunction::kCrossEntropy:
809 case ELossFunction::kSoftmaxCrossEntropy:
814 switch(fWeightInitialization) {
815 case EInitialization::kGauss:
817 std::back_inserter(weights));
819 case EInitialization::kUniform:
821 std::back_inserter(weights));
825 std::back_inserter(weights));
830 for (
auto s : fTrainingSettings) {
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;
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);
846 <<
"Training with learning rate = " << ptrSettings->learningRate ()
847 <<
", momentum = " << ptrSettings->momentum ()
848 <<
", repetitions = " << ptrSettings->repetitions ()
851 ptrSettings->setProgressLimits ((idxSetting)*100.0/(fSettings.size ()),
852 (idxSetting+1)*100.0/(fSettings.size ()));
854 const std::vector<double>& dropConfig = ptrSettings->dropFractions ();
855 if (!dropConfig.empty ()) {
857 <<
" drop repetitions = " << ptrSettings->dropRepetitions()
862 for (
auto f : dropConfig) {
868 DNN::Steepest minimizer(ptrSettings->learningRate(),
869 ptrSettings->momentum(),
870 ptrSettings->repetitions());
871 net.
train(weights, trainPattern, testPattern, minimizer, *ptrSettings.get());
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];
885 auto & layerBiases = fNet.GetLayer(
l).GetBiases();
887 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
888 layerBiases(i,0) = weights[weightIndex];
892 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
893 layerBiases(i,0) = 0.0;
901void TMVA::MethodDNN::TrainGpu()
905 Log() <<
kINFO <<
"Start of neural network training on GPU." <<
Endl <<
Endl;
907 size_t nValidationSamples = GetNumValidationSamples();
908 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
909 size_t nTestSamples = nValidationSamples;
911 Log() <<
kDEBUG <<
"Using " << nValidationSamples <<
" validation samples." <<
Endl;
912 Log() <<
kDEBUG <<
"Using " << nTestSamples <<
" training samples." <<
Endl;
914 size_t trainingPhase = 1;
915 fNet.Initialize(fWeightInitialization);
916 for (TTrainingSettings & settings : fTrainingSettings) {
918 TNet<TCuda<>> net(settings.batchSize, fNet);
919 net.SetWeightDecay(settings.weightDecay);
920 net.SetRegularization(settings.regularization);
924 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
925 for (
auto &
p : dropoutVector) {
928 net.SetDropoutProbabilities(dropoutVector);
930 net.InitializeGradients();
931 auto testNet = net.CreateClone(settings.batchSize);
933 Log() <<
kINFO <<
"Training phase " << trainingPhase <<
" of "
934 << fTrainingSettings.size() <<
":" <<
Endl;
937 using DataLoader_t = TDataLoader<TMVAInput_t, TCuda<>>;
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());
946 if (trainingInputData.size() != nTrainingSamples) {
947 Log() <<
kFATAL <<
"Inconsistent training sample size" <<
Endl;
949 if (testInputData.size() != nTestSamples) {
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(),
962 DNN::TGradientDescent<TCuda<>> minimizer(settings.learningRate,
963 settings.convergenceSteps,
964 settings.testInterval);
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++) {
971 for (
size_t j = 0; j < net.GetDepth(); j++)
973 auto &masterLayer = net.GetLayer(j);
974 auto &layer = nets.back().GetLayer(j);
976 masterLayer.GetWeights());
978 masterLayer.GetBiases());
982 bool converged =
false;
983 size_t stepCount = 0;
984 size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
986 std::chrono::time_point<std::chrono::system_clock> start, end;
987 start = std::chrono::system_clock::now();
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,
'-');
1002 trainingData.Shuffle();
1003 for (
size_t i = 0; i < batchesInEpoch; i += nThreads) {
1005 for (
size_t j = 0; j < nThreads; j++) {
1006 batches.reserve(nThreads);
1007 batches.push_back(trainingData.GetBatch());
1009 if (settings.momentum > 0.0) {
1010 minimizer.StepMomentum(net, nets, batches, settings.momentum);
1012 minimizer.Step(net, nets, batches);
1016 if ((stepCount % minimizer.GetTestInterval()) == 0) {
1020 for (
auto batch : testData) {
1021 auto inputMatrix = batch.GetInput();
1022 auto outputMatrix = batch.GetOutput();
1023 testError += testNet.Loss(inputMatrix, outputMatrix);
1025 testError /= (
Double_t) (nTestSamples / settings.batchSize);
1028 fTrainHistory.AddValue(
"testError",stepCount,testError);
1030 end = std::chrono::system_clock::now();
1034 for (
auto batch : trainingData) {
1035 auto inputMatrix = batch.GetInput();
1036 auto outputMatrix = batch.GetOutput();
1037 trainingError += net.Loss(inputMatrix, outputMatrix);
1039 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
1041 fTrainHistory.AddValue(
"trainingError",stepCount,trainingError);
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() * 1
e-9;
1049 converged = minimizer.HasConverged(testError);
1050 start = std::chrono::system_clock::now();
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;
1062 for (
size_t l = 0;
l < net.GetDepth();
l++) {
1070 Log() <<
kFATAL <<
"CUDA backend not enabled. Please make sure "
1071 "you have CUDA installed and it was successfully "
1072 "detected by CMAKE." <<
Endl;
1078void TMVA::MethodDNN::TrainCpu()
1082 Log() <<
kINFO <<
"Start of neural network training on CPU." <<
Endl <<
Endl;
1084 size_t nValidationSamples = GetNumValidationSamples();
1085 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
1086 size_t nTestSamples = nValidationSamples;
1088 Log() <<
kDEBUG <<
"Using " << nValidationSamples <<
" validation samples." <<
Endl;
1089 Log() <<
kDEBUG <<
"Using " << nTestSamples <<
" training samples." <<
Endl;
1091 fNet.Initialize(fWeightInitialization);
1093 size_t trainingPhase = 1;
1094 for (TTrainingSettings & settings : fTrainingSettings) {
1096 Log() <<
"Training phase " << trainingPhase <<
" of "
1097 << fTrainingSettings.size() <<
":" <<
Endl;
1100 TNet<TCpu<>> net(settings.batchSize, fNet);
1101 net.SetWeightDecay(settings.weightDecay);
1102 net.SetRegularization(settings.regularization);
1105 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
1106 for (
auto &
p : dropoutVector) {
1109 net.SetDropoutProbabilities(dropoutVector);
1110 net.InitializeGradients();
1111 auto testNet = net.CreateClone(settings.batchSize);
1113 using DataLoader_t = TDataLoader<TMVAInput_t, TCpu<>>;
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());
1122 if (trainingInputData.size() != nTrainingSamples) {
1123 Log() <<
kFATAL <<
"Inconsistent training sample size" <<
Endl;
1125 if (testInputData.size() != nTestSamples) {
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(),
1138 DNN::TGradientDescent<TCpu<>> minimizer(settings.learningRate,
1139 settings.convergenceSteps,
1140 settings.testInterval);
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++)
1149 auto &masterLayer = net.GetLayer(j);
1150 auto &layer = nets.back().GetLayer(j);
1152 masterLayer.GetWeights());
1154 masterLayer.GetBiases());
1158 bool converged =
false;
1159 size_t stepCount = 0;
1160 size_t batchesInEpoch = nTrainingSamples / net.GetBatchSize();
1162 std::chrono::time_point<std::chrono::system_clock> start, end;
1163 start = std::chrono::system_clock::now();
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,
'-');
1177 trainingData.Shuffle();
1178 for (
size_t i = 0; i < batchesInEpoch; i += nThreads) {
1180 for (
size_t j = 0; j < nThreads; j++) {
1181 batches.reserve(nThreads);
1182 batches.push_back(trainingData.GetBatch());
1184 if (settings.momentum > 0.0) {
1185 minimizer.StepMomentum(net, nets, batches, settings.momentum);
1187 minimizer.Step(net, nets, batches);
1191 if ((stepCount % minimizer.GetTestInterval()) == 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);
1201 testError /= (
Double_t) (nTestSamples / settings.batchSize);
1204 fTrainHistory.AddValue(
"testError",stepCount,testError);
1206 end = std::chrono::system_clock::now();
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);
1216 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
1219 fTrainHistory.AddValue(
"trainingError",stepCount,trainingError);
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() * 1
e-9;
1227 converged = minimizer.HasConverged(testError);
1228 start = std::chrono::system_clock::now();
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;
1242 for (
size_t l = 0;
l < net.GetDepth();
l++) {
1243 auto & layer = fNet.GetLayer(
l);
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;
1259 size_t nVariables = GetEvent()->GetNVariables();
1260 Matrix_t
X(1, nVariables);
1261 Matrix_t YHat(1, 1);
1263 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1264 for (
size_t i = 0; i < nVariables; i++) {
1265 X(0,i) = inputValues[i];
1268 fNet.Prediction(YHat,
X, fOutputFunction);
1274const std::vector<Float_t> & TMVA::MethodDNN::GetRegressionValues()
1276 size_t nVariables = GetEvent()->GetNVariables();
1277 Matrix_t
X(1, nVariables);
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];
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);
1291 for (
size_t i = 0; i < nTargets; i++)
1292 output[i] = YHat(0, i);
1294 if (fRegressionReturnVal == NULL) {
1295 fRegressionReturnVal =
new std::vector<Float_t>();
1297 fRegressionReturnVal->clear();
1299 Event * evT =
new Event(*ev);
1300 for (
size_t i = 0; i < nTargets; ++i) {
1301 evT->SetTarget(i, output[i]);
1304 const Event* evT2 = GetTransformationHandler().InverseTransform(evT);
1305 for (
size_t i = 0; i < nTargets; ++i) {
1306 fRegressionReturnVal->push_back(evT2->GetTarget(i));
1309 return *fRegressionReturnVal;
1312const std::vector<Float_t> & TMVA::MethodDNN::GetMulticlassValues()
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());
1321 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1322 for (
size_t i = 0; i < nVariables; i++) {
1323 X(0,i) = inputValues[i];
1326 fNet.Prediction(YHat,
X, fOutputFunction);
1327 for (
size_t i = 0; i < (size_t) YHat.GetNcols(); i++) {
1328 (*fMulticlassReturnVal)[i] = YHat(0, i);
1330 return *fMulticlassReturnVal;
1335void TMVA::MethodDNN::AddWeightsXMLTo(
void* parent )
const
1338 Int_t inputWidth = fNet.GetInputWidth();
1339 Int_t depth = fNet.GetDepth();
1340 char lossFunction =
static_cast<char>(fNet.GetLossFunction());
1342 gTools().StringFromInt(inputWidth));
1346 TString(
static_cast<char>(fOutputFunction)));
1348 for (
Int_t i = 0; i < depth; i++) {
1349 const auto& layer = fNet.GetLayer(i);
1351 int activationFunction =
static_cast<int>(layer.GetActivationFunction());
1354 WriteMatrixXML(layerxml,
"Weights", layer.GetWeights());
1355 WriteMatrixXML(layerxml,
"Biases", layer.GetBiases());
1361void TMVA::MethodDNN::ReadWeightsFromXML(
void* rootXML)
1369 fNet.SetBatchSize(1);
1371 size_t inputWidth, depth;
1374 char lossFunctionChar;
1376 char outputFunctionChar;
1379 fNet.SetInputWidth(inputWidth);
1380 fNet.SetLossFunction(
static_cast<ELossFunction
>(lossFunctionChar));
1381 fOutputFunction =
static_cast<EOutputFunction
>(outputFunctionChar);
1383 size_t previousWidth = inputWidth;
1385 for (
size_t i = 0; i < depth; i++) {
1387 EActivationFunction
f;
1391 f =
static_cast<EActivationFunction
>(fString.
Atoi());
1401 ReadMatrixXML(layerXML,
"Weights", weights);
1402 ReadMatrixXML(layerXML,
"Biases", biases);
1403 fNet.GetLayer(i).GetWeights() = weights;
1404 fNet.GetLayer(i).GetBiases() = biases;
1407 previousWidth =
width;
1413void TMVA::MethodDNN::ReadWeightsFromStream( std::istream & )
1421 fRanking =
new Ranking(
GetName(),
"Importance" );
1422 for (
UInt_t ivar=0; ivar<GetNvar(); ivar++) {
1423 fRanking->AddRank( Rank( GetInputLabel(ivar), 1.0));
1430void TMVA::MethodDNN::MakeClassSpecific( std::ostream& ,
1437void TMVA::MethodDNN::GetHelpMessage()
const
1447 Log() << col <<
"--- Short description:" << colres <<
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;
1455 Log() << col <<
"--- Performance optimisation:" << colres <<
Endl;
1458 const char* txt =
"The DNN supports various options to improve performance in terms of training speed and \n \
1459reduction of overfitting: \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 \
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 \
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 \
1482 - example: \"TANH|(N+30)*2,TANH|(N+30),LINEAR\" \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 \
1492 \"ErrorStrategy\": \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 \
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 \
1507 \"WeightInitialization\" \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 \
1515 Random values scaled by the layer size \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 \
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 \
1534 Size of the mini-batches. \n \
1535 . TestRepetitions \n \
1536 Perform testing the neural net on the test samples each \"TestRepetitions\" cycle \n \
1538 If \"Renormalize\" is set to L1 or L2, \"WeightDecay\" provides the renormalization factor \n \
1540 NONE, L1 (|w|) or L2 (w^2) \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 \
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 \
#define REGISTER_METHOD(CLASS)
for example
int Int_t
Signed integer 4 bytes (int)
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
double Double_t
Double 8 bytes.
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 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
Bool_t WriteOptionsReference() const
void setInputSize(size_t sizeInput)
set the input size of the DNN
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
void initializeWeights(WeightInitializationStrategy eInitStrategy, OutIterator itWeight)
initialize the weights with the given strategy
void addLayer(Layer &layer)
add a layer (layout)
void setOutputSize(size_t sizeOutput)
set the output size of the DNN
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)
Collectable string class.
const TString & GetString() const
Int_t Atoi() const
Return integer value of string.
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
Ssiz_t First(char c) const
Find first occurrence of a character c.
const char * Data() const
TString & ReplaceAll(const TString &s1, const TString &s2)
void ToUpper()
Change string to upper case.
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
static TString Itoa(Int_t value, Int_t base)
Converts an Int_t to a TString with respect to the base specified (2-36).
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.
std::tuple< const std::vector< Event * > &, const DataSetInfo & > TMVAInput_t
create variable transformations
TString fetchValue(const std::map< TString, TString > &keyValueMap, TString key)
MsgLogger & Endl(MsgLogger &ml)
Double_t Log(Double_t x)
Returns the natural logarithm of x.
std::string GetName(TCppScope_t)