75 const TString& methodTitle,
77 const TString& theOption)
79 fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
80 fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
81 fTrainingSettings(), fResume(false), fSettings()
88 const TString& theWeightFile)
90 fWeightInitialization(), fOutputFunction(), fLayoutString(), fErrorStrategy(),
91 fTrainingStrategyString(), fWeightInitializationString(), fArchitectureString(),
92 fTrainingSettings(), fResume(false), fSettings()
134 DeclareOptionRef(fLayoutString=
"SOFTSIGN|(N+100)*2,LINEAR",
136 "Layou of the network.");
138 DeclareOptionRef(fErrorStrategy=
"CROSSENTROPY",
140 "Loss function: Mean squared error (regression)"
141 " or cross entropy (binary classifcation).");
142 AddPreDefVal(TString(
"CROSSENTROPY"));
143 AddPreDefVal(TString(
"SUMOFSQUARES"));
145 DeclareOptionRef(fWeightInitializationString=
"XAVIER",
146 "WeightInitialization",
147 "Weight initialization strategy");
148 AddPreDefVal(TString(
"XAVIER"));
149 AddPreDefVal(TString(
"XAVIERUNIFORM"));
151 DeclareOptionRef(fArchitectureString=
"STANDARD",
153 "Which architecture to perfrom the training on.");
154 AddPreDefVal(TString(
"STANDARD"));
155 AddPreDefVal(TString(
"CPU"));
156 AddPreDefVal(TString(
"GPU"));
157 AddPreDefVal(TString(
"OPENCL"));
160 fTrainingStrategyString =
"LearningRate=1e-1,"
163 "ConvergenceSteps=50,"
169 "DropRepetitions=5|LearningRate=1e-4,"
172 "ConvergenceSteps=50,"
177 "DropConfig=0.0+0.5+0.5,"
179 "Multithreading=True",
181 "Defines the training strategies.");
191 const TString layerDelimiter(
",");
192 const TString subDelimiter(
"|");
194 const size_t inputSize = GetNvar();
196 TObjArray* layerStrings = layoutString.Tokenize(layerDelimiter);
197 TIter nextLayer (layerStrings);
200 for (; layerString !=
nullptr; layerString = (
TObjString*) nextLayer()) {
202 EActivationFunction activationFunction = EActivationFunction::kTanh;
205 TIter nextToken (subStrings);
208 for (; token !=
nullptr; token = (
TObjString *) nextToken()) {
214 if (strActFnc ==
"RELU") {
216 }
else if (strActFnc ==
"TANH") {
218 }
else if (strActFnc ==
"SYMMRELU") {
220 }
else if (strActFnc ==
"SOFTSIGN") {
222 }
else if (strActFnc ==
"SIGMOID") {
224 }
else if (strActFnc ==
"LINEAR") {
226 }
else if (strActFnc ==
"GAUSS") {
233 TString strNumNodes (token->
GetString ());
235 strNumNodes.ReplaceAll (
"N", strN);
236 strNumNodes.ReplaceAll (
"n", strN);
238 numNodes = fml.
Eval (inputSize);
244 layout.push_back(std::make_pair(numNodes, activationFunction));
257 const TString keyValueDelim (
"=");
259 TObjArray* blockStrings = parseString.Tokenize (blockDelim);
260 TIter nextBlock (blockStrings);
263 for (; blockString !=
nullptr; blockString = (
TObjString *) nextBlock())
265 blockKeyValues.push_back (std::map<TString,TString>());
266 std::map<TString,TString>& currentBlock = blockKeyValues.back ();
269 TIter nextToken (subStrings);
272 for (; token !=
nullptr; token = (
TObjString *)nextToken())
274 TString strKeyValue (token->
GetString ());
275 int delimPos = strKeyValue.First (keyValueDelim.Data ());
279 TString strKey = TString (strKeyValue (0, delimPos));
281 TString strValue = TString (strKeyValue (delimPos+1, strKeyValue.Length ()));
286 currentBlock.insert (std::make_pair (strKey, strValue));
289 return blockKeyValues;
293 TString
fetchValue (
const std::map<TString, TString>& keyValueMap, TString key)
296 std::map<TString, TString>::const_iterator it = keyValueMap.find (key);
297 if (it == keyValueMap.end()) {
304 template <
typename T>
305 T fetchValue(
const std::map<TString,TString>& keyValueMap,
315 TString value (
fetchValue (keyValueMap, key));
319 return value.Atoi ();
324 double fetchValue (
const std::map<TString,TString>& keyValueMap,
325 TString key,
double defaultValue)
327 TString value (
fetchValue (keyValueMap, key));
331 return value.Atof ();
336 TString
fetchValue (
const std::map<TString,TString>& keyValueMap,
337 TString key, TString defaultValue)
339 TString value (
fetchValue (keyValueMap, key));
348 bool fetchValue (
const std::map<TString,TString>& keyValueMap,
349 TString key,
bool defaultValue)
351 TString value (
fetchValue (keyValueMap, key));
356 if (value ==
"TRUE" || value ==
"T" || value ==
"1") {
364 std::vector<double>
fetchValue(
const std::map<TString, TString> & keyValueMap,
366 std::vector<double> defaultValue)
368 TString parseString (
fetchValue (keyValueMap, key));
369 if (parseString ==
"") {
372 parseString.ToUpper ();
373 std::vector<double> values;
375 const TString tokenDelim (
"+");
376 TObjArray* tokenStrings = parseString.Tokenize (tokenDelim);
377 TIter nextToken (tokenStrings);
379 for (; tokenString !=
NULL; tokenString = (
TObjString*)nextToken ()) {
380 std::stringstream sstr;
382 sstr << tokenString->
GetString ().Data ();
383 sstr >> currentValue;
384 values.push_back (currentValue);
392 if (IgnoreEventsWithNegWeightsInTraining()) {
394 <<
"Will ignore negative events in training!"
403 size_t inputSize = GetNVariables ();
404 size_t outputSize = 1;
405 if (GetNTargets() != 0) {
406 outputSize = GetNTargets();
407 }
else if (DataInfo().GetNClasses() > 2) {
408 outputSize = DataInfo().GetNClasses();
411 fNet.SetBatchSize(1);
412 fNet.SetInputWidth(inputSize);
414 auto itLayout = std::begin (fLayout);
415 auto itLayoutEnd = std::end (fLayout)-1;
416 for ( ; itLayout != itLayoutEnd; ++itLayout) {
417 fNet.AddLayer((*itLayout).first, (*itLayout).second);
419 fNet.AddLayer(outputSize, EActivationFunction::kIdentity);
425 fOutputFunction = EOutputFunction::kSigmoid;
428 if (fErrorStrategy ==
"SUMOFSQUARES") {
429 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
431 if (fErrorStrategy ==
"CROSSENTROPY") {
434 fOutputFunction = EOutputFunction::kSigmoid;
436 if (fErrorStrategy !=
"SUMOFSQUARES") {
437 Log () <<
kWARNING <<
"For regression only SUMOFSQUARES is a valid "
438 <<
" neural net error function. Setting error function to "
439 <<
" SUMOFSQUARES now." <<
Endl;
441 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
442 fOutputFunction = EOutputFunction::kIdentity;
444 if (fErrorStrategy ==
"SUMOFSQUARES") {
445 fNet.SetLossFunction(ELossFunction::kMeanSquaredError);
447 if (fErrorStrategy ==
"CROSSENTROPY") {
450 if (fErrorStrategy ==
"MUTUALEXCLUSIVE") {
451 fNet.SetLossFunction(ELossFunction::kSoftmaxCrossEntropy);
453 fOutputFunction = EOutputFunction::kSoftmax;
460 if (fWeightInitializationString ==
"XAVIER") {
463 else if (fWeightInitializationString ==
"XAVIERUNIFORM") {
474 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
477 for (
auto& block : strategyKeyValues) {
487 std::vector<Double_t>());
491 if (regularization ==
"L1") {
493 }
else if (regularization ==
"L2") {
497 TString strMultithreading =
fetchValue(block,
"Multithreading",
499 if (strMultithreading.BeginsWith (
"T")) {
505 fTrainingSettings.push_back(settings);
512 if (fInteractive && fInteractive->NotInitialized()){
513 std::vector<TString> titles = {
"Error on training set",
"Error on test set"};
514 fInteractive->Init(titles);
519 if (fArchitectureString ==
"GPU") {
521 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
524 }
else if (fArchitectureString ==
"OpenCL") {
525 Log() <<
kFATAL <<
"OpenCL backend not yes supported." <<
Endl;
527 }
else if (fArchitectureString ==
"CPU") {
529 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
534 Log() <<
kINFO <<
"Using Standard Implementation.";
536 std::vector<Pattern> trainPattern;
537 std::vector<Pattern> testPattern;
539 const std::vector<TMVA::Event*>& eventCollectionTraining = GetEventCollection (
Types::kTraining);
540 const std::vector<TMVA::Event*>& eventCollectionTesting = GetEventCollection (
Types::kTesting);
542 for (
auto &event : eventCollectionTraining) {
543 const std::vector<Float_t>& values =
event->GetValues();
545 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
546 trainPattern.push_back(
Pattern (values.begin(),
549 event->GetWeight()));
550 trainPattern.back().addInput(1.0);
552 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
553 oneHot[
event->GetClass()] = 1.0;
554 trainPattern.push_back(
Pattern (values.begin(), values.end(),
555 oneHot.cbegin(), oneHot.cend(),
556 event->GetWeight()));
557 trainPattern.back().addInput(1.0);
559 const std::vector<Float_t>& targets =
event->GetTargets ();
560 trainPattern.push_back(
Pattern(values.begin(),
564 event->GetWeight ()));
565 trainPattern.back ().addInput (1.0);
569 for (
auto &event : eventCollectionTesting) {
570 const std::vector<Float_t>& values =
event->GetValues();
572 double outputValue =
event->GetClass () == 0 ? 0.9 : 0.1;
573 testPattern.push_back(
Pattern (values.begin(),
576 event->GetWeight()));
577 testPattern.back().addInput(1.0);
579 std::vector<Float_t> oneHot(DataInfo().GetNClasses(), 0.0);
580 oneHot[
event->GetClass()] = 1.0;
581 testPattern.push_back(
Pattern (values.begin(), values.end(),
582 oneHot.cbegin(), oneHot.cend(),
583 event->GetWeight()));
584 testPattern.back().addInput(1.0);
586 const std::vector<Float_t>& targets =
event->GetTargets ();
587 testPattern.push_back(
Pattern(values.begin(),
591 event->GetWeight ()));
592 testPattern.back ().addInput (1.0);
597 std::vector<double> weights;
604 for (
size_t i = 0; i < fNet.GetDepth(); i++) {
605 EActivationFunction
f = fNet.GetLayer(i).GetActivationFunction();
608 case EActivationFunction::kIdentity: g = EnumFunction::LINEAR;
break;
609 case EActivationFunction::kRelu: g = EnumFunction::RELU;
break;
610 case EActivationFunction::kSigmoid: g = EnumFunction::SIGMOID;
break;
611 case EActivationFunction::kTanh: g = EnumFunction::TANH;
break;
612 case EActivationFunction::kSymmRelu: g = EnumFunction::SYMMRELU;
break;
613 case EActivationFunction::kSoftSign: g = EnumFunction::SOFTSIGN;
break;
614 case EActivationFunction::kGauss: g = EnumFunction::GAUSS;
break;
616 if (i < fNet.GetDepth() - 1) {
620 switch(fOutputFunction) {
621 case EOutputFunction::kIdentity: h = ModeOutputValues::DIRECT;
break;
622 case EOutputFunction::kSigmoid: h = ModeOutputValues::SIGMOID;
break;
623 case EOutputFunction::kSoftmax: h = ModeOutputValues::SOFTMAX;
break;
629 switch(fNet.GetLossFunction()) {
630 case ELossFunction::kMeanSquaredError:
636 case ELossFunction::kSoftmaxCrossEntropy:
641 switch(fWeightInitialization) {
642 case EInitialization::kGauss:
644 std::back_inserter(weights));
646 case EInitialization::kUniform:
648 std::back_inserter(weights));
652 std::back_inserter(weights));
657 for (
auto s : fTrainingSettings) {
660 switch(s.regularization) {
662 case ERegularization::kL1: r = EnumRegularization::L1;
break;
663 case ERegularization::kL2: r = EnumRegularization::L2;
break;
666 Settings * settings =
new Settings(TString(), s.convergenceSteps, s.batchSize,
667 s.testInterval, s.weightDecay, r,
669 s.momentum, 1, s.multithreading);
670 std::shared_ptr<Settings> ptrSettings(settings);
671 ptrSettings->setMonitoring (0);
673 <<
"Training with learning rate = " << ptrSettings->learningRate ()
674 <<
", momentum = " << ptrSettings->momentum ()
675 <<
", repetitions = " << ptrSettings->repetitions ()
678 ptrSettings->setProgressLimits ((idxSetting)*100.0/(fSettings.size ()),
679 (idxSetting+1)*100.0/(fSettings.size ()));
681 const std::vector<double>& dropConfig = ptrSettings->dropFractions ();
682 if (!dropConfig.empty ()) {
684 <<
" drop repetitions = " << ptrSettings->dropRepetitions()
689 for (
auto f : dropConfig) {
696 ptrSettings->momentum(),
697 ptrSettings->repetitions());
698 net.
train(weights, trainPattern, testPattern, minimizer, *ptrSettings.get());
703 size_t weightIndex = 0;
704 for (
size_t l = 0;
l < fNet.GetDepth();
l++) {
705 auto & layerWeights = fNet.GetLayer(
l).GetWeights();
706 for (
Int_t j = 0; j < layerWeights.GetNcols(); j++) {
707 for (
Int_t i = 0; i < layerWeights.GetNrows(); i++) {
708 layerWeights(i,j) = weights[weightIndex];
712 auto & layerBiases = fNet.GetLayer(
l).GetBiases();
714 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
715 layerBiases(i,0) = weights[weightIndex];
719 for (
Int_t i = 0; i < layerBiases.GetNrows(); i++) {
720 layerBiases(i,0) = 0.0;
724 if (!fExitFromTraining) fIPyMaxIter = fIPyCurrentIter;
732 #ifdef DNNCUDA // Included only if DNNCUDA flag is set.
737 Log() <<
kINFO <<
"Start of neural network training on GPU." <<
Endl;
739 size_t trainingPhase = 1;
740 fNet.Initialize(fWeightInitialization);
744 fInteractive->ClearGraphs();
753 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
754 for (
auto & p : dropoutVector) {
760 auto testNet = net.
CreateClone(settings.batchSize);
762 Log() <<
kINFO <<
"Training phase " << trainingPhase <<
" of "
763 << fTrainingSettings.size() <<
":" <<
Endl;
776 testNet.GetBatchSize(),
780 settings.convergenceSteps,
781 settings.testInterval);
783 std::vector<TNet<TCuda<>>> nets{};
784 std::vector<TBatch<TCuda<>>> batches{};
785 nets.reserve(nThreads);
786 for (
size_t i = 0; i < nThreads; i++) {
788 for (
size_t j = 0; j < net.
GetDepth(); j++)
790 auto &masterLayer = net.
GetLayer(j);
791 auto &layer = nets.back().GetLayer(j);
793 masterLayer.GetWeights());
795 masterLayer.GetBiases());
799 bool converged =
false;
800 size_t stepCount = 0;
801 size_t batchesInEpoch = nTrainingSamples / net.
GetBatchSize();
803 std::chrono::time_point<std::chrono::system_clock> start, end;
804 start = std::chrono::system_clock::now();
807 Log() << std::setw(10) <<
"Epoch" <<
" | "
808 << std::setw(12) <<
"Train Err."
809 << std::setw(12) <<
"Test Err."
810 << std::setw(12) <<
"GFLOP/s"
811 << std::setw(12) <<
"Conv. Steps" <<
Endl;
821 trainingData.Shuffle();
822 for (
size_t i = 0; i < batchesInEpoch; i += nThreads) {
824 for (
size_t j = 0; j < nThreads; j++) {
825 batches.reserve(nThreads);
826 batches.push_back(trainingData.GetBatch());
828 if (settings.momentum > 0.0) {
829 minimizer.StepMomentum(net, nets, batches, settings.momentum);
831 minimizer.Step(net, nets, batches);
835 if ((stepCount % minimizer.GetTestInterval()) == 0) {
839 for (
auto batch : testData) {
840 auto inputMatrix = batch.GetInput();
841 auto outputMatrix = batch.GetOutput();
842 testError += testNet.Loss(inputMatrix, outputMatrix);
844 testError /= (
Double_t) (nTestSamples / settings.batchSize);
846 end = std::chrono::system_clock::now();
850 for (
auto batch : trainingData) {
851 auto inputMatrix = batch.GetInput();
852 auto outputMatrix = batch.GetOutput();
853 trainingError += net.
Loss(inputMatrix, outputMatrix);
855 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
858 std::chrono::duration<double> elapsed_seconds = end - start;
859 double seconds = elapsed_seconds.count();
860 double nFlops = (double) (settings.testInterval * batchesInEpoch);
863 converged = minimizer.HasConverged(testError);
864 start = std::chrono::system_clock::now();
867 fInteractive->AddPoint(stepCount, trainingError, testError);
868 fIPyCurrentIter = 100.0 * minimizer.GetConvergenceCount()
869 / minimizer.GetConvergenceSteps ();
870 if (fExitFromTraining)
break;
872 Log() << std::setw(10) << stepCount <<
" | "
873 << std::setw(12) << trainingError
874 << std::setw(12) << testError
875 << std::setw(12) << nFlops / seconds
876 << std::setw(12) << minimizer.GetConvergenceCount() <<
Endl;
889 #else // DNNCUDA flag not set.
891 Log() <<
kFATAL <<
"CUDA backend not enabled. Please make sure "
892 "you have CUDA installed and it was successfully "
893 "detected by CMAKE." <<
Endl;
901 #ifdef DNNCPU // Included only if DNNCPU flag is set.
906 Log() <<
kINFO <<
"Start of neural network training on CPU." <<
Endl <<
Endl;
908 fNet.Initialize(fWeightInitialization);
910 size_t trainingPhase = 1;
914 fInteractive->ClearGraphs();
917 Log() <<
"Training phase " << trainingPhase <<
" of "
918 << fTrainingSettings.size() <<
":" <<
Endl;
926 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
927 for (
auto & p : dropoutVector) {
933 auto testNet = net.
CreateClone(settings.batchSize);
945 testNet.GetBatchSize(),
949 settings.convergenceSteps,
950 settings.testInterval);
952 std::vector<TNet<TCpu<>>> nets{};
953 std::vector<TBatch<TCpu<>>> batches{};
954 nets.reserve(nThreads);
955 for (
size_t i = 0; i < nThreads; i++) {
957 for (
size_t j = 0; j < net.
GetDepth(); j++)
959 auto &masterLayer = net.
GetLayer(j);
960 auto &layer = nets.back().GetLayer(j);
962 masterLayer.GetWeights());
964 masterLayer.GetBiases());
968 bool converged =
false;
969 size_t stepCount = 0;
970 size_t batchesInEpoch = nTrainingSamples / net.
GetBatchSize();
972 std::chrono::time_point<std::chrono::system_clock> start, end;
973 start = std::chrono::system_clock::now();
976 Log() << std::setw(10) <<
"Epoch" <<
" | "
977 << std::setw(12) <<
"Train Err."
978 << std::setw(12) <<
"Test Err."
979 << std::setw(12) <<
"GFLOP/s"
980 << std::setw(12) <<
"Conv. Steps" <<
Endl;
989 trainingData.Shuffle();
990 for (
size_t i = 0; i < batchesInEpoch; i += nThreads) {
992 for (
size_t j = 0; j < nThreads; j++) {
993 batches.reserve(nThreads);
994 batches.push_back(trainingData.GetBatch());
996 if (settings.momentum > 0.0) {
997 minimizer.StepMomentum(net, nets, batches, settings.momentum);
999 minimizer.Step(net, nets, batches);
1003 if ((stepCount % minimizer.GetTestInterval()) == 0) {
1007 for (
auto batch : testData) {
1008 auto inputMatrix = batch.GetInput();
1009 auto outputMatrix = batch.GetOutput();
1010 testError += testNet.Loss(inputMatrix, outputMatrix);
1012 testError /= (
Double_t) (nTestSamples / settings.batchSize);
1014 end = std::chrono::system_clock::now();
1018 for (
auto batch : trainingData) {
1019 auto inputMatrix = batch.GetInput();
1020 auto outputMatrix = batch.GetOutput();
1021 trainingError += net.
Loss(inputMatrix, outputMatrix);
1023 trainingError /= (
Double_t) (nTrainingSamples / settings.batchSize);
1026 fInteractive->AddPoint(stepCount, trainingError, testError);
1027 fIPyCurrentIter = 100*(double)minimizer.GetConvergenceCount() /(double)settings.convergenceSteps;
1028 if (fExitFromTraining)
break;
1032 std::chrono::duration<double> elapsed_seconds = end - start;
1033 double seconds = elapsed_seconds.count();
1034 double nFlops = (double) (settings.testInterval * batchesInEpoch);
1037 converged = minimizer.HasConverged(testError);
1038 start = std::chrono::system_clock::now();
1041 fInteractive->AddPoint(stepCount, trainingError, testError);
1042 fIPyCurrentIter = 100.0 * minimizer.GetConvergenceCount()
1043 / minimizer.GetConvergenceSteps ();
1044 if (fExitFromTraining)
break;
1046 Log() << std::setw(10) << stepCount <<
" | "
1047 << std::setw(12) << trainingError
1048 << std::setw(12) << testError
1049 << std::setw(12) << nFlops / seconds
1050 << std::setw(12) << minimizer.GetConvergenceCount() <<
Endl;
1060 auto & layer = fNet.GetLayer(
l);
1066 #else // DNNCPU flag not set.
1067 Log() <<
kFATAL <<
"Multi-core CPU backend not enabled. Please make sure "
1068 "you have a BLAS implementation and it was successfully "
1069 "detected by CMake as well that the imt CMake flag is set." <<
Endl;
1076 size_t nVariables = GetEvent()->GetNVariables();
1080 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1081 for (
size_t i = 0; i < nVariables; i++) {
1082 X(0,i) = inputValues[i];
1085 fNet.Prediction(YHat, X, fOutputFunction);
1092 size_t nVariables = GetEvent()->GetNVariables();
1095 const Event *ev = GetEvent();
1096 const std::vector<Float_t>& inputValues = ev->
GetValues();
1097 for (
size_t i = 0; i < nVariables; i++) {
1098 X(0,i) = inputValues[i];
1101 size_t nTargets = std::max(1u, ev->
GetNTargets());
1103 std::vector<Float_t>
output(nTargets);
1104 auto net = fNet.CreateClone(1);
1105 net.Prediction(YHat, X, fOutputFunction);
1107 for (
size_t i = 0; i < nTargets; i++)
1108 output[i] = YHat(0, i);
1110 if (fRegressionReturnVal ==
NULL) {
1111 fRegressionReturnVal =
new std::vector<Float_t>();
1113 fRegressionReturnVal->clear();
1116 for (
size_t i = 0; i < nTargets; ++i) {
1120 const Event* evT2 = GetTransformationHandler().InverseTransform(evT);
1121 for (
size_t i = 0; i < nTargets; ++i) {
1122 fRegressionReturnVal->push_back(evT2->
GetTarget(i));
1125 return *fRegressionReturnVal;
1130 size_t nVariables = GetEvent()->GetNVariables();
1132 Matrix_t YHat(1, DataInfo().GetNClasses());
1133 if (fMulticlassReturnVal ==
NULL) {
1134 fMulticlassReturnVal =
new std::vector<Float_t>(DataInfo().GetNClasses());
1137 const std::vector<Float_t>& inputValues = GetEvent()->GetValues();
1138 for (
size_t i = 0; i < nVariables; i++) {
1139 X(0,i) = inputValues[i];
1142 fNet.Prediction(YHat, X, fOutputFunction);
1143 for (
size_t i = 0; i < (size_t) YHat.GetNcols(); i++) {
1144 (*fMulticlassReturnVal)[i] = YHat(0, i);
1146 return *fMulticlassReturnVal;
1153 Int_t inputWidth = fNet.GetInputWidth();
1154 Int_t depth = fNet.GetDepth();
1155 char lossFunction =
static_cast<char>(fNet.GetLossFunction());
1157 gTools().StringFromInt(inputWidth));
1161 TString(static_cast<char>(fOutputFunction)));
1163 for (
Int_t i = 0; i < depth; i++) {
1164 const auto& layer = fNet.GetLayer(i);
1166 int activationFunction =
static_cast<int>(layer.GetActivationFunction());
1169 WriteMatrixXML(layerxml,
"Weights", layer.GetWeights());
1170 WriteMatrixXML(layerxml,
"Biases", layer.GetBiases());
1183 fNet.SetBatchSize(1);
1185 size_t inputWidth, depth;
1188 char lossFunctionChar;
1190 char outputFunctionChar;
1193 fNet.SetInputWidth(inputWidth);
1194 fNet.SetLossFunction(static_cast<ELossFunction>(lossFunctionChar));
1195 fOutputFunction =
static_cast<EOutputFunction
>(outputFunctionChar);
1197 size_t previousWidth = inputWidth;
1199 for (
size_t i = 0; i < depth; i++) {
1201 EActivationFunction
f;
1205 f =
static_cast<EActivationFunction
>(fString.Atoi());
1212 fNet.AddLayer(width, f);
1215 ReadMatrixXML(layerXML,
"Weights", weights);
1216 ReadMatrixXML(layerXML,
"Biases", biases);
1217 fNet.GetLayer(i).GetWeights() = weights;
1218 fNet.GetLayer(i).GetBiases() = biases;
1221 previousWidth = width;
1234 for (
UInt_t ivar=0; ivar<GetNvar(); ivar++) {
1235 fRanking->AddRank(
Rank( GetInputLabel(ivar), 1.0));
1242 const TString& )
const
1257 Log() << col <<
"--- Short description:" << colres <<
Endl;
1259 Log() <<
"The DNN neural network is a feedforward" <<
Endl;
1260 Log() <<
"multilayer perceptron impementation. The DNN has a user-" <<
Endl;
1261 Log() <<
"defined hidden layer architecture, where the number of input (output)" <<
Endl;
1262 Log() <<
"nodes is determined by the input variables (output classes, i.e., " <<
Endl;
1263 Log() <<
"signal and one background, regression or multiclass). " <<
Endl;
1265 Log() << col <<
"--- Performance optimisation:" << colres <<
Endl;
1268 const char* txt =
"The DNN supports various options to improve performance in terms of training speed and \n \
1269 reduction of overfitting: \n \
1271 - different training settings can be stacked. Such that the initial training \n\
1272 is done with a large learning rate and a large drop out fraction whilst \n \
1273 in a later stage learning rate and drop out can be reduced. \n \
1276 initial training stage: 0.0 for the first layer, 0.5 for later layers. \n \
1277 later training stage: 0.1 or 0.0 for all layers \n \
1278 final training stage: 0.0] \n \
1279 Drop out is a technique where a at each training cycle a fraction of arbitrary \n \
1280 nodes is disabled. This reduces co-adaptation of weights and thus reduces overfitting. \n \
1281 - L1 and L2 regularization are available \n \
1283 [recommended 10 - 150] \n \
1284 Arbitrary mini-batch sizes can be chosen. \n \
1285 - Multithreading \n \
1286 [recommended: True] \n \
1287 Multithreading can be turned on. The minibatches are distributed to the available \n \
1288 cores. The algorithm is lock-free (\"Hogwild!\"-style) for each cycle. \n \
1292 - example: \"TANH|(N+30)*2,TANH|(N+30),LINEAR\" \n \
1294 . two hidden layers (separated by \",\") \n \
1295 . the activation function is TANH (other options: RELU, SOFTSIGN, LINEAR) \n \
1296 . the activation function for the output layer is LINEAR \n \
1297 . the first hidden layer has (N+30)*2 nodes where N is the number of input neurons \n \
1298 . the second hidden layer has N+30 nodes, where N is the number of input neurons \n \
1299 . the number of nodes in the output layer is determined by the number of output nodes \n \
1300 and can therefore not be chosen freely. \n \
1302 \"ErrorStrategy\": \n \
1304 The error of the neural net is determined by a sum-of-squares error function \n \
1305 For regression, this is the only possible choice. \n \
1307 The error of the neural net is determined by a cross entropy function. The \n \
1308 output values are automatically (internally) transformed into probabilities \n \
1309 using a sigmoid function. \n \
1310 For signal/background classification this is the default choice. \n \
1311 For multiclass using cross entropy more than one or no output classes \n \
1312 can be equally true or false (e.g. Event 0: A and B are true, Event 1: \n \
1313 A and C is true, Event 2: C is true, ...) \n \
1314 - MUTUALEXCLUSIVE \n \
1315 In multiclass settings, exactly one of the output classes can be true (e.g. either A or B or C) \n \
1317 \"WeightInitialization\" \n \
1320 \"Xavier Glorot & Yoshua Bengio\"-style of initializing the weights. The weights are chosen randomly \n \
1321 such that the variance of the values of the nodes is preserved for each layer. \n \
1322 - XAVIERUNIFORM \n \
1323 The same as XAVIER, but with uniformly distributed weights instead of gaussian weights \n \
1325 Random values scaled by the layer size \n \
1327 \"TrainingStrategy\" \n \
1328 - example: \"LearningRate=1e-1,Momentum=0.3,ConvergenceSteps=50,BatchSize=30,TestRepetitions=7,WeightDecay=0.0,Renormalize=L2,DropConfig=0.0,DropRepetitions=5|LearningRate=1e-4,Momentum=0.3,ConvergenceSteps=50,BatchSize=20,TestRepetitions=7,WeightDecay=0.001,Renormalize=L2,DropFraction=0.0,DropRepetitions=5\" \n \
1329 - explanation: two stacked training settings separated by \"|\" \n \
1330 . first training setting: \"LearningRate=1e-1,Momentum=0.3,ConvergenceSteps=50,BatchSize=30,TestRepetitions=7,WeightDecay=0.0,Renormalize=L2,DropConfig=0.0,DropRepetitions=5\" \n \
1331 . second training setting : \"LearningRate=1e-4,Momentum=0.3,ConvergenceSteps=50,BatchSize=20,TestRepetitions=7,WeightDecay=0.001,Renormalize=L2,DropFractions=0.0,DropRepetitions=5\" \n \
1332 . LearningRate : \n \
1333 - recommended for classification: 0.1 initially, 1e-4 later \n \
1334 - recommended for regression: 1e-4 and less \n \
1336 preserve a fraction of the momentum for the next training batch [fraction = 0.0 - 1.0] \n \
1337 . Repetitions : \n \
1338 train \"Repetitions\" repetitions with the same minibatch before switching to the next one \n \
1339 . ConvergenceSteps : \n \
1340 Assume that convergence is reached after \"ConvergenceSteps\" cycles where no improvement \n \
1341 of the error on the test samples has been found. (Mind that only at each \"TestRepetitions\" \n \
1342 cycle the test sampes are evaluated and thus the convergence is checked) \n \
1344 Size of the mini-batches. \n \
1345 . TestRepetitions \n \
1346 Perform testing the neural net on the test samples each \"TestRepetitions\" cycle \n \
1348 If \"Renormalize\" is set to L1 or L2, \"WeightDecay\" provides the renormalization factor \n \
1350 NONE, L1 (|w|) or L2 (w^2) \n \
1352 Drop a fraction of arbitrary nodes of each of the layers according to the values given \n \
1353 in the DropConfig. \n \
1354 [example: DropConfig=0.0+0.5+0.3 \n \
1355 meaning: drop no nodes in layer 0 (input layer), half of the nodes in layer 1 and 30% of the nodes \n \
1357 recommended: leave all the nodes turned on for the input layer (layer 0) \n \
1358 turn off half of the nodes in later layers for the initial training; leave all nodes \n \
1359 turned on (0.0) in later training stages] \n \
1360 . DropRepetitions \n \
1361 Each \"DropRepetitions\" cycle the configuration of which nodes are dropped is changed \n \
1362 [recommended : 1] \n \
1363 . Multithreading \n \
1364 turn on multithreading [recommended: True] \n \
std::string GetName(const std::string &scope_name)
size_t GetOutputWidth() 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).
MsgLogger & Endl(MsgLogger &ml)
Collectable string class.
UInt_t GetNTargets() const
accessor to the number of targets
Steepest Gradient Descent algorithm (SGD)
void SetDropoutProbabilities(const std::vector< Double_t > &probabilities)
void GetHelpMessage() const
void setErrorFunction(ModeErrorFunction eErrorFunction)
which error function is to be used
size_t GetBatchSize() const
typename Architecture_t::Matrix_t Matrix_t
void MakeClassSpecific(std::ostream &, const TString &) const
void setOutputSize(size_t sizeOutput)
set the output size of the DNN
void SetWeightDecay(Scalar_t weightDecay)
std::vector< std::map< TString, TString >> KeyValueVector_t
void ReadWeightsFromStream(std::istream &i)
ERegularization regularization
void SetIpythonInteractive(IPythonInteractive *fI, bool *fE, UInt_t *M, UInt_t *C)
std::vector< Double_t > dropoutProbabilities
void ReadWeightsFromXML(void *wghtnode)
void setInputSize(size_t sizeInput)
set the input size of the DNN
Generic neural network class.
void initializeWeights(WeightInitializationStrategy eInitStrategy, OutIterator itWeight)
initialize the weights with the given strategy
TString GetString() const
const Ranking * CreateRanking()
void SetRegularization(ERegularization R)
size_t GetInputWidth() const
virtual Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets)
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.
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
Settings for the training of the neural net.
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...
Layer defines the layout of a layer.
std::vector< std::pair< int, EActivationFunction >> LayoutVector_t
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
KeyValueVector_t ParseKeyValueString(TString parseString, TString blockDelim, TString tokenDelim)
void Copy(void *source, void *dest)
TString fetchValue(const std::map< TString, TString > &keyValueMap, TString key)
double train(std::vector< double > &weights, std::vector< Pattern > &trainPattern, const std::vector< Pattern > &testPattern, Minimizer &minimizer, Settings &settings)
start the training
EOutputFunction
Enum that represents output functions.
ELossFunction
Enum that represents objective functions for the net, i.e.
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Float_t GetTarget(UInt_t itgt) const
#define REGISTER_METHOD(CLASS)
for example
void addLayer(Layer &layer)
add a layer (layout)
std::vector< Float_t > & GetValues()
virtual Double_t GetMvaValue(Double_t *err=0, Double_t *errUpper=0)
void InitializeGradients()
Initialize the gradients in the net to zero.
XMLNodePointer_t GetChild(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
returns first child of xml node
MethodDNN(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption)
XMLNodePointer_t NewChild(XMLNodePointer_t parent, XMLNsPointer_t ns, const char *name, const char *content=0)
create new child element for parent node
LayoutVector_t ParseLayoutString(TString layerSpec)
EActivationFunction
Enum that represents layer activation functions.
Bool_t WriteOptionsReference() const
virtual const std::vector< Float_t > & GetMulticlassValues()
virtual const std::vector< Float_t > & GetRegressionValues()
void AddWeightsXMLTo(void *parent) const
Scalar_t Loss(const Matrix_t &Y, bool includeRegularization=false) const
Evaluate the loss function of the net using the activations that are currently stored in the output l...
Layer_t & GetLayer(size_t i)
if(line.BeginsWith("/*"))