75 : MethodBase(jobName, Types::kDNN, methodTitle, theData, theOption), fWeightInitialization(), fOutputFunction(),
76 fLayoutString(), fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
77 fArchitectureString(), fTrainingSettings(), fResume(false), fSettings()
86 : MethodBase( Types::kDNN, theData, theWeightFile),
87 fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
88 fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
89 fTrainingSettings(), fResume(false), fSettings()
91 fWeightInitialization = DNN::EInitialization::kGauss;
92 fOutputFunction = DNN::EOutputFunction::kSigmoid;
140 DeclareOptionRef(fLayoutString=
"SOFTSIGN|(N+100)*2,LINEAR",
142 "Layout of the network.");
144 DeclareOptionRef(fValidationSize =
"20%",
"ValidationSize",
145 "Part of the training data to use for "
146 "validation. Specify as 0.2 or 20% to use a "
147 "fifth of the data set as validation set. "
148 "Specify as 100 to use exactly 100 events. "
151 DeclareOptionRef(fErrorStrategy=
"CROSSENTROPY",
153 "Loss function: Mean squared error (regression)"
154 " or cross entropy (binary classification).");
155 AddPreDefVal(
TString(
"CROSSENTROPY"));
156 AddPreDefVal(
TString(
"SUMOFSQUARES"));
157 AddPreDefVal(
TString(
"MUTUALEXCLUSIVE"));
159 DeclareOptionRef(fWeightInitializationString=
"XAVIER",
160 "WeightInitialization",
161 "Weight initialization strategy");
162 AddPreDefVal(
TString(
"XAVIER"));
163 AddPreDefVal(
TString(
"XAVIERUNIFORM"));
165 DeclareOptionRef(fArchitectureString =
"CPU",
"Architecture",
"Which architecture to perform the training on.");
166 AddPreDefVal(
TString(
"STANDARD"));
169 AddPreDefVal(
TString(
"OPENCL"));
172 fTrainingStrategyString =
"LearningRate=1e-1,"
175 "ConvergenceSteps=50,"
181 "DropRepetitions=5|LearningRate=1e-4,"
184 "ConvergenceSteps=50,"
189 "DropConfig=0.0+0.5+0.5,"
191 "Multithreading=True",
193 "Defines the training strategies.");
203 LayoutVector_t layout;
204 const TString layerDelimiter(
",");
205 const TString subDelimiter(
"|");
207 const size_t inputSize = GetNvar();
209 TObjArray* layerStrings = layoutString.Tokenize(layerDelimiter);
210 TIter nextLayer (layerStrings);
213 for (; layerString !=
nullptr; layerString = (
TObjString*) nextLayer()) {
218 TIter nextToken (subStrings);
221 for (; token !=
nullptr; token = (
TObjString *) nextToken()) {
227 if (strActFnc ==
"RELU") {
229 }
else if (strActFnc ==
"TANH") {
231 }
else if (strActFnc ==
"SYMMRELU") {
233 }
else if (strActFnc ==
"SOFTSIGN") {
235 }
else if (strActFnc ==
"SIGMOID") {
237 }
else if (strActFnc ==
"LINEAR") {
239 }
else if (strActFnc ==
"GAUSS") {
248 strNumNodes.ReplaceAll (
"N", strN);
249 strNumNodes.ReplaceAll (
"n", strN);
251 numNodes = fml.Eval (inputSize);
257 layout.push_back(std::make_pair(numNodes, activationFunction));
270 KeyValueVector_t blockKeyValues;
271 const TString keyValueDelim (
"=");
273 TObjArray* blockStrings = parseString.Tokenize (blockDelim);
274 TIter nextBlock (blockStrings);
277 for (; blockString !=
nullptr; blockString = (
TObjString *) nextBlock())
279 blockKeyValues.push_back (std::map<TString,TString>());
280 std::map<TString,TString>& currentBlock = blockKeyValues.back ();
283 TIter nextToken (subStrings);
286 for (; token !=
nullptr; token = (
TObjString *)nextToken())
289 int delimPos = strKeyValue.First (keyValueDelim.Data ());
295 TString strValue =
TString (strKeyValue (delimPos+1, strKeyValue.Length ()));
300 currentBlock.insert (std::make_pair (strKey, strValue));
303 return blockKeyValues;
311 std::map<TString, TString>::const_iterator it = keyValueMap.find (key);
312 if (it == keyValueMap.end()) {
336 return value.
Atoi ();
342double fetchValue (
const std::map<TString,TString>& keyValueMap,
343 TString key,
double defaultValue)
349 return value.
Atof ();
368bool fetchValue (
const std::map<TString,TString>& keyValueMap,
369 TString key,
bool defaultValue)
376 if (value ==
"TRUE" || value ==
"T" || value ==
"1") {
385std::vector<double>
fetchValue(
const std::map<TString, TString> & keyValueMap,
387 std::vector<double> defaultValue)
390 if (parseString ==
"") {
394 std::vector<double> values;
396 const TString tokenDelim (
"+");
398 TIter nextToken (tokenStrings);
400 for (; tokenString != NULL; tokenString = (
TObjString*)nextToken ()) {
401 std::stringstream sstr;
404 sstr >> currentValue;
405 values.push_back (currentValue);
414 if (IgnoreEventsWithNegWeightsInTraining()) {
416 <<
"Will ignore negative events in training!"
420 if (fArchitectureString ==
"STANDARD") {
421 Log() << kERROR <<
"The STANDARD architecture has been deprecated. "
422 "Please use Architecture=CPU or Architecture=CPU."
423 "See the TMVA Users' Guide for instructions if you "
424 "encounter problems."
426 Log() << kFATAL <<
"The STANDARD architecture has been deprecated. "
427 "Please use Architecture=CPU or Architecture=CPU."
428 "See the TMVA Users' Guide for instructions if you "
429 "encounter problems."
433 if (fArchitectureString ==
"OPENCL") {
434 Log() << kERROR <<
"The OPENCL architecture has not been implemented yet. "
435 "Please use Architecture=CPU or Architecture=CPU for the "
436 "time being. See the TMVA Users' Guide for instructions "
437 "if you encounter problems."
439 Log() << kFATAL <<
"The OPENCL architecture has not been implemented yet. "
440 "Please use Architecture=CPU or Architecture=CPU for the "
441 "time being. See the TMVA Users' Guide for instructions "
442 "if you encounter problems."
446 if (fArchitectureString ==
"GPU") {
448 Log() << kERROR <<
"CUDA backend not enabled. Please make sure "
449 "you have CUDA installed and it was successfully "
452 Log() << kFATAL <<
"CUDA backend not enabled. Please make sure "
453 "you have CUDA installed and it was successfully "
459 if (fArchitectureString ==
"CPU") {
461 Log() << kERROR <<
"Multi-core CPU backend not enabled. Please make sure "
462 "you have a BLAS implementation and it was successfully "
463 "detected by CMake as well that the imt CMake flag is set."
465 Log() << kFATAL <<
"Multi-core CPU backend not enabled. Please make sure "
466 "you have a BLAS implementation and it was successfully "
467 "detected by CMake as well that the imt CMake flag is set."
477 size_t inputSize = GetNVariables ();
478 size_t outputSize = 1;
480 outputSize = GetNTargets();
482 outputSize = DataInfo().GetNClasses();
485 fNet.SetBatchSize(1);
486 fNet.SetInputWidth(inputSize);
488 auto itLayout = std::begin (fLayout);
489 auto itLayoutEnd = std::end (fLayout)-1;
490 for ( ; itLayout != itLayoutEnd; ++itLayout) {
491 fNet.AddLayer((*itLayout).first, (*itLayout).second);
502 if (fErrorStrategy ==
"SUMOFSQUARES") {
503 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
505 if (fErrorStrategy ==
"CROSSENTROPY") {
510 if (fErrorStrategy !=
"SUMOFSQUARES") {
511 Log () << kWARNING <<
"For regression only SUMOFSQUARES is a valid "
512 <<
" neural net error function. Setting error function to "
513 <<
" SUMOFSQUARES now." <<
Endl;
515 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
518 if (fErrorStrategy ==
"SUMOFSQUARES") {
519 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
521 if (fErrorStrategy ==
"CROSSENTROPY") {
524 if (fErrorStrategy ==
"MUTUALEXCLUSIVE") {
525 fNet.SetLossFunction(ELossFunction::kSoftmaxCrossEntropy);
534 if (fWeightInitializationString ==
"XAVIER") {
537 else if (fWeightInitializationString ==
"XAVIERUNIFORM") {
549 GetNumValidationSamples();
551 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
555 std::cout <<
"Parsed Training DNN string " << fTrainingStrategyString << std::endl;
556 std::cout <<
"STring has size " << strategyKeyValues.size() << std::endl;
557 for (
auto& block : strategyKeyValues) {
567 std::vector<Double_t>());
587 fTrainingSettings.push_back(settings);
602 Int_t nValidationSamples = 0;
607 if (fValidationSize.EndsWith(
"%")) {
612 Double_t valSizeAsDouble = fValidationSize.Atof() / 100.0;
613 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
615 Log() << kFATAL <<
"Cannot parse number \"" << fValidationSize
616 <<
"\". Expected string like \"20%\" or \"20.0%\"." <<
Endl;
618 }
else if (fValidationSize.IsFloat()) {
619 Double_t valSizeAsDouble = fValidationSize.Atof();
621 if (valSizeAsDouble < 1.0) {
623 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
626 nValidationSamples = valSizeAsDouble;
629 Log() << kFATAL <<
"Cannot parse number \"" << fValidationSize <<
"\". Expected string like \"0.2\" or \"100\"."
635 if (nValidationSamples < 0) {
636 Log() << kFATAL <<
"Validation size \"" << fValidationSize <<
"\" is negative." <<
Endl;
639 if (nValidationSamples == 0) {
640 Log() << kFATAL <<
"Validation size \"" << fValidationSize <<
"\" is zero." <<
Endl;
643 if (nValidationSamples >= (
Int_t)trainingSetSize) {
644 Log() << kFATAL <<
"Validation size \"" << fValidationSize
645 <<
"\" is larger than or equal in size to training set (size=\"" << trainingSetSize <<
"\")." <<
Endl;
648 return nValidationSamples;
655 if (fInteractive && fInteractive->NotInitialized()){
656 std::vector<TString> titles = {
"Error on training set",
"Error on test set"};
657 fInteractive->Init(titles);
663 size_t nValidationSamples = GetNumValidationSamples();
664 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
665 size_t nTestSamples = nValidationSamples;
667 if (nTrainingSamples < settings.batchSize or
668 nValidationSamples < settings.batchSize or
669 nTestSamples < settings.batchSize) {
670 Log() << kFATAL <<
"Number of samples in the datasets are train: "
671 << nTrainingSamples <<
" valid: " << nValidationSamples
672 <<
" test: " << nTestSamples <<
". "
673 <<
"One of these is smaller than the batch size of "
674 << settings.batchSize <<
". Please increase the batch"
675 <<
" size to be at least the same size as the smallest"
676 <<
" of these values." <<
Endl;
680 if (fArchitectureString ==
"GPU") {
682 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
685 }
else if (fArchitectureString ==
"OpenCL") {
686 Log() << kFATAL <<
"OpenCL backend not yet supported." <<
Endl;
688 }
else if (fArchitectureString ==
"CPU") {
690 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
695 Log() << kINFO <<
"Using Standard Implementation.";
697 std::vector<Pattern> trainPattern;
698 std::vector<Pattern> testPattern;
700 size_t nValidationSamples = GetNumValidationSamples();
701 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
703 const std::vector<TMVA::Event *> &allData = GetEventCollection(
Types::kTraining);
704 const std::vector<TMVA::Event *> eventCollectionTraining{allData.begin(), allData.begin() + nTrainingSamples};
705 const std::vector<TMVA::Event *> eventCollectionTesting{allData.begin() + nTrainingSamples, allData.end()};
707 for (
auto &event : eventCollectionTraining) {
708 const std::vector<Float_t>& values =
event->GetValues();
710 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
711 trainPattern.push_back(
Pattern (values.begin(),
714 event->GetWeight()));
715 trainPattern.back().addInput(1.0);
717 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
718 oneHot[
event->GetClass()] = 1.0;
719 trainPattern.push_back(
Pattern (values.begin(), values.end(),
720 oneHot.cbegin(), oneHot.cend(),
721 event->GetWeight()));
722 trainPattern.back().addInput(1.0);
724 const std::vector<Float_t>& targets =
event->GetTargets ();
725 trainPattern.push_back(
Pattern(values.begin(),
729 event->GetWeight ()));
730 trainPattern.back ().addInput (1.0);
734 for (
auto &event : eventCollectionTesting) {
735 const std::vector<Float_t>& values =
event->GetValues();
737 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
738 testPattern.push_back(
Pattern (values.begin(),
741 event->GetWeight()));
742 testPattern.back().addInput(1.0);
744 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
745 oneHot[
event->GetClass()] = 1.0;
746 testPattern.push_back(
Pattern (values.begin(), values.end(),
747 oneHot.cbegin(), oneHot.cend(),
748 event->GetWeight()));
749 testPattern.back().addInput(1.0);
751 const std::vector<Float_t>& targets =
event->GetTargets ();
752 testPattern.push_back(
Pattern(values.begin(),
756 event->GetWeight ()));
757 testPattern.back ().addInput (1.0);
762 std::vector<double> weights;
769 for (
size_t i = 0; i < fNet.GetDepth(); i++) {
774 case EActivationFunction::kRelu:
g = EnumFunction::RELU;
break;
777 case EActivationFunction::kSymmRelu:
g = EnumFunction::SYMMRELU;
break;
778 case EActivationFunction::kSoftSign:
g = EnumFunction::SOFTSIGN;
break;
781 if (i < fNet.GetDepth() - 1) {
785 switch(fOutputFunction) {
794 switch(fNet.GetLossFunction()) {
795 case ELossFunction::kMeanSquaredError:
801 case ELossFunction::kSoftmaxCrossEntropy:
806 switch(fWeightInitialization) {
809 std::back_inserter(weights));
813 std::back_inserter(weights));
817 std::back_inserter(weights));
822 for (
auto s : fTrainingSettings) {
825 switch(
s.regularization) {
827 case ERegularization::kL1:
r = EnumRegularization::L1;
break;
828 case ERegularization::kL2:
r = EnumRegularization::L2;
break;
832 s.testInterval,
s.weightDecay,
r,
834 s.momentum, 1,
s.multithreading);
835 std::shared_ptr<Settings> ptrSettings(settings);
836 ptrSettings->setMonitoring (0);
838 <<
"Training with learning rate = " << ptrSettings->learningRate ()
839 <<
", momentum = " << ptrSettings->momentum ()
840 <<
", repetitions = " << ptrSettings->repetitions ()
843 ptrSettings->setProgressLimits ((idxSetting)*100.0/(fSettings.size ()),
844 (idxSetting+1)*100.0/(fSettings.size ()));
846 const std::vector<double>& dropConfig = ptrSettings->dropFractions ();
847 if (!dropConfig.empty ()) {
848 Log () << kINFO <<
"Drop configuration" <<
Endl
849 <<
" drop repetitions = " << ptrSettings->dropRepetitions()
854 for (
auto f : dropConfig) {
855 Log () << kINFO <<
" Layer " << idx <<
" = " <<
f <<
Endl;
861 ptrSettings->momentum(),
862 ptrSettings->repetitions());
863 net.
train(weights, trainPattern, testPattern, minimizer, *ptrSettings.get());
868 size_t weightIndex = 0;
869 for (
size_t l = 0;
l < fNet.GetDepth();
l++) {
870 auto & layerWeights = fNet.GetLayer(
l).GetWeights();
871 for (
Int_t j = 0; j < layerWeights.GetNcols(); j++) {
872 for (
Int_t i = 0; i < layerWeights.GetNrows(); i++) {
873 layerWeights(i,j) = weights[weightIndex];
877 auto & layerBiases = fNet.GetLayer(
l).GetBiases();
879 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
880 layerBiases(i,0) = weights[weightIndex];
884 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
885 layerBiases(i,0) = 0.0;
889 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
899 Log() << kINFO <<
"Start of neural network training on GPU." <<
Endl <<
Endl;
901 size_t nValidationSamples = GetNumValidationSamples();
902 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
903 size_t nTestSamples = nValidationSamples;
905 Log() << kDEBUG <<
"Using " << nValidationSamples <<
" validation samples." <<
Endl;
906 Log() << kDEBUG <<
"Using " << nTestSamples <<
" training samples." <<
Endl;
908 size_t trainingPhase = 1;
909 fNet.Initialize(fWeightInitialization);
913 fInteractive->ClearGraphs();
922 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
923 for (
auto & p : dropoutVector) {
929 auto testNet = net.
CreateClone(settings.batchSize);
931 Log() << kINFO <<
"Training phase " << trainingPhase <<
" of "
932 << fTrainingSettings.size() <<
":" <<
Endl;
939 const std::vector<Event *> trainingInputData =
940 std::vector<Event *>(allData.begin(), allData.begin() + nTrainingSamples);
941 const std::vector<Event *> testInputData =
942 std::vector<Event *>(allData.begin() + nTrainingSamples, allData.end());
944 if (trainingInputData.size() != nTrainingSamples) {
945 Log() << kFATAL <<
"Inconsistent training sample size" <<
Endl;
947 if (testInputData.size() != nTestSamples) {
948 Log() << kFATAL <<
"Inconsistent test sample size" <<
Endl;
952 TMVAInput_t trainingTuple = std::tie(trainingInputData, DataInfo());
953 TMVAInput_t testTuple = std::tie(testInputData, DataInfo());
954 DataLoader_t trainingData(trainingTuple, nTrainingSamples,
957 DataLoader_t testData(testTuple, nTestSamples, testNet.GetBatchSize(),
961 settings.convergenceSteps,
962 settings.testInterval);
964 std::vector<TNet<TCuda<>>> nets{};
965 std::vector<TBatch<TCuda<>>> batches{};
966 nets.reserve(nThreads);
967 for (
size_t i = 0; i < nThreads; i++) {
969 for (
size_t j = 0; j < net.
GetDepth(); j++)
971 auto &masterLayer = net.
GetLayer(j);
972 auto &layer = nets.back().GetLayer(j);
974 masterLayer.GetWeights());
976 masterLayer.GetBiases());
980 bool converged =
false;
981 size_t stepCount = 0;
982 size_t batchesInEpoch = nTrainingSamples / net.
GetBatchSize();
984 std::chrono::time_point<std::chrono::system_clock> start, end;
985 start = std::chrono::system_clock::now();
988 Log() << std::setw(10) <<
"Epoch" <<
" | "
989 << std::setw(12) <<
"Train Err."
990 << std::setw(12) <<
"Test Err."
991 << std::setw(12) <<
"GFLOP/s"
992 << std::setw(12) <<
"Conv. Steps" <<
Endl;
993 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);
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);
1027 end = std::chrono::system_clock::now();
1031 for (
auto batch : trainingData) {
1032 auto inputMatrix = batch.GetInput();
1033 auto outputMatrix = batch.GetOutput();
1034 trainingError += net.
Loss(inputMatrix, outputMatrix);
1036 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
1039 std::chrono::duration<double> elapsed_seconds = end - start;
1040 double seconds = elapsed_seconds.count();
1041 double nFlops = (double) (settings.testInterval * batchesInEpoch);
1045 start = std::chrono::system_clock::now();
1048 fInteractive->AddPoint(stepCount, trainingError, testError);
1051 if (fExitFromTraining)
break;
1053 Log() << std::setw(10) << stepCount <<
" | "
1054 << std::setw(12) << trainingError
1055 << std::setw(12) << testError
1056 << std::setw(12) << nFlops / seconds
1072 Log() << kFATAL <<
"CUDA backend not enabled. Please make sure "
1073 "you have CUDA installed and it was successfully "
1074 "detected by CMAKE." <<
Endl;
1084 Log() << kINFO <<
"Start of neural network training on CPU." <<
Endl <<
Endl;
1086 size_t nValidationSamples = GetNumValidationSamples();
1087 size_t nTrainingSamples = GetEventCollection(
Types::kTraining).size() - nValidationSamples;
1088 size_t nTestSamples = nValidationSamples;
1090 Log() << kDEBUG <<
"Using " << nValidationSamples <<
" validation samples." <<
Endl;
1091 Log() << kDEBUG <<
"Using " << nTestSamples <<
" training samples." <<
Endl;
1093 fNet.Initialize(fWeightInitialization);
1095 size_t trainingPhase = 1;
1099 fInteractive->ClearGraphs();
1102 Log() <<
"Training phase " << trainingPhase <<
" of "
1103 << fTrainingSettings.size() <<
":" <<
Endl;
1111 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
1112 for (
auto & p : dropoutVector) {
1117 auto testNet = net.
CreateClone(settings.batchSize);
1122 const std::vector<Event *> &allData = GetEventCollection(
Types::kTraining);
1123 const std::vector<Event *> trainingInputData =
1124 std::vector<Event *>(allData.begin(), allData.begin() + nTrainingSamples);
1125 const std::vector<Event *> testInputData =
1126 std::vector<Event *>(allData.begin() + nTrainingSamples, allData.end());
1128 if (trainingInputData.size() != nTrainingSamples) {
1129 Log() << kFATAL <<
"Inconsistent training sample size" <<
Endl;
1131 if (testInputData.size() != nTestSamples) {
1132 Log() << kFATAL <<
"Inconsistent test sample size" <<
Endl;
1135 size_t nThreads = 1;
1136 TMVAInput_t trainingTuple = std::tie(trainingInputData, DataInfo());
1137 TMVAInput_t testTuple = std::tie(testInputData, DataInfo());
1138 DataLoader_t trainingData(trainingTuple, nTrainingSamples,
1141 DataLoader_t testData(testTuple, nTestSamples, testNet.GetBatchSize(),
1145 settings.convergenceSteps,
1146 settings.testInterval);
1148 std::vector<TNet<TCpu<>>> nets{};
1149 std::vector<TBatch<TCpu<>>> batches{};
1150 nets.reserve(nThreads);
1151 for (
size_t i = 0; i < nThreads; i++) {
1152 nets.push_back(net);
1153 for (
size_t j = 0; j < net.
GetDepth(); j++)
1155 auto &masterLayer = net.
GetLayer(j);
1156 auto &layer = nets.back().GetLayer(j);
1158 masterLayer.GetWeights());
1160 masterLayer.GetBiases());
1164 bool converged =
false;
1165 size_t stepCount = 0;
1166 size_t batchesInEpoch = nTrainingSamples / net.
GetBatchSize();
1168 std::chrono::time_point<std::chrono::system_clock> start, end;
1169 start = std::chrono::system_clock::now();
1171 if (!fInteractive) {
1172 Log() << std::setw(10) <<
"Epoch" <<
" | "
1173 << std::setw(12) <<
"Train Err."
1174 << std::setw(12) <<
"Test Err."
1175 << std::setw(12) <<
"GFLOP/s"
1176 << std::setw(12) <<
"Conv. Steps" <<
Endl;
1177 std::string separator(62,
'-');
1185 trainingData.Shuffle();
1186 for (
size_t i = 0; i < batchesInEpoch; i += nThreads) {
1188 for (
size_t j = 0; j < nThreads; j++) {
1189 batches.reserve(nThreads);
1190 batches.push_back(trainingData.GetBatch());
1192 if (settings.momentum > 0.0) {
1193 minimizer.
StepMomentum(net, nets, batches, settings.momentum);
1195 minimizer.
Step(net, nets, batches);
1203 for (
auto batch : testData) {
1204 auto inputMatrix = batch.GetInput();
1205 auto outputMatrix = batch.GetOutput();
1206 auto weightMatrix = batch.GetWeights();
1207 testError += testNet.Loss(inputMatrix, outputMatrix, weightMatrix);
1209 testError /= (
Double_t) (nTestSamples / settings.batchSize);
1211 end = std::chrono::system_clock::now();
1215 for (
auto batch : trainingData) {
1216 auto inputMatrix = batch.GetInput();
1217 auto outputMatrix = batch.GetOutput();
1218 auto weightMatrix = batch.GetWeights();
1219 trainingError += net.
Loss(inputMatrix, outputMatrix, weightMatrix);
1221 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
1224 fInteractive->AddPoint(stepCount, trainingError, testError);
1225 fIPyCurrentIter = 100*(double)minimizer.
GetConvergenceCount() /(double)settings.convergenceSteps;
1226 if (fExitFromTraining)
break;
1230 std::chrono::duration<double> elapsed_seconds = end - start;
1231 double seconds = elapsed_seconds.count();
1232 double nFlops = (double) (settings.testInterval * batchesInEpoch);
1236 start = std::chrono::system_clock::now();
1239 fInteractive->AddPoint(stepCount, trainingError, testError);
1242 if (fExitFromTraining)
break;
1244 Log() << std::setw(10) << stepCount <<
" | "
1245 << std::setw(12) << trainingError
1246 << std::setw(12) << testError
1247 << std::setw(12) << nFlops / seconds
1258 auto & layer = fNet.GetLayer(
l);
1265 Log() << kFATAL <<
"Multi-core CPU backend not enabled. Please make sure "
1266 "you have a BLAS implementation and it was successfully "
1267 "detected by CMake as well that the imt CMake flag is set." <<
Endl;
1275 size_t nVariables = GetEvent()->GetNVariables();
1279 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1280 for (
size_t i = 0; i < nVariables; i++) {
1281 X(0,i) = inputValues[i];
1284 fNet.Prediction(YHat, X, fOutputFunction);
1292 size_t nVariables = GetEvent()->GetNVariables();
1295 const Event *ev = GetEvent();
1296 const std::vector<Float_t>& inputValues = ev->
GetValues();
1297 for (
size_t i = 0; i < nVariables; i++) {
1298 X(0,i) = inputValues[i];
1301 size_t nTargets = std::max(1u, ev->
GetNTargets());
1303 std::vector<Float_t>
output(nTargets);
1304 auto net = fNet.CreateClone(1);
1305 net.Prediction(YHat, X, fOutputFunction);
1307 for (
size_t i = 0; i < nTargets; i++)
1310 if (fRegressionReturnVal == NULL) {
1311 fRegressionReturnVal =
new std::vector<Float_t>();
1313 fRegressionReturnVal->clear();
1316 for (
size_t i = 0; i < nTargets; ++i) {
1320 const Event* evT2 = GetTransformationHandler().InverseTransform(evT);
1321 for (
size_t i = 0; i < nTargets; ++i) {
1322 fRegressionReturnVal->push_back(evT2->
GetTarget(i));
1325 return *fRegressionReturnVal;
1330 size_t nVariables = GetEvent()->GetNVariables();
1332 Matrix_t YHat(1, DataInfo().GetNClasses());
1333 if (fMulticlassReturnVal == NULL) {
1334 fMulticlassReturnVal =
new std::vector<Float_t>(DataInfo().GetNClasses());
1337 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1338 for (
size_t i = 0; i < nVariables; i++) {
1339 X(0,i) = inputValues[i];
1342 fNet.Prediction(YHat, X, fOutputFunction);
1343 for (
size_t i = 0; i < (size_t) YHat.GetNcols(); i++) {
1344 (*fMulticlassReturnVal)[i] = YHat(0, i);
1346 return *fMulticlassReturnVal;
1354 Int_t inputWidth = fNet.GetInputWidth();
1355 Int_t depth = fNet.GetDepth();
1356 char lossFunction =
static_cast<char>(fNet.GetLossFunction());
1358 gTools().StringFromInt(inputWidth));
1362 TString(
static_cast<char>(fOutputFunction)));
1364 for (
Int_t i = 0; i < depth; i++) {
1365 const auto& layer = fNet.GetLayer(i);
1367 int activationFunction =
static_cast<int>(layer.GetActivationFunction());
1370 WriteMatrixXML(layerxml,
"Weights", layer.GetWeights());
1371 WriteMatrixXML(layerxml,
"Biases", layer.GetBiases());
1385 fNet.SetBatchSize(1);
1387 size_t inputWidth, depth;
1390 char lossFunctionChar;
1392 char outputFunctionChar;
1395 fNet.SetInputWidth(inputWidth);
1396 fNet.SetLossFunction(
static_cast<ELossFunction>(lossFunctionChar));
1399 size_t previousWidth = inputWidth;
1401 for (
size_t i = 0; i < depth; i++) {
1417 ReadMatrixXML(layerXML,
"Weights", weights);
1418 ReadMatrixXML(layerXML,
"Biases", biases);
1419 fNet.GetLayer(i).GetWeights() = weights;
1420 fNet.GetLayer(i).GetBiases() = biases;
1423 previousWidth =
width;
1438 for (
UInt_t ivar=0; ivar<GetNvar(); ivar++) {
1439 fRanking->AddRank(
Rank( GetInputLabel(ivar), 1.0));
1463 Log() << col <<
"--- Short description:" << colres <<
Endl;
1465 Log() <<
"The DNN neural network is a feedforward" <<
Endl;
1466 Log() <<
"multilayer perceptron implementation. The DNN has a user-" <<
Endl;
1467 Log() <<
"defined hidden layer architecture, where the number of input (output)" <<
Endl;
1468 Log() <<
"nodes is determined by the input variables (output classes, i.e., " <<
Endl;
1469 Log() <<
"signal and one background, regression or multiclass). " <<
Endl;
1471 Log() << col <<
"--- Performance optimisation:" << colres <<
Endl;
1474 const char* txt =
"The DNN supports various options to improve performance in terms of training speed and \n \
1475reduction of overfitting: \n \
1477 - different training settings can be stacked. Such that the initial training \n\
1478 is done with a large learning rate and a large drop out fraction whilst \n \
1479 in a later stage learning rate and drop out can be reduced. \n \
1482 initial training stage: 0.0 for the first layer, 0.5 for later layers. \n \
1483 later training stage: 0.1 or 0.0 for all layers \n \
1484 final training stage: 0.0] \n \
1485 Drop out is a technique where a at each training cycle a fraction of arbitrary \n \
1486 nodes is disabled. This reduces co-adaptation of weights and thus reduces overfitting. \n \
1487 - L1 and L2 regularization are available \n \
1489 [recommended 10 - 150] \n \
1490 Arbitrary mini-batch sizes can be chosen. \n \
1491 - Multithreading \n \
1492 [recommended: True] \n \
1493 Multithreading can be turned on. The minibatches are distributed to the available \n \
1494 cores. The algorithm is lock-free (\"Hogwild!\"-style) for each cycle. \n \
1498 - example: \"TANH|(N+30)*2,TANH|(N+30),LINEAR\" \n \
1500 . two hidden layers (separated by \",\") \n \
1501 . the activation function is TANH (other options: RELU, SOFTSIGN, LINEAR) \n \
1502 . the activation function for the output layer is LINEAR \n \
1503 . the first hidden layer has (N+30)*2 nodes where N is the number of input neurons \n \
1504 . the second hidden layer has N+30 nodes, where N is the number of input neurons \n \
1505 . the number of nodes in the output layer is determined by the number of output nodes \n \
1506 and can therefore not be chosen freely. \n \
1508 \"ErrorStrategy\": \n \
1510 The error of the neural net is determined by a sum-of-squares error function \n \
1511 For regression, this is the only possible choice. \n \
1513 The error of the neural net is determined by a cross entropy function. The \n \
1514 output values are automatically (internally) transformed into probabilities \n \
1515 using a sigmoid function. \n \
1516 For signal/background classification this is the default choice. \n \
1517 For multiclass using cross entropy more than one or no output classes \n \
1518 can be equally true or false (e.g. Event 0: A and B are true, Event 1: \n \
1519 A and C is true, Event 2: C is true, ...) \n \
1520 - MUTUALEXCLUSIVE \n \
1521 In multiclass settings, exactly one of the output classes can be true (e.g. either A or B or C) \n \
1523 \"WeightInitialization\" \n \
1526 \"Xavier Glorot & Yoshua Bengio\"-style of initializing the weights. The weights are chosen randomly \n \
1527 such that the variance of the values of the nodes is preserved for each layer. \n \
1528 - XAVIERUNIFORM \n \
1529 The same as XAVIER, but with uniformly distributed weights instead of gaussian weights \n \
1531 Random values scaled by the layer size \n \
1533 \"TrainingStrategy\" \n \
1534 - 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 \
1535 - explanation: two stacked training settings separated by \"|\" \n \
1536 . 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 \
1537 . 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 \
1538 . LearningRate : \n \
1539 - recommended for classification: 0.1 initially, 1e-4 later \n \
1540 - recommended for regression: 1e-4 and less \n \
1542 preserve a fraction of the momentum for the next training batch [fraction = 0.0 - 1.0] \n \
1543 . Repetitions : \n \
1544 train \"Repetitions\" repetitions with the same minibatch before switching to the next one \n \
1545 . ConvergenceSteps : \n \
1546 Assume that convergence is reached after \"ConvergenceSteps\" cycles where no improvement \n \
1547 of the error on the test samples has been found. (Mind that only at each \"TestRepetitions\" \n \
1548 cycle the test samples are evaluated and thus the convergence is checked) \n \
1550 Size of the mini-batches. \n \
1551 . TestRepetitions \n \
1552 Perform testing the neural net on the test samples each \"TestRepetitions\" cycle \n \
1554 If \"Renormalize\" is set to L1 or L2, \"WeightDecay\" provides the renormalization factor \n \
1556 NONE, L1 (|w|) or L2 (w^2) \n \
1558 Drop a fraction of arbitrary nodes of each of the layers according to the values given \n \
1559 in the DropConfig. \n \
1560 [example: DropConfig=0.0+0.5+0.3 \n \
1561 meaning: drop no nodes in layer 0 (input layer), half of the nodes in layer 1 and 30% of the nodes \n \
1563 recommended: leave all the nodes turned on for the input layer (layer 0) \n \
1564 turn off half of the nodes in later layers for the initial training; leave all nodes \n \
1565 turned on (0.0) in later training stages] \n \
1566 . DropRepetitions \n \
1567 Each \"DropRepetitions\" cycle the configuration of which nodes are dropped is changed \n \
1568 [recommended : 1] \n \
1569 . Multithreading \n \
1570 turn on multithreading [recommended: True] \n \
#define REGISTER_METHOD(CLASS)
for example
include TDocParser_001 C image html pict1_TDocParser_001 png width
Bool_t WriteOptionsReference() const
Layer defines the layout of a layer.
void setInputSize(size_t sizeInput)
set the input size of the DNN
void SetIpythonInteractive(IPythonInteractive *fI, bool *fE, UInt_t *M, UInt_t *C)
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
Settings for the training of the neural net.
Steepest Gradient Descent algorithm (SGD)
static void Copy(TCpuMatrix< Scalar_t > &B, const TCpuMatrix< Scalar_t > &A)
static void Copy(TCudaMatrix< AFloat > &B, const TCudaMatrix< AFloat > &A)
Copy the elements of matrix A into matrix B.
bool HasConverged()
Increases the minimization step counter by the test error evaluation period and uses the current inte...
void Step(Net_t &net, Matrix_t &input, const Matrix_t &output, const Matrix_t &weights)
Perform a single optimization step on a given batch.
size_t GetTestInterval() const
void StepMomentum(Net_t &master, std::vector< Net_t > &nets, std::vector< TBatch< Architecture_t > > &batches, Scalar_t momentum)
Same as the Step(...) method for multiple batches but uses momentum.
size_t GetConvergenceCount() const
size_t GetConvergenceSteps() const
Generic neural network class.
void SetWeightDecay(Scalar_t weightDecay)
Scalar_t Loss(const Matrix_t &Y, const Matrix_t &weights, bool includeRegularization=true) const
Evaluate the loss function of the net using the activations that are currently stored in the output l...
void SetRegularization(ERegularization R)
size_t GetOutputWidth() const
void InitializeGradients()
Initialize the gradients in the net to zero.
TNet< Architecture_t, TSharedLayer< Architecture_t > > CreateClone(size_t batchSize)
Create a clone that uses the same weight and biases matrices but potentially a difference batch size.
size_t GetBatchSize() const
void SetDropoutProbabilities(const std::vector< Double_t > &probabilities)
size_t GetInputWidth() const
Layer_t & GetLayer(size_t i)
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
UInt_t GetNTargets() const
accessor to the number of targets
std::vector< Float_t > & GetValues()
Float_t GetTarget(UInt_t itgt) const
Deep Neural Network Implementation.
virtual Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets)
virtual const std::vector< Float_t > & GetMulticlassValues()
UInt_t GetNumValidationSamples()
void ReadWeightsFromXML(void *wghtnode)
std::vector< std::map< TString, TString > > KeyValueVector_t
typename Architecture_t::Matrix_t Matrix_t
void ReadWeightsFromStream(std::istream &i)
LayoutVector_t ParseLayoutString(TString layerSpec)
void MakeClassSpecific(std::ostream &, const TString &) const
MethodDNN(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption)
DNN::EInitialization fWeightInitialization
virtual Double_t GetMvaValue(Double_t *err=0, Double_t *errUpper=0)
const Ranking * CreateRanking()
KeyValueVector_t ParseKeyValueString(TString parseString, TString blockDelim, TString tokenDelim)
DNN::EOutputFunction fOutputFunction
void AddWeightsXMLTo(void *parent) const
void GetHelpMessage() const
virtual const std::vector< Float_t > & GetRegressionValues()
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.
Double_t Atof() const
Return floating-point value contained in string.
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
const char * Data() const
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 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
XMLNodePointer_t NewChild(XMLNodePointer_t parent, XMLNsPointer_t ns, const char *name, const char *content=0)
create new child element for parent node
std::string GetName(const std::string &scope_name)
static constexpr double s
EOutputFunction
Enum that represents output functions.
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.
EActivationFunction
Enum that represents layer activation functions.
ELossFunction
Enum that represents objective functions for the net, i.e.
std::tuple< const std::vector< Event * > &, const DataSetInfo & > TMVAInput_t
Abstract ClassifierFactory template that handles arbitrary types.
TString fetchValue(const std::map< TString, TString > &keyValueMap, TString key)
MsgLogger & Endl(MsgLogger &ml)
DNN::ERegularization regularization
std::vector< Double_t > dropoutProbabilities