68#pragma warning(disable : 4996)
70#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
92 std::map<TString, TString>::const_iterator it = keyValueMap.find(key);
93 if (it == keyValueMap.end()) {
156 std::vector<double> defaultValue)
159 if (parseString ==
"") {
164 std::vector<double> values;
168 TIter nextToken(tokenStrings);
170 for (; tokenString != NULL; tokenString = (
TObjString *)nextToken()) {
171 std::stringstream sstr;
174 sstr >> currentValue;
175 values.push_back(currentValue);
181void MethodDL::DeclareOptions()
185 DeclareOptionRef(fInputLayoutString =
"0|0|0",
"InputLayout",
"The Layout of the input");
187 DeclareOptionRef(fBatchLayoutString =
"0|0|0",
"BatchLayout",
"The Layout of the batch");
189 DeclareOptionRef(fLayoutString =
"DENSE|(N+100)*2|SOFTSIGN,DENSE|0|LINEAR",
"Layout",
"Layout of the network.");
191 DeclareOptionRef(fErrorStrategy =
"CROSSENTROPY",
"ErrorStrategy",
"Loss function: Mean squared error (regression)"
192 " or cross entropy (binary classification).");
193 AddPreDefVal(
TString(
"CROSSENTROPY"));
194 AddPreDefVal(
TString(
"SUMOFSQUARES"));
195 AddPreDefVal(
TString(
"MUTUALEXCLUSIVE"));
197 DeclareOptionRef(fWeightInitializationString =
"XAVIER",
"WeightInitialization",
"Weight initialization strategy");
198 AddPreDefVal(
TString(
"XAVIER"));
199 AddPreDefVal(
TString(
"XAVIERUNIFORM"));
200 AddPreDefVal(
TString(
"GAUSS"));
201 AddPreDefVal(
TString(
"UNIFORM"));
202 AddPreDefVal(
TString(
"IDENTITY"));
205 DeclareOptionRef(fRandomSeed = 0,
"RandomSeed",
"Random seed used for weight initialization and batch shuffling");
207 DeclareOptionRef(fNumValidationString =
"20%",
"ValidationSize",
"Part of the training data to use for validation. "
208 "Specify as 0.2 or 20% to use a fifth of the data set as validation set. "
209 "Specify as 100 to use exactly 100 events. (Default: 20%)");
211 DeclareOptionRef(fArchitectureString =
"CPU",
"Architecture",
"Which architecture to perform the training on.");
212 AddPreDefVal(
TString(
"STANDARD"));
215 AddPreDefVal(
TString(
"OPENCL"));
216 AddPreDefVal(
TString(
"CUDNN"));
219 DeclareOptionRef(fTrainingStrategyString =
"LearningRate=1e-3,"
221 "ConvergenceSteps=100,"
227 "Regularization=None,"
229 "TrainingStrategy",
"Defines the training strategies.");
233void MethodDL::ProcessOptions()
236 if (IgnoreEventsWithNegWeightsInTraining()) {
237 Log() << kINFO <<
"Will ignore negative events in training!" <<
Endl;
240 if (fArchitectureString ==
"STANDARD") {
241 Log() << kWARNING <<
"The STANDARD architecture is not supported anymore. "
242 "Please use Architecture=CPU or Architecture=CPU."
243 "See the TMVA Users' Guide for instructions if you "
244 "encounter problems."
246 Log() << kINFO <<
"We will use instead the CPU architecture" <<
Endl;
247 fArchitectureString =
"CPU";
249 if (fArchitectureString ==
"OPENCL") {
250 Log() << kERROR <<
"The OPENCL architecture has not been implemented yet. "
251 "Please use Architecture=CPU or Architecture=CPU for the "
252 "time being. See the TMVA Users' Guide for instructions "
253 "if you encounter problems."
256 Log() << kINFO <<
"We will try using the GPU-CUDA architecture if available" <<
Endl;
257 fArchitectureString =
"GPU";
263 if (fArchitectureString ==
"GPU" || fArchitectureString ==
"CUDNN") {
265 Log() << kINFO <<
"Will now use the GPU architecture !" <<
Endl;
267 Log() << kERROR <<
"CUDA backend not enabled. Please make sure "
268 "you have CUDA installed and it was successfully "
269 "detected by CMAKE by using -Dtmva-gpu=On "
271 fArchitectureString =
"CPU";
272 Log() << kINFO <<
"Will now use instead the CPU architecture !" <<
Endl;
276 if (fArchitectureString ==
"CPU") {
278 Log() << kINFO <<
"Will now use the CPU architecture with BLAS and IMT support !" <<
Endl;
280 Log() << kINFO <<
"Multi-core CPU backend not enabled. For better performance, build ROOT with the "
281 "tmva-cpu option, which requires a BLAS implementation and the imt option."
283 Log() << kINFO <<
"Will use anyway the CPU architecture but with slower performance" <<
Endl;
292 fOutputFunction = EOutputFunction::kSigmoid;
293 if (fAnalysisType == Types::kClassification) {
294 if (fErrorStrategy ==
"SUMOFSQUARES") {
295 fLossFunction = ELossFunction::kMeanSquaredError;
297 if (fErrorStrategy ==
"CROSSENTROPY") {
298 fLossFunction = ELossFunction::kCrossEntropy;
300 fOutputFunction = EOutputFunction::kSigmoid;
301 }
else if (fAnalysisType == Types::kRegression) {
302 if (fErrorStrategy !=
"SUMOFSQUARES") {
303 Log() << kWARNING <<
"For regression only SUMOFSQUARES is a valid "
304 <<
" neural net error function. Setting error function to "
305 <<
" SUMOFSQUARES now." <<
Endl;
308 fLossFunction = ELossFunction::kMeanSquaredError;
309 fOutputFunction = EOutputFunction::kIdentity;
310 }
else if (fAnalysisType == Types::kMulticlass) {
311 if (fErrorStrategy ==
"SUMOFSQUARES") {
312 fLossFunction = ELossFunction::kMeanSquaredError;
314 if (fErrorStrategy ==
"CROSSENTROPY") {
315 fLossFunction = ELossFunction::kCrossEntropy;
317 if (fErrorStrategy ==
"MUTUALEXCLUSIVE") {
318 fLossFunction = ELossFunction::kSoftmaxCrossEntropy;
320 fOutputFunction = EOutputFunction::kSoftmax;
325 if (fWeightInitializationString ==
"XAVIER") {
326 fWeightInitialization = DNN::EInitialization::kGlorotNormal;
327 }
else if (fWeightInitializationString ==
"XAVIERUNIFORM") {
328 fWeightInitialization = DNN::EInitialization::kGlorotUniform;
329 }
else if (fWeightInitializationString ==
"GAUSS") {
330 fWeightInitialization = DNN::EInitialization::kGauss;
331 }
else if (fWeightInitializationString ==
"UNIFORM") {
332 fWeightInitialization = DNN::EInitialization::kUniform;
333 }
else if (fWeightInitializationString ==
"ZERO") {
334 fWeightInitialization = DNN::EInitialization::kZero;
335 }
else if (fWeightInitializationString ==
"IDENTITY") {
336 fWeightInitialization = DNN::EInitialization::kIdentity;
338 fWeightInitialization = DNN::EInitialization::kGlorotUniform;
343 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString,
TString(
"|"),
TString(
","));
344 for (
auto &block : strategyKeyValues) {
367 if (optimizer ==
"SGD") {
368 settings.
optimizer = DNN::EOptimizer::kSGD;
369 }
else if (optimizer ==
"ADAM") {
370 settings.
optimizer = DNN::EOptimizer::kAdam;
371 }
else if (optimizer ==
"ADAGRAD") {
372 settings.
optimizer = DNN::EOptimizer::kAdagrad;
373 }
else if (optimizer ==
"RMSPROP") {
374 settings.
optimizer = DNN::EOptimizer::kRMSProp;
375 }
else if (optimizer ==
"ADADELTA") {
376 settings.
optimizer = DNN::EOptimizer::kAdadelta;
380 settings.
optimizer = DNN::EOptimizer::kAdam;
384 std::vector<TString> optimParamLabels = {
"_beta1",
"_beta2",
"_eps",
"_rho"};
386 std::map<TString, double> defaultValues = {
387 {
"ADADELTA_eps", 1.E-8}, {
"ADADELTA_rho", 0.95},
388 {
"ADAGRAD_eps", 1.E-8},
389 {
"ADAM_beta1", 0.9}, {
"ADAM_beta2", 0.999}, {
"ADAM_eps", 1.E-7},
390 {
"RMSPROP_eps", 1.E-7}, {
"RMSPROP_rho", 0.9},
392 for (
auto &pN : optimParamLabels) {
395 if (defaultValues.count(optimParamName) > 0) {
396 double defValue = defaultValues[optimParamName];
403 fTrainingSettings.push_back(settings);
407 this->SetBatchSize(fTrainingSettings.front().batchSize);
415 if (fInputShape[3] == 0 && fInputShape[2] == 0 && fInputShape[1] == 0) {
418 fInputShape[3] = GetNVariables();
426 if (fBatchWidth == 0 && fBatchHeight == 0 && fBatchDepth == 0) {
428 if (fInputShape[2] == 1 && fInputShape[1] == 1) {
431 fBatchHeight = fTrainingSettings.front().batchSize;
432 fBatchWidth = fInputShape[3];
436 fBatchDepth = fTrainingSettings.front().batchSize;
437 fBatchHeight = fInputShape[1];
438 fBatchWidth = fInputShape[3]*fInputShape[2];
448 <<
"MethodDL is deprecated and will be removed in ROOT 6.46. Please train neural networks with a "
449 "dedicated machine learning library instead, and use SOFIE for inference in C++."
455void MethodDL::ParseInputLayout()
461 TString inputLayoutString = this->GetInputLayoutString();
465 TIter nextInputDim(inputDimStrings);
471 std::vector<size_t> inputShape;
472 inputShape.reserve(inputLayoutString.
Length()/2 + 2);
473 inputShape.push_back(0);
474 for (; inputDimString !=
nullptr; inputDimString = (
TObjString *)nextInputDim()) {
479 inputShape.push_back(subDim);
484 if (inputShape.size() == 2) {
486 inputShape = {inputShape[0], 1, 1, inputShape[1]};
488 else if (inputShape.size() == 3) {
490 inputShape = {inputShape[0], inputShape[1], 1, inputShape[2]};
493 this->SetInputShape(inputShape);
498void MethodDL::ParseBatchLayout()
504 TString batchLayoutString = this->GetBatchLayoutString();
506 size_t batchDepth = 0;
507 size_t batchHeight = 0;
508 size_t batchWidth = 0;
512 TIter nextBatchDim(batchDimStrings);
516 for (; batchDimString !=
nullptr; batchDimString = (
TObjString *)nextBatchDim()) {
521 batchDepth = (size_t)strDepth.Atoi();
526 batchHeight = (size_t)strHeight.Atoi();
531 batchWidth = (size_t)strWidth.Atoi();
537 this->SetBatchDepth(batchDepth);
538 this->SetBatchHeight(batchHeight);
539 this->SetBatchWidth(batchWidth);
544template <
typename Architecture_t,
typename Layer_t>
549 const TString layerDelimiter(
",");
550 const TString subDelimiter(
"|");
552 TString layoutString = this->GetLayoutString();
558 TIter nextLayer(layerStrings);
562 for (; layerString !=
nullptr; layerString = (
TObjString *)nextLayer()) {
566 TIter nextToken(subStrings);
573 if (strLayerType ==
"DENSE") {
574 ParseDenseLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
575 }
else if (strLayerType ==
"CONV") {
576 ParseConvLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
577 }
else if (strLayerType ==
"MAXPOOL") {
578 ParseMaxPoolLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
579 }
else if (strLayerType ==
"RESHAPE") {
580 ParseReshapeLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
581 }
else if (strLayerType ==
"BNORM") {
582 ParseBatchNormLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
583 }
else if (strLayerType ==
"RNN") {
584 ParseRecurrentLayer(kLayerRNN, deepNet, nets, layerString->
GetString(), subDelimiter);
585 }
else if (strLayerType ==
"LSTM") {
586 ParseRecurrentLayer(kLayerLSTM, deepNet, nets, layerString->
GetString(), subDelimiter);
587 }
else if (strLayerType ==
"GRU") {
588 ParseRecurrentLayer(kLayerGRU, deepNet, nets, layerString->
GetString(), subDelimiter);
591 ParseDenseLayer(deepNet, nets, layerString->
GetString(), subDelimiter);
598template <
typename Architecture_t,
typename Layer_t>
609 const size_t inputSize = GetNvar();
613 TIter nextToken(subStrings);
619 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
623 if (strActFnc ==
"DENSE")
continue;
625 if (strActFnc ==
"RELU") {
626 activationFunction = DNN::EActivationFunction::kRelu;
627 }
else if (strActFnc ==
"TANH") {
628 activationFunction = DNN::EActivationFunction::kTanh;
629 }
else if (strActFnc ==
"FTANH") {
630 activationFunction = DNN::EActivationFunction::kFastTanh;
631 }
else if (strActFnc ==
"SYMMRELU") {
632 activationFunction = DNN::EActivationFunction::kSymmRelu;
633 }
else if (strActFnc ==
"SOFTSIGN") {
634 activationFunction = DNN::EActivationFunction::kSoftSign;
635 }
else if (strActFnc ==
"SIGMOID") {
636 activationFunction = DNN::EActivationFunction::kSigmoid;
637 }
else if (strActFnc ==
"LINEAR") {
638 activationFunction = DNN::EActivationFunction::kIdentity;
639 }
else if (strActFnc ==
"GAUSS") {
640 activationFunction = DNN::EActivationFunction::kGauss;
641 }
else if (
width == 0) {
645 TString strNumNodes = strActFnc;
651 width = fml.Eval(inputSize);
656 size_t outputSize = 1;
657 if (fAnalysisType == Types::kRegression && GetNTargets() != 0) {
658 outputSize = GetNTargets();
659 }
else if (fAnalysisType == Types::kMulticlass && DataInfo().GetNClasses() >= 2) {
660 outputSize = DataInfo().GetNClasses();
669 if (fBuildNet) fNet->AddDenseLayer(
width, activationFunction);
684template <
typename Architecture_t,
typename Layer_t>
694 int zeroPadHeight = 0;
695 int zeroPadWidth = 0;
700 TIter nextToken(subStrings);
704 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
709 depth = strDepth.Atoi();
714 fltHeight = strFltHeight.Atoi();
719 fltWidth = strFltWidth.Atoi();
724 strideRows = strStrideRows.Atoi();
729 strideCols = strStrideCols.Atoi();
734 zeroPadHeight = strZeroPadHeight.Atoi();
739 zeroPadWidth = strZeroPadWidth.Atoi();
744 if (strActFnc ==
"RELU") {
745 activationFunction = DNN::EActivationFunction::kRelu;
746 }
else if (strActFnc ==
"TANH") {
747 activationFunction = DNN::EActivationFunction::kTanh;
748 }
else if (strActFnc ==
"SYMMRELU") {
749 activationFunction = DNN::EActivationFunction::kSymmRelu;
750 }
else if (strActFnc ==
"SOFTSIGN") {
751 activationFunction = DNN::EActivationFunction::kSoftSign;
752 }
else if (strActFnc ==
"SIGMOID") {
753 activationFunction = DNN::EActivationFunction::kSigmoid;
754 }
else if (strActFnc ==
"LINEAR") {
755 activationFunction = DNN::EActivationFunction::kIdentity;
756 }
else if (strActFnc ==
"GAUSS") {
757 activationFunction = DNN::EActivationFunction::kGauss;
766 zeroPadHeight, zeroPadWidth, activationFunction);
770 if (fBuildNet) fNet->AddConvLayer(depth, fltHeight, fltWidth, strideRows, strideCols,
771 zeroPadHeight, zeroPadWidth, activationFunction);
783template <
typename Architecture_t,
typename Layer_t>
789 int filterHeight = 0;
796 TIter nextToken(subStrings);
800 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
805 filterHeight = strFrmHeight.Atoi();
810 filterWidth = strFrmWidth.Atoi();
815 strideRows = strStrideRows.Atoi();
820 strideCols = strStrideCols.Atoi();
828 deepNet.
AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
831 if (fBuildNet) fNet->AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
844template <
typename Architecture_t,
typename Layer_t>
852 bool flattening =
false;
856 TIter nextToken(subStrings);
860 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
861 if (token->
GetString() ==
"FLAT") idxToken=4;
865 depth = strDepth.Atoi();
870 height = strHeight.Atoi();
875 width = strWidth.Atoi();
880 if (flat ==
"FLAT") {
893 if (fBuildNet) fNet->AddReshapeLayer(depth,
height,
width, flattening);
905template <
typename Architecture_t,
typename Layer_t>
912 double momentum = -1;
913 double epsilon = 0.0001;
917 TIter nextToken(subStrings);
921 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
940 if (fBuildNet) fNet->AddBatchNormLayer(momentum, epsilon);
946template <
typename Architecture_t,
typename Layer_t>
955 bool rememberState =
false;
956 bool returnSequence =
false;
957 bool resetGateAfter =
false;
961 TIter nextToken(subStrings);
965 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
970 stateSize = strstateSize.Atoi();
976 inputSize = strinputSize.Atoi();
982 timeSteps = strtimeSteps.Atoi();
988 rememberState = (
bool) strrememberState.Atoi();
994 returnSequence = (
bool)str.Atoi();
1000 resetGateAfter = (
bool)str.Atoi();
1007 if (rnnType == kLayerRNN) {
1008 auto * recurrentLayer = deepNet.
AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1009 recurrentLayer->Initialize();
1011 if (fBuildNet) fNet->AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1013 else if (rnnType == kLayerLSTM ) {
1014 auto *recurrentLayer = deepNet.
AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1015 recurrentLayer->Initialize();
1018 fNet->AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1020 else if (rnnType == kLayerGRU) {
1021 if (Architecture_t::IsCudnn()) resetGateAfter =
true;
1022 auto *recurrentLayer = deepNet.
AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
1023 recurrentLayer->Initialize();
1026 fNet->AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
1029 Log() << kFATAL <<
"Invalid Recurrent layer type " <<
Endl;
1036 :
MethodBase(jobName,
Types::kDL, methodTitle, theData, theOption), fInputShape(4,0),
1037 fBatchHeight(), fBatchWidth(), fRandomSeed(0), fWeightInitialization(),
1038 fOutputFunction(), fLossFunction(), fInputLayoutString(), fBatchLayoutString(),
1039 fLayoutString(), fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
1040 fArchitectureString(), fResume(false), fBuildNet(true), fTrainingSettings(),
1049 :
MethodBase(
Types::kDL, theData, theWeightFile), fInputShape(4,0), fBatchHeight(),
1050 fBatchWidth(), fRandomSeed(0), fWeightInitialization(), fOutputFunction(),
1051 fLossFunction(), fInputLayoutString(), fBatchLayoutString(), fLayoutString(),
1052 fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
1053 fArchitectureString(), fResume(false), fBuildNet(true), fTrainingSettings(),
1061MethodDL::~MethodDL()
1068auto MethodDL::ParseKeyValueString(
TString parseString,
TString blockDelim,
TString tokenDelim) -> KeyValueVector_t
1071 parseString.ReplaceAll(
" ",
"");
1072 KeyValueVector_t blockKeyValues;
1073 const TString keyValueDelim(
"=");
1075 TObjArray *blockStrings = parseString.Tokenize(blockDelim);
1076 TIter nextBlock(blockStrings);
1079 for (; blockString !=
nullptr; blockString = (
TObjString *)nextBlock()) {
1080 blockKeyValues.push_back(std::map<TString, TString>());
1081 std::map<TString, TString> ¤tBlock = blockKeyValues.back();
1084 TIter nextToken(subStrings);
1087 for (; token !=
nullptr; token = (
TObjString *)nextToken()) {
1089 int delimPos = strKeyValue.First(keyValueDelim.Data());
1090 if (delimPos <= 0)
continue;
1094 TString strValue =
TString(strKeyValue(delimPos + 1, strKeyValue.Length()));
1099 currentBlock.insert(std::make_pair(strKey, strValue));
1102 return blockKeyValues;
1109 if (
type == Types::kClassification && numberClasses == 2)
return kTRUE;
1110 if (
type == Types::kMulticlass)
return kTRUE;
1111 if (
type == Types::kRegression)
return kTRUE;
1124UInt_t TMVA::MethodDL::GetNumValidationSamples()
1126 Int_t nValidationSamples = 0;
1131 if (fNumValidationString.EndsWith(
"%")) {
1136 Double_t valSizeAsDouble = fNumValidationString.Atof() / 100.0;
1137 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
1139 Log() <<
kFATAL <<
"Cannot parse number \"" << fNumValidationString
1140 <<
"\". Expected string like \"20%\" or \"20.0%\"." <<
Endl;
1142 }
else if (fNumValidationString.IsFloat()) {
1143 Double_t valSizeAsDouble = fNumValidationString.Atof();
1145 if (valSizeAsDouble < 1.0) {
1147 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
1150 nValidationSamples = valSizeAsDouble;
1153 Log() <<
kFATAL <<
"Cannot parse number \"" << fNumValidationString <<
"\". Expected string like \"0.2\" or \"100\"."
1159 if (nValidationSamples < 0) {
1160 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is negative." <<
Endl;
1163 if (nValidationSamples == 0) {
1164 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is zero." <<
Endl;
1167 if (nValidationSamples >= (
Int_t)trainingSetSize) {
1168 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString
1169 <<
"\" is larger than or equal in size to training set (size=\"" << trainingSetSize <<
"\")." <<
Endl;
1172 return nValidationSamples;
1179template <
typename Architecture_t>
1180void MethodDL::TrainDeepNet()
1183 using Scalar_t =
typename Architecture_t::Scalar_t;
1188 bool debug =
Log().GetMinType() == kDEBUG;
1192 Architecture_t::SetRandomSeed(fRandomSeed);
1197 size_t nValidationSamples = GetNumValidationSamples();
1198 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
1200 const std::vector<TMVA::Event *> &allData = GetEventCollection(Types::kTraining);
1201 const std::vector<TMVA::Event *> eventCollectionTraining{allData.begin(), allData.begin() + nTrainingSamples};
1202 const std::vector<TMVA::Event *> eventCollectionValidation{allData.begin() + nTrainingSamples, allData.end()};
1204 size_t trainingPhase = 1;
1208 size_t nThreads = 1;
1213 this->SetBatchSize(batchSize);
1215 size_t inputDepth = this->GetInputDepth();
1216 size_t inputHeight = this->GetInputHeight();
1217 size_t inputWidth = this->GetInputWidth();
1218 size_t batchDepth = this->GetBatchDepth();
1219 size_t batchHeight = this->GetBatchHeight();
1220 size_t batchWidth = this->GetBatchWidth();
1233 if (batchDepth != batchSize && batchDepth > 1) {
1234 Error(
"Train",
"Given batch depth of %zu (specified in BatchLayout) should be equal to given batch size %zu",batchDepth,batchSize);
1237 if (batchDepth == 1 && batchSize > 1 && batchSize != batchHeight ) {
1238 Error(
"Train",
"Given batch height of %zu (specified in BatchLayout) should be equal to given batch size %zu",batchHeight,batchSize);
1244 bool badLayout =
false;
1246 if (batchDepth == batchSize)
1247 badLayout = ( inputDepth * inputHeight * inputWidth != batchHeight * batchWidth ) ;
1249 if (batchHeight == batchSize && batchDepth == 1)
1250 badLayout |= ( inputDepth * inputHeight * inputWidth != batchWidth);
1252 Error(
"Train",
"Given input layout %zu x %zu x %zu is not compatible with batch layout %zu x %zu x %zu ",
1253 inputDepth,inputHeight,inputWidth,batchDepth,batchHeight,batchWidth);
1258 if (nTrainingSamples < settings.
batchSize || nValidationSamples < settings.
batchSize) {
1259 Log() << kFATAL <<
"Number of samples in the datasets are train: ("
1260 << nTrainingSamples <<
") test: (" << nValidationSamples
1261 <<
"). One of these is smaller than the batch size of "
1262 << settings.
batchSize <<
". Please increase the batch"
1263 <<
" size to be at least the same size as the smallest"
1264 <<
" of them." <<
Endl;
1267 DeepNet_t deepNet(batchSize, inputDepth, inputHeight, inputWidth, batchDepth, batchHeight, batchWidth, J, I,
R,
weightDecay);
1271 if (trainingPhase == 1) {
1272 fNet = std::unique_ptr<DeepNetImpl_t>(
new DeepNetImpl_t(1, inputDepth, inputHeight, inputWidth, batchDepth,
1280 std::vector<DeepNet_t> nets{};
1281 nets.reserve(nThreads);
1282 for (
size_t i = 0; i < nThreads; i++) {
1284 nets.push_back(deepNet);
1289 CreateDeepNet(deepNet, nets);
1295 for (
auto &
p : dropoutVector) {
1300 if (trainingPhase > 1) {
1302 for (
size_t i = 0; i < deepNet.
GetDepth(); ++i) {
1303 deepNet.
GetLayerAt(i)->CopyParameters(*fNet->GetLayerAt(i));
1314 fXInput = ArchitectureImpl_t::CreateTensor(fNet->GetBatchSize(), GetInputDepth(), GetInputHeight(), GetInputWidth() );
1315 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1)
1316 fXInput = TensorImpl_t( fNet->GetBatchSize(), GetInputWidth() );
1317 fXInputBuffer = HostBufferImpl_t( fXInput.GetSize() );
1321 fYHat = std::unique_ptr<MatrixImpl_t>(
new MatrixImpl_t(fNet->GetBatchSize(), fNet->GetOutputWidth() ) );
1324 Log() <<
"***** Deep Learning Network *****" <<
Endl;
1325 if (
Log().GetMinType() <= kINFO)
1328 Log() <<
"Using " << nTrainingSamples <<
" events for training and " << nValidationSamples <<
" for testing" <<
Endl;
1331 TMVAInput_t trainingTuple = std::tie(eventCollectionTraining, DataInfo());
1332 TensorDataLoader_t trainingData(trainingTuple, nTrainingSamples, batchSize,
1333 {inputDepth, inputHeight, inputWidth},
1337 TMVAInput_t validationTuple = std::tie(eventCollectionValidation, DataInfo());
1338 TensorDataLoader_t validationData(validationTuple, nValidationSamples, batchSize,
1339 {inputDepth, inputHeight, inputWidth},
1347 Bool_t includeRegularization = (
R != DNN::ERegularization::kNone);
1350 Log() <<
"Compute initial loss on the validation data " <<
Endl;
1351 for (
auto batch : validationData) {
1352 auto inputTensor = batch.GetInput();
1353 auto outputMatrix = batch.GetOutput();
1354 auto weights = batch.GetWeights();
1358 minValError += deepNet.
Loss(inputTensor, outputMatrix, weights,
false, includeRegularization);
1363 minValError += regzTerm;
1367 std::unique_ptr<DNN::VOptimizer<Architecture_t, Layer_t, DeepNet_t>> optimizer;
1372 case EOptimizer::kSGD:
1373 optimizer = std::unique_ptr<DNN::TSGD<Architecture_t, Layer_t, DeepNet_t>>(
1377 case EOptimizer::kAdam: {
1378 optimizer = std::unique_ptr<DNN::TAdam<Architecture_t, Layer_t, DeepNet_t>>(
1385 case EOptimizer::kAdagrad:
1386 optimizer = std::unique_ptr<DNN::TAdagrad<Architecture_t, Layer_t, DeepNet_t>>(
1391 case EOptimizer::kRMSProp:
1392 optimizer = std::unique_ptr<DNN::TRMSProp<Architecture_t, Layer_t, DeepNet_t>>(
1398 case EOptimizer::kAdadelta:
1399 optimizer = std::unique_ptr<DNN::TAdadelta<Architecture_t, Layer_t, DeepNet_t>>(
1408 std::vector<TTensorBatch<Architecture_t>> batches{};
1410 bool converged =
false;
1411 size_t convergenceCount = 0;
1412 size_t batchesInEpoch = nTrainingSamples / deepNet.
GetBatchSize();
1415 std::chrono::time_point<std::chrono::system_clock> tstart, tend;
1416 tstart = std::chrono::system_clock::now();
1419 auto optimParametersString = [&]() {
1421 for (
auto & element : settings.optimizerParams) {
1424 double value = element.second;
1425 if (!optimParameters.
IsNull())
1426 optimParameters +=
",";
1428 optimParameters +=
" (";
1431 if (!optimParameters.
IsNull())
1432 optimParameters +=
")";
1433 return optimParameters;
1436 Log() <<
"Training phase " << trainingPhase <<
" of " << this->GetTrainingSettings().size() <<
": "
1438 << optimParametersString()
1440 <<
" minimum error = " << minValError << Endl;
1441 std::string separator(62,
'-');
1443 Log() << std::setw(10) <<
"Epoch"
1444 <<
" | " << std::setw(12) <<
"Train Err." << std::setw(12) <<
"Val. Err." << std::setw(12)
1445 <<
"t(s)/epoch" << std::setw(12) <<
"t(s)/Loss" << std::setw(12) <<
"nEvents/s" << std::setw(12)
1446 <<
"Conv. Steps" <<
Endl;
1451 size_t shuffleSeed = 0;
1452 if (fRandomSeed != 0) shuffleSeed = fRandomSeed + trainingPhase;
1456 if (fBuildNet && debug) {
1457 Log() <<
"Initial Deep Net Weights " <<
Endl;
1458 auto & weights_tensor = deepNet.
GetLayerAt(0)->GetWeights();
1459 for (
size_t l = 0;
l < weights_tensor.size(); ++
l)
1460 weights_tensor[
l].
Print();
1461 auto & bias_tensor = deepNet.
GetLayerAt(0)->GetBiases();
1462 bias_tensor[0].Print();
1465 Log() <<
" Start epoch iteration ..." <<
Endl;
1466 bool debugFirstEpoch =
false;
1467 bool computeLossInTraining =
true;
1468 size_t nTrainEpochs = 0;
1469 while (!converged) {
1471 trainingData.Shuffle(rng);
1477 for (
size_t i = 0; i < batchesInEpoch; ++i ) {
1484 if (debugFirstEpoch) std::cout <<
"\n\n----- batch # " << i <<
"\n\n";
1486 auto my_batch = trainingData.GetTensorBatch();
1488 if (debugFirstEpoch)
1489 std::cout <<
"got batch data - doing forward \n";
1493 Architecture_t::PrintTensor(my_batch.GetInput(),
"input tensor",
true);
1494 typename Architecture_t::Tensor_t tOut(my_batch.GetOutput());
1495 typename Architecture_t::Tensor_t tW(my_batch.GetWeights());
1496 Architecture_t::PrintTensor(tOut,
"label tensor",
true) ;
1497 Architecture_t::PrintTensor(tW,
"weight tensor",
true) ;
1500 deepNet.
Forward(my_batch.GetInput(),
true);
1502 if (computeLossInTraining) {
1503 auto outputMatrix = my_batch.GetOutput();
1504 auto weights = my_batch.GetWeights();
1505 trainingError += deepNet.
Loss(outputMatrix, weights,
false);
1508 if (debugFirstEpoch)
1509 std::cout <<
"- doing backward \n";
1512 size_t nlayers = deepNet.
GetLayers().size();
1513 for (
size_t l = 0;
l < nlayers; ++
l) {
1514 if (deepNet.
GetLayerAt(
l)->GetWeights().size() > 0)
1515 Architecture_t::PrintTensor(deepNet.
GetLayerAt(
l)->GetWeightsAt(0),
1518 Architecture_t::PrintTensor(deepNet.
GetLayerAt(
l)->GetOutput(),
1525 deepNet.
Backward(my_batch.GetInput(), my_batch.GetOutput(), my_batch.GetWeights());
1527 if (debugFirstEpoch)
1528 std::cout <<
"- doing optimizer update \n";
1531 optimizer->IncrementGlobalStep();
1535 std::cout <<
"minmimizer step - momentum " << settings.
momentum <<
" learning rate " << optimizer->GetLearningRate() << std::endl;
1536 for (
size_t l = 0;
l < nlayers; ++
l) {
1537 if (deepNet.
GetLayerAt(
l)->GetWeights().size() > 0) {
1539 Architecture_t::PrintTensor(deepNet.
GetLayerAt(
l)->GetWeightGradientsAt(0),
"weight gradients");
1546 if (debugFirstEpoch) std::cout <<
"\n End batch loop - compute validation loss \n";
1548 debugFirstEpoch =
false;
1551 std::chrono::time_point<std::chrono::system_clock>
t1,t2;
1553 t1 = std::chrono::system_clock::now();
1559 bool inTraining =
false;
1560 for (
auto batch : validationData) {
1561 auto inputTensor = batch.GetInput();
1562 auto outputMatrix = batch.GetOutput();
1563 auto weights = batch.GetWeights();
1565 valError += deepNet.
Loss(inputTensor, outputMatrix, weights, inTraining, includeRegularization);
1570 valError += regTerm;
1573 fTrainHistory.AddValue(
"valError",nTrainEpochs,valError);
1575 t2 = std::chrono::system_clock::now();
1578 if (valError < minValError) {
1579 convergenceCount = 0;
1585 if (valError < minValError ) {
1587 Log() << std::setw(10) << nTrainEpochs
1588 <<
" Minimum Test error found - save the configuration " <<
Endl;
1589 for (
size_t i = 0; i < deepNet.
GetDepth(); ++i) {
1590 fNet->GetLayerAt(i)->CopyParameters(*deepNet.
GetLayerAt(i));
1599 minValError = valError;
1601 else if ( minValError <= 0. )
1602 minValError = valError;
1604 if (!computeLossInTraining) {
1605 trainingError = 0.0;
1607 for (
auto batch : trainingData) {
1608 auto inputTensor = batch.GetInput();
1609 auto outputMatrix = batch.GetOutput();
1610 auto weights = batch.GetWeights();
1611 trainingError += deepNet.
Loss(inputTensor, outputMatrix, weights,
false,
false);
1616 trainingError += regTerm;
1619 fTrainHistory.AddValue(
"trainingError",nTrainEpochs,trainingError);
1622 tend = std::chrono::system_clock::now();
1625 std::chrono::duration<double> elapsed_seconds = tend - tstart;
1626 std::chrono::duration<double> elapsed1 =
t1-tstart;
1629 std::chrono::duration<double> elapsed_testing = tend-
t1;
1631 double seconds = elapsed_seconds.count();
1640 Log() << std::setw(10) << nTrainEpochs <<
" | "
1641 << std::setw(12) << trainingError
1642 << std::setw(12) << valError
1644 << std::setw(12) << elapsed_testing.count()
1645 << std::setw(12) << 1. / eventTime
1646 << std::setw(12) << convergenceCount
1652 tstart = std::chrono::system_clock::now();
1656 if (converged && debug) {
1657 Log() <<
"Final Deep Net Weights for phase " << trainingPhase <<
" epoch " << nTrainEpochs
1659 auto & weights_tensor = deepNet.
GetLayerAt(0)->GetWeights();
1660 auto & bias_tensor = deepNet.
GetLayerAt(0)->GetBiases();
1661 for (
size_t l = 0;
l < weights_tensor.size(); ++
l)
1662 weights_tensor[
l].
Print();
1663 bias_tensor[0].Print();
1673void MethodDL::Train()
1676 if (this->GetArchitectureString() ==
"GPU") {
1677#ifdef R__HAS_TMVAGPU
1678 Log() << kINFO <<
"Start of deep neural network training on GPU." <<
Endl <<
Endl;
1680 TrainDeepNet<DNN::TCudnn<ScalarImpl_t> >();
1682 TrainDeepNet<DNN::TCuda<ScalarImpl_t>>();
1685 Log() << kFATAL <<
"CUDA backend not enabled. Please make sure "
1686 "you have CUDA installed and it was successfully "
1687 "detected by CMAKE."
1691 }
else if (this->GetArchitectureString() ==
"CPU") {
1692#ifdef R__HAS_TMVACPU
1695 Log() << kINFO <<
"Start of deep neural network training on CPU using MT, nthreads = "
1698 Log() << kINFO <<
"Start of deep neural network training on single thread CPU (without ROOT-MT support) " <<
Endl
1701 TrainDeepNet<DNN::TCpu<ScalarImpl_t> >();
1705 Log() << kFATAL << this->GetArchitectureString() <<
1706 " is not a supported architecture for TMVA::MethodDL"
1713void TMVA::MethodDL::FillInputTensor()
1722 if (!fNet || fNet->GetDepth() == 0) {
1723 Log() <<
kFATAL <<
"The network has not been trained and fNet is not built" <<
Endl;
1725 if (fNet->GetBatchSize() != 1) {
1726 Log() <<
kFATAL <<
"FillINputTensor::Network batch size must be equal to 1 when doing single event predicition" <<
Endl;
1730 const std::vector<Float_t> &inputValues = GetEvent()->GetValues();
1731 size_t nVariables = GetEvent()->GetNVariables();
1735 R__ASSERT(fXInput.GetShape().size() < 4);
1737 if (fXInput.GetShape().size() == 2) {
1738 nc = fXInput.GetShape()[0];
1740 ArchitectureImpl_t::PrintTensor(fXInput);
1741 Log() <<
kFATAL <<
"First tensor dimension should be equal to batch size, i.e. = 1" <<
Endl;
1743 nhw = fXInput.GetShape()[1];
1745 nc = fXInput.GetCSize();
1746 nhw = fXInput.GetWSize();
1748 if (nVariables != nc * nhw) {
1749 Log() <<
kFATAL <<
"Input Event variable dimensions are not compatible with the built network architecture"
1750 <<
" n-event variables " << nVariables <<
" expected input tensor " << nc <<
" x " << nhw <<
Endl;
1752 for (
size_t j = 0; j < nc; j++) {
1753 for (
size_t k = 0; k < nhw; k++) {
1755 fXInputBuffer[k * nc + j] = inputValues[j * nhw + k];
1760 assert(fXInput.GetShape().size() >= 4);
1761 size_t nc = fXInput.GetCSize();
1762 size_t nh = fXInput.GetHSize();
1763 size_t nw = fXInput.GetWSize();
1764 size_t n = nc * nh * nw;
1765 if (nVariables !=
n) {
1766 Log() <<
kFATAL <<
"Input Event variable dimensions are not compatible with the built network architecture"
1767 <<
" n-event variables " << nVariables <<
" expected input tensor " << nc <<
" x " << nh <<
" x " << nw
1770 for (
size_t j = 0; j <
n; j++) {
1772 fXInputBuffer[j] = inputValues[j];
1776 fXInput.GetDeviceBuffer().CopyFrom(fXInputBuffer);
1787 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
1790 double mvaValue = (*fYHat)(0, 0);
1793#ifdef DEBUG_MVAVALUE
1794 using Tensor_t = std::vector<MatrixImpl_t>;
1795 TMatrixF xInput(n1,n2, inputValues.data() );
1796 std::cout <<
"Input data - class " << GetEvent()->GetClass() << std::endl;
1798 std::cout <<
"Output of DeepNet " << mvaValue << std::endl;
1799 auto & deepnet = *fNet;
1800 std::cout <<
"Loop on layers " << std::endl;
1801 for (
int l = 0;
l < deepnet.GetDepth(); ++
l) {
1802 std::cout <<
"Layer " <<
l;
1803 const auto * layer = deepnet.GetLayerAt(
l);
1804 const Tensor_t & layer_output = layer->GetOutput();
1806 std::cout <<
"DNN output " << layer_output.size() << std::endl;
1807 for (
size_t i = 0; i < layer_output.size(); ++i) {
1808#ifdef R__HAS_TMVAGPU
1812 TMatrixD m(layer_output[i].GetNrows(), layer_output[i].GetNcols() , layer_output[i].GetRawDataPointer() );
1816 const Tensor_t & layer_weights = layer->GetWeights();
1817 std::cout <<
"DNN weights " << layer_weights.size() << std::endl;
1818 if (layer_weights.size() > 0) {
1820#ifdef R__HAS_TMVAGPU
1824 TMatrixD m(layer_weights[i].GetNrows(), layer_weights[i].GetNcols() , layer_weights[i].GetRawDataPointer() );
1836template <
typename Architecture_t>
1837std::vector<Double_t> MethodDL::PredictDeepNet(
Long64_t firstEvt,
Long64_t lastEvt,
size_t batchSize,
Bool_t logProgress)
1841 if (!fNet || fNet->GetDepth() == 0) {
1842 Log() << kFATAL <<
"The network has not been trained and fNet is not built"
1847 this->SetBatchSize(batchSize);
1848 size_t inputDepth = this->GetInputDepth();
1849 size_t inputHeight = this->GetInputHeight();
1850 size_t inputWidth = this->GetInputWidth();
1851 size_t batchDepth = this->GetBatchDepth();
1852 size_t batchHeight = this->GetBatchHeight();
1853 size_t batchWidth = this->GetBatchWidth();
1860 using Matrix_t =
typename Architecture_t::Matrix_t;
1864 DeepNet_t deepNet(batchSize, inputDepth, inputHeight, inputWidth, batchDepth, batchHeight, batchWidth, J, I,
R,
weightDecay);
1865 std::vector<DeepNet_t> nets{};
1867 CreateDeepNet(deepNet,nets);
1870 for (
size_t i = 0; i < deepNet.
GetDepth(); ++i) {
1871 deepNet.
GetLayerAt(i)->CopyParameters(*fNet->GetLayerAt(i));
1882 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1) {
1887 Long64_t nEvents = lastEvt - firstEvt;
1888 TMVAInput_t testTuple = std::tie(GetEventCollection(Data()->GetCurrentType()), DataInfo());
1889 TensorDataLoader_t testData(testTuple, nEvents, batchSize, {inputDepth, inputHeight, inputWidth}, {n0, n1, n2}, deepNet.
GetOutputWidth(), 1);
1905 << (Data()->GetCurrentType() == Types::kTraining ?
"training" :
"testing")
1906 <<
" sample (" << nEvents <<
" events)" << Endl;
1910 std::vector<double> mvaValues(nEvents);
1913 for (
Long64_t ievt = firstEvt; ievt < lastEvt; ievt+=batchSize) {
1915 Long64_t ievt_end = ievt + batchSize;
1917 if (ievt_end <= lastEvt) {
1919 if (ievt == firstEvt) {
1920 Data()->SetCurrentEvent(ievt);
1921 size_t nVariables = GetEvent()->GetNVariables();
1923 if (n1 == batchSize && n0 == 1) {
1924 if (n2 != nVariables) {
1925 Log() << kFATAL <<
"Input Event variable dimensions are not compatible with the built network architecture"
1926 <<
" n-event variables " << nVariables <<
" expected input matrix " << n1 <<
" x " << n2
1930 if (n1*n2 != nVariables || n0 != batchSize) {
1931 Log() << kFATAL <<
"Input Event variable dimensions are not compatible with the built network architecture"
1932 <<
" n-event variables " << nVariables <<
" expected input tensor " << n0 <<
" x " << n1 <<
" x " << n2
1938 auto batch = testData.GetTensorBatch();
1939 auto inputTensor = batch.GetInput();
1941 auto xInput = batch.GetInput();
1943 deepNet.
Prediction(yHat, xInput, fOutputFunction);
1944 for (
size_t i = 0; i < batchSize; ++i) {
1945 double value = yHat(i,0);
1951 for (
Long64_t i = ievt; i < lastEvt; ++i) {
1952 Data()->SetCurrentEvent(i);
1953 mvaValues[i] = GetMvaValue();
1960 <<
"Elapsed time for evaluation of " << nEvents <<
" events: "
1961 << timer.GetElapsedTime() <<
" " <<
Endl;
1970const std::vector<Float_t> & TMVA::MethodDL::GetRegressionValues()
1976 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
1978 size_t nTargets = DataInfo().GetNTargets();
1979 R__ASSERT(nTargets == fYHat->GetNcols());
1981 std::vector<Float_t> output(nTargets);
1982 for (
size_t i = 0; i < nTargets; i++)
1983 output[i] = (*fYHat)(0, i);
1986 if (fRegressionReturnVal == NULL)
1987 fRegressionReturnVal =
new std::vector<Float_t>(nTargets);
1988 R__ASSERT(fRegressionReturnVal->size() == nTargets);
1992 for (
size_t i = 0; i < nTargets; ++i) {
1995 const Event *evT2 = GetTransformationHandler().InverseTransform(evT);
1996 for (
size_t i = 0; i < nTargets; ++i) {
1997 (*fRegressionReturnVal)[i] = evT2->
GetTarget(i);
2000 return *fRegressionReturnVal;
2005const std::vector<Float_t> &TMVA::MethodDL::GetMulticlassValues()
2010 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
2012 size_t nClasses = DataInfo().GetNClasses();
2013 R__ASSERT(nClasses == fYHat->GetNcols());
2015 if (fMulticlassReturnVal == NULL) {
2016 fMulticlassReturnVal =
new std::vector<Float_t>(nClasses);
2018 R__ASSERT(fMulticlassReturnVal->size() == nClasses);
2020 for (
size_t i = 0; i < nClasses; i++) {
2021 (*fMulticlassReturnVal)[i] = (*fYHat)(0, i);
2023 return *fMulticlassReturnVal;
2034 Long64_t nEvents = Data()->GetNEvents();
2035 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
2036 if (firstEvt < 0) firstEvt = 0;
2037 nEvents = lastEvt-firstEvt;
2040 size_t defaultEvalBatchSize = (fXInput.GetSize() > 1000) ? 100 : 1000;
2041 size_t batchSize = (fTrainingSettings.empty()) ? defaultEvalBatchSize : fTrainingSettings.front().batchSize;
2042 if (
size_t(nEvents) < batchSize ) batchSize = nEvents;
2045 if (this->GetArchitectureString() ==
"GPU") {
2046#ifdef R__HAS_TMVAGPU
2047 Log() << kINFO <<
"Evaluate deep neural network on GPU using batches with size = " << batchSize <<
Endl <<
Endl;
2049 return PredictDeepNet<DNN::TCudnn<ScalarImpl_t>>(firstEvt, lastEvt, batchSize, logProgress);
2051 return PredictDeepNet<DNN::TCuda<ScalarImpl_t>>(firstEvt, lastEvt, batchSize, logProgress);
2056 Log() << kINFO <<
"Evaluate deep neural network on CPU using batches with size = " << batchSize <<
Endl <<
Endl;
2057 return PredictDeepNet<DNN::TCpu<ScalarImpl_t> >(firstEvt, lastEvt, batchSize, logProgress);
2060void MethodDL::AddWeightsXMLTo(
void * parent)
const
2064 void* nn = xmlEngine.
NewChild(parent, 0,
"Weights");
2070 Int_t depth = fNet->GetDepth();
2072 Int_t inputDepth = fNet->GetInputDepth();
2073 Int_t inputHeight = fNet->GetInputHeight();
2074 Int_t inputWidth = fNet->GetInputWidth();
2076 Int_t batchSize = fNet->GetBatchSize();
2078 Int_t batchDepth = fNet->GetBatchDepth();
2079 Int_t batchHeight = fNet->GetBatchHeight();
2080 Int_t batchWidth = fNet->GetBatchWidth();
2082 char lossFunction =
static_cast<char>(fNet->GetLossFunction());
2083 char initialization =
static_cast<char>(fNet->GetInitialization());
2084 char regularization =
static_cast<char>(fNet->GetRegularization());
2089 char outputFunction =
static_cast<char>(this->GetOutputFunction());
2104 xmlEngine.NewAttr(nn, 0,
"LossFunction",
TString(lossFunction));
2105 xmlEngine.NewAttr(nn, 0,
"Initialization",
TString(initialization));
2107 xmlEngine.NewAttr(nn, 0,
"OutputFunction",
TString(outputFunction));
2112 for (
Int_t i = 0; i < depth; i++)
2114 fNet->GetLayerAt(i) -> AddWeightsXMLTo(nn);
2121void MethodDL::ReadWeightsFromXML(
void * rootXML)
2132 size_t inputDepth, inputHeight, inputWidth;
2137 size_t batchSize, batchDepth, batchHeight, batchWidth;
2145 char lossFunctionChar;
2147 char initializationChar;
2149 char regularizationChar;
2151 char outputFunctionChar;
2159 this->SetInputDepth(inputDepth);
2160 this->SetInputHeight(inputHeight);
2161 this->SetInputWidth(inputWidth);
2162 this->SetBatchDepth(batchDepth);
2163 this->SetBatchHeight(batchHeight);
2164 this->SetBatchWidth(batchWidth);
2168 fNet = std::unique_ptr<DeepNetImpl_t>(
new DeepNetImpl_t(batchSize, inputDepth, inputHeight, inputWidth, batchDepth,
2169 batchHeight, batchWidth,
2182 for (
size_t i = 0; i < netDepth; i++) {
2187 if (layerName ==
"DenseLayer") {
2199 fNet->AddDenseLayer(
width, func, 0.0);
2203 else if (layerName ==
"ConvLayer") {
2208 size_t fltHeight, fltWidth = 0;
2209 size_t strideRows, strideCols = 0;
2210 size_t padHeight, padWidth = 0;
2224 fNet->AddConvLayer(depth, fltHeight, fltWidth, strideRows, strideCols,
2225 padHeight, padWidth, actFunction);
2230 else if (layerName ==
"MaxPoolLayer") {
2233 size_t filterHeight, filterWidth = 0;
2234 size_t strideRows, strideCols = 0;
2240 fNet->AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
2243 else if (layerName ==
"ReshapeLayer") {
2253 fNet->AddReshapeLayer(depth,
height,
width, flattening);
2257 else if (layerName ==
"RNNLayer") {
2260 size_t stateSize,inputSize, timeSteps = 0;
2261 int rememberState= 0;
2262 int returnSequence = 0;
2269 fNet->AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
2273 else if (layerName ==
"LSTMLayer") {
2276 size_t stateSize,inputSize, timeSteps = 0;
2277 int rememberState, returnSequence = 0;
2284 fNet->AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
2288 else if (layerName ==
"GRULayer") {
2291 size_t stateSize,inputSize, timeSteps = 0;
2292 int rememberState, returnSequence, resetGateAfter = 0;
2300 if (!resetGateAfter && ArchitectureImpl_t::IsCudnn())
2302 "Cannot use a reset gate after to false with CudNN - use implementation with resetgate=true");
2304 fNet->AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
2307 else if (layerName ==
"BatchNormLayer") {
2309 fNet->AddBatchNormLayer(0., 0.0);
2312 fNet->GetLayers().back()->ReadWeightsFromXML(layerXML);
2325 fXInput = ArchitectureImpl_t::CreateTensor(fNet->GetBatchSize(), GetInputDepth(), GetInputHeight(), GetInputWidth() );
2326 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1)
2329 fXInputBuffer = HostBufferImpl_t( fXInput.GetSize());
2332 fYHat = std::unique_ptr<MatrixImpl_t>(
new MatrixImpl_t(fNet->GetBatchSize(), fNet->GetOutputWidth() ) );
2339void MethodDL::ReadWeightsFromStream(std::istream & )
2344const Ranking *TMVA::MethodDL::CreateRanking()
2351void MethodDL::GetHelpMessage()
const
#define REGISTER_METHOD(CLASS)
for example
double Double_t
Double 8 bytes.
long long Long64_t
Portable signed long integer 8 bytes.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
winID h TVirtualViewer3D TVirtualGLPainter p
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
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
void Print(Option_t *option="") const override
Dump this line with its attributes.
Adadelta Optimizer class.
Generic Deep Neural Network class.
size_t GetBatchHeight() const
void Forward(Tensor_t &input, bool applyDropout=false)
Function that executes the entire forward pass in the network.
std::vector< Layer_t * > & GetLayers()
size_t GetBatchSize() const
Getters.
TBatchNormLayer< Architecture_t > * AddBatchNormLayer(Scalar_t momentum=-1, Scalar_t epsilon=0.0001)
Function for adding a Batch Normalization layer with given parameters.
void Backward(const Tensor_t &input, const Matrix_t &groundTruth, const Matrix_t &weights)
Function that executes the entire backward pass in the network.
Layer_t * GetLayerAt(size_t i)
Get the layer in the vector of layers at position i.
void Print() const
Print the Deep Net Info.
TBasicGRULayer< Architecture_t > * AddBasicGRULayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false, bool resetGateAfter=false)
Function for adding GRU Layer in the Deep Neural Network, with given parameters.
Scalar_t RegularizationTerm() const
Function for computing the regularizaton term to be added to the loss function
TDenseLayer< Architecture_t > * AddDenseLayer(size_t width, EActivationFunction f, Scalar_t dropoutProbability=1.0)
Function for adding Dense Connected Layer in the Deep Neural Network, with a given width,...
void Prediction(Matrix_t &predictions, EOutputFunction f) const
Prediction based on activations stored in the last layer.
size_t GetBatchWidth() const
TBasicLSTMLayer< Architecture_t > * AddBasicLSTMLayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false)
Function for adding LSTM Layer in the Deep Neural Network, with given parameters.
TMaxPoolLayer< Architecture_t > * AddMaxPoolLayer(size_t frameHeight, size_t frameWidth, size_t strideRows, size_t strideCols, Scalar_t dropoutProbability=1.0)
Function for adding Pooling layer in the Deep Neural Network, with a given filter height and width,...
Scalar_t Loss(const Matrix_t &groundTruth, const Matrix_t &weights, bool includeRegularization=true) const
Function for evaluating the loss, based on the activations stored in the last layer.
TConvLayer< Architecture_t > * AddConvLayer(size_t depth, size_t filterHeight, size_t filterWidth, size_t strideRows, size_t strideCols, size_t paddingHeight, size_t paddingWidth, EActivationFunction f, Scalar_t dropoutProbability=1.0)
Function for adding Convolution layer in the Deep Neural Network, with a given depth,...
size_t GetOutputWidth() const
TReshapeLayer< Architecture_t > * AddReshapeLayer(size_t depth, size_t height, size_t width, bool flattening)
Function for adding Reshape Layer in the Deep Neural Network, with a given height and width.
TBasicRNNLayer< Architecture_t > * AddBasicRNNLayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false, EActivationFunction f=EActivationFunction::kTanh)
Function for adding Recurrent Layer in the Deep Neural Network, with given parameters.
void SetDropoutProbabilities(const std::vector< Double_t > &probabilities)
size_t GetBatchDepth() const
Stochastic Batch Gradient Descent Optimizer class.
Generic General Layer class.
virtual void Initialize()
Initialize the weights and biases according to the given initialization method.
Class that contains all the data information.
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
Float_t GetTarget(UInt_t itgt) const
Virtual base Class for all MVA method.
Ranking for variables in method (implementation)
Timing information for training and evaluation of MVA methods.
Singleton class for Global types used by TMVA.
void Print(Option_t *option="") const override
Dump this marker with its attributes.
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.
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.
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
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
const char * GetNodeName(XMLNodePointer_t xmlnode)
returns name of xmlnode
RVec< PromoteType< T > > abs(const RVec< T > &v)
void Print(std::ostream &os, const OptionType &opt)
EOptimizer
Enum representing the optimizer used for training.
EOutputFunction
Enum that represents output functions.
double weightDecay(double error, ItWeight itWeight, ItWeight itWeightEnd, double factorWeightDecay, EnumRegularization eRegularization)
compute the weight decay for regularization (L1 or L2)
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.
ERegularization
Enum representing the regularization type applied for a given layer.
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
void GetMethodName(TString &name, TKey *mkey)
create variable transformations
TString fetchValueTmp(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)
All of the options that can be specified in the training string.
std::map< TString, double > optimizerParams
DNN::EOptimizer optimizer
DNN::ERegularization regularization
std::vector< Double_t > dropoutProbabilities