Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
NeuralNet.h
Go to the documentation of this file.
1/**
2 * @file TMVA/NeuralNet.h
3 * @author Peter Speckmayer
4 * @version 1.0
5 *
6 * @section LICENSE
7 *
8 *
9 * @section Neural net implementation
10 *
11 * An implementation of a neural net for TMVA. This neural net uses multithreading
12 *
13 */
14
15
16//////////////////////////////////////////////////////////////////////////
17// //
18// NeuralNet //
19// //
20// A neural net implementation //
21// //
22//////////////////////////////////////////////////////////////////////////
23
24#ifndef TMVA_NEURAL_NET
25#define TMVA_NEURAL_NET
26#pragma once
27
28#include <vector>
29#include <iostream>
30#include <algorithm>
31#include <iterator>
32#include <functional>
33#include <tuple>
34#include <cmath>
35#include <cassert>
36#include <random>
37#include <thread>
38#include <future>
39#include <type_traits>
40#include <string>
41#include <utility>
42
43#include "Pattern.h"
44#include "Monitoring.h"
45
46#include "TApplication.h"
47#include "Timer.h"
48
49#include "TH1F.h"
50#include "TH2F.h"
51
52#include <cfenv> // turn on or off exceptions for NaN and other numeric exceptions
53
54
55namespace TMVA
56{
57
58 namespace DNN
59 {
60
61 // double gaussDoubl (edouble mean, double sigma);
62
63
64
65 double gaussDouble (double mean, double sigma);
66 double uniformDouble (double minValue, double maxValue);
67 int randomInt (int maxValue);
68
69
70
71
73 {
74 public:
76 : m_n(0)
77 , m_sumWeights(0)
78 , m_mean(0)
79 , m_squared(0)
80 {}
81
82 inline void clear()
83 {
84 m_n = 0;
85 m_sumWeights = 0;
86 m_mean = 0;
87 m_squared = 0;
88 }
89
90 template <typename T>
91 inline void add(T value, double weight = 1.0)
92 {
93 ++m_n; // a value has been added
94
95 if (m_n == 1) // initialization
96 {
97 m_mean = value;
98 m_squared = 0.0;
99 m_sumWeights = weight;
100 return;
101 }
102
103 double tmpWeight = m_sumWeights+weight;
104 double Q = value - m_mean;
105
106 double R = Q*weight/tmpWeight;
107 m_mean += R;
109
111 }
112
113 template <typename ITERATOR>
115 {
116 for (ITERATOR it = itBegin; it != itEnd; ++it)
117 add (*it);
118 }
119
120
121
122 inline int count() const { return m_n; }
123 inline double weights() const { if(m_n==0) return 0; return m_sumWeights; }
124 inline double mean() const { if(m_n==0) return 0; return m_mean; }
125 inline double var() const
126 {
127 if(m_n==0)
128 return 0;
129 if (m_squared <= 0)
130 return 0;
131 return (m_squared/m_sumWeights);
132 }
133
134 inline double var_corr () const
135 {
136 if (m_n <= 1)
137 return var ();
138
139 return (var()*m_n/(m_n-1)); // unbiased for small sample sizes
140 }
141
142 inline double stdDev_corr () const { return sqrt( var_corr() ); }
143 inline double stdDev () const { return sqrt( var() ); } // unbiased for small sample sizes
144
145 private:
146 size_t m_n;
148 double m_mean;
149 double m_squared;
150 };
151
152
153
154 enum class EnumFunction
155 {
156 ZERO = '0',
157 LINEAR = 'L',
158 TANH = 'T',
159 RELU = 'R',
160 SYMMRELU = 'r',
161 TANHSHIFT = 't',
162 SIGMOID = 's',
163 SOFTSIGN = 'S',
164 GAUSS = 'G',
165 GAUSSCOMPLEMENT = 'C'
166 };
167
168
169
171 {
172 NONE, L1, L2, L1MAX
173 };
174
175
176 enum class ModeOutputValues : int
177 {
178 DIRECT = 0x01,
179 SIGMOID = 0x02,
180 SOFTMAX = 0x04,
181 BATCHNORMALIZATION = 0x08
182 };
183
184
185
187 {
188 return (ModeOutputValues)(static_cast<std::underlying_type<ModeOutputValues>::type>(lhs) | static_cast<std::underlying_type<ModeOutputValues>::type>(rhs));
189 }
190
192 {
193 lhs = (ModeOutputValues)(static_cast<std::underlying_type<ModeOutputValues>::type>(lhs) | static_cast<std::underlying_type<ModeOutputValues>::type>(rhs));
194 return lhs;
195 }
196
198 {
199 return (ModeOutputValues)(static_cast<std::underlying_type<ModeOutputValues>::type>(lhs) & static_cast<std::underlying_type<ModeOutputValues>::type>(rhs));
200 }
201
203 {
204 lhs = (ModeOutputValues)(static_cast<std::underlying_type<ModeOutputValues>::type>(lhs) & static_cast<std::underlying_type<ModeOutputValues>::type>(rhs));
205 return lhs;
206 }
207
208
209 template <typename T>
210 bool isFlagSet (T flag, T value)
211 {
212 return (int)(value & flag) != 0;
213 }
214
215
216
217 class Net;
218
219
220
221
222
223
224
225 typedef std::vector<char> DropContainer;
226
227
228 /*! \brief The Batch class encapsulates one mini-batch
229 *
230 * Holds a const_iterator to the beginning and the end of one batch in a vector of Pattern
231 */
232 class Batch
233 {
234 public:
235 typedef typename std::vector<Pattern>::const_iterator const_iterator;
236
237 Batch (typename std::vector<Pattern>::const_iterator itBegin, typename std::vector<Pattern>::const_iterator itEnd)
239 , m_itEnd (itEnd)
240 {}
241
242 const_iterator begin () const { return m_itBegin; }
243 const_iterator end () const { return m_itEnd; }
244
245 size_t size () const { return std::distance (begin (), end ()); }
246
247 private:
248 const_iterator m_itBegin; ///< iterator denoting the beginning of the batch
249 const_iterator m_itEnd; ///< iterator denoting the end of the batch
250 };
251
252
253
254
255
256
257 template <typename ItSource, typename ItWeight, typename ItTarget>
259
260
261
262 template <typename ItSource, typename ItWeight, typename ItPrev>
264
265
266
267
268
269 template <typename ItValue, typename ItFunction>
271
272
273 template <typename ItValue, typename ItFunction, typename ItInverseFunction, typename ItGradient>
275
276
277
278 template <typename ItSource, typename ItDelta, typename ItTargetGradient, typename ItGradient>
283
284
285
286 template <EnumRegularization Regularization, typename ItSource, typename ItDelta, typename ItTargetGradient, typename ItGradient, typename ItWeight>
292
293
294
295 // ----- signature of a minimizer -------------
296 // class Minimizer
297 // {
298 // public:
299
300 // template <typename Function, typename Variables, typename PassThrough>
301 // double operator() (Function& fnc, Variables& vars, PassThrough& passThrough)
302 // {
303 // // auto itVars = begin (vars);
304 // // auto itVarsEnd = end (vars);
305
306 // std::vector<double> myweights;
307 // std::vector<double> gradients;
308
309 // double value = fnc (passThrough, myweights);
310 // value = fnc (passThrough, myweights, gradients);
311 // return value;
312 // }
313 // };
314
315
316
317 ///< list all the minimizer types
319 {
320 fSteepest ///< SGD
321 };
322
323
324
325
326
327 /*! \brief Steepest Gradient Descent algorithm (SGD)
328 *
329 * Implements a steepest gradient descent minimization algorithm
330 */
332 {
333 public:
334
336
337
338 /*! \brief c'tor
339 *
340 * C'tor
341 *
342 * \param learningRate denotes the learning rate for the SGD algorithm
343 * \param momentum fraction of the velocity which is taken over from the last step
344 * \param repetitions re-compute the gradients each "repetitions" steps
345 */
346 Steepest (double learningRate = 1e-4,
347 double momentum = 0.5,
348 size_t repetitions = 10)
349 : m_repetitions (repetitions)
350 , m_alpha (learningRate)
351 , m_beta (momentum)
352 {}
353
354 /*! \brief operator to call the steepest gradient descent algorithm
355 *
356 * entry point to start the minimization procedure
357 *
358 * \param fitnessFunction (templated) function which has to be provided. This function is minimized
359 * \param weights (templated) a reference to a container of weights. The result of the minimization procedure
360 * is returned via this reference (needs to support std::begin and std::end
361 * \param passThrough (templated) object which can hold any data which the fitness function needs. This object
362 * is not touched by the minimizer; This object is provided to the fitness function when
363 * called
364 */
365 template <typename Function, typename Weights, typename PassThrough>
366 double operator() (Function& fitnessFunction, Weights& weights, PassThrough& passThrough);
367
368
369 double m_alpha; ///< internal parameter (learningRate)
370 double m_beta; ///< internal parameter (momentum)
371 std::vector<double> m_prevGradients; ///< vector remembers the gradients of the previous step
372
373 std::vector<double> m_localWeights; ///< local weights for reuse in thread.
374 std::vector<double> m_localGradients; ///< local gradients for reuse in thread.
375 };
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394 template <typename ItOutput, typename ItTruth, typename ItDelta, typename ItInvActFnc>
396
397
398
399 template <typename ItProbability, typename ItTruth, typename ItDelta, typename ItInvActFnc>
401
402
403
404
405 template <typename ItOutput, typename ItTruth, typename ItDelta, typename ItInvActFnc>
407
408
409
410
411
412 template <typename ItWeight>
413 double weightDecay (double error, ItWeight itWeight, ItWeight itWeightEnd, double factorWeightDecay, EnumRegularization eRegularization);
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428 /*! \brief LayerData holds the data of one layer
429 *
430 * LayerData holds the data of one layer, but not its layout
431 *
432 *
433 */
435 {
436 public:
437 typedef std::vector<double> container_type;
438
439 typedef container_type::iterator iterator_type;
440 typedef container_type::const_iterator const_iterator_type;
441
442 typedef std::vector<std::function<double(double)> > function_container_type;
443 typedef function_container_type::iterator function_iterator_type;
444 typedef function_container_type::const_iterator const_function_iterator_type;
445
446 typedef DropContainer::const_iterator const_dropout_iterator;
447
448 /*! \brief c'tor of LayerData
449 *
450 * C'tor of LayerData for the input layer
451 *
452 * \param itInputBegin iterator to the begin of a vector which holds the values of the nodes of the neural net
453 * \param itInputEnd iterator to the end of a vector which holdsd the values of the nodes of the neural net
454 * \param eModeOutput indicates a potential tranformation of the output values before further computation
455 * DIRECT does not further transformation; SIGMOID applies a sigmoid transformation to each
456 * output value (to create a probability); SOFTMAX applies a softmax transformation to all
457 * output values (mutually exclusive probability)
458 */
460
461
462 /*! \brief c'tor of LayerData
463 *
464 * C'tor of LayerData for the input layer
465 *
466 * \param inputSize input size of this layer
467 */
468 LayerData (size_t inputSize);
470
471
472 /*! \brief c'tor of LayerData
473 *
474 * C'tor of LayerData for all layers which are not the input layer; Used during the training of the DNN
475 *
476 * \param size size of the layer
477 * \param itWeightBegin indicates the start of the weights for this layer on the weight vector
478 * \param itGradientBegin indicates the start of the gradients for this layer on the gradient vector
479 * \param activationFunction indicates activation functions for this layer
480 * \param inverseActivationFunction indicates the inverse activation functions for this layer
481 * \param eModeOutput indicates a potential tranformation of the output values before further computation
482 * DIRECT does not further transformation; SIGMOID applies a sigmoid transformation to each
483 * output value (to create a probability); SOFTMAX applies a softmax transformation to all
484 * output values (mutually exclusive probability)
485 */
486 LayerData (size_t size,
489 std::shared_ptr<std::function<double(double)>> activationFunction,
490 std::shared_ptr<std::function<double(double)>> inverseActivationFunction,
492
493 /*! \brief c'tor of LayerData
494 *
495 * C'tor of LayerData for all layers which are not the input layer; Used during the application of the DNN
496 *
497 * \param size size of the layer
498 * \param itWeightBegin indicates the start of the weights for this layer on the weight vector
499 * \param activationFunction indicates the activation function for this layer
500 * \param eModeOutput indicates a potential tranformation of the output values before further computation
501 * DIRECT does not further transformation; SIGMOID applies a sigmoid transformation to each
502 * output value (to create a probability); SOFTMAX applies a softmax transformation to all
503 * output values (mutually exclusive probability)
504 */
506 std::shared_ptr<std::function<double(double)>> activationFunction,
508
509 /*! \brief copy c'tor of LayerData
510 *
511 *
512 */
531
532 /*! \brief move c'tor of LayerData
533 *
534 *
535 */
554
555
556 /*! \brief change the input iterators
557 *
558 *
559 * \param itInputBegin indicates the start of the input node vector
560 * \param itInputEnd indicates the end of the input node vector
561 *
562 */
569
570 /*! \brief clear the values and the deltas
571 *
572 *
573 */
574 void clear ()
575 {
576 m_values.assign (m_values.size (), 0.0);
577 m_deltas.assign (m_deltas.size (), 0.0);
578 }
579
580 const_iterator_type valuesBegin () const { return m_isInputLayer ? m_itInputBegin : begin (m_values); } ///< returns const iterator to the begin of the (node) values
581 const_iterator_type valuesEnd () const { return m_isInputLayer ? m_itInputEnd : end (m_values); } ///< returns iterator to the end of the (node) values
582
583 iterator_type valuesBegin () { assert (!m_isInputLayer); return begin (m_values); } ///< returns iterator to the begin of the (node) values
584 iterator_type valuesEnd () { assert (!m_isInputLayer); return end (m_values); } ///< returns iterator to the end of the (node) values
585
586 ModeOutputValues outputMode () const { return m_eModeOutput; } ///< returns the output mode
587 container_type probabilities () const { return computeProbabilities (); } ///< computes the probabilities from the current node values and returns them
588
589 iterator_type deltasBegin () { return begin (m_deltas); } ///< returns iterator to the begin of the deltas (back-propagation)
590 iterator_type deltasEnd () { return end (m_deltas); } ///< returns iterator to the end of the deltas (back-propagation)
591
592 const_iterator_type deltasBegin () const { return begin (m_deltas); } ///< returns const iterator to the begin of the deltas (back-propagation)
593 const_iterator_type deltasEnd () const { return end (m_deltas); } ///< returns const iterator to the end of the deltas (back-propagation)
594
595 iterator_type valueGradientsBegin () { return begin (m_valueGradients); } ///< returns iterator to the begin of the gradients of the node values
596 iterator_type valueGradientsEnd () { return end (m_valueGradients); } ///< returns iterator to the end of the gradients of the node values
597
598 const_iterator_type valueGradientsBegin () const { return begin (m_valueGradients); } ///< returns const iterator to the begin of the gradients
599 const_iterator_type valueGradientsEnd () const { return end (m_valueGradients); } ///< returns const iterator to the end of the gradients
600
601 iterator_type gradientsBegin () { assert (m_hasGradients); return m_itGradientBegin; } ///< returns iterator to the begin of the gradients
602 const_iterator_type gradientsBegin () const { assert (m_hasGradients); return m_itGradientBegin; } ///< returns const iterator to the begin of the gradients
603 const_iterator_type weightsBegin () const { assert (m_hasWeights); return m_itConstWeightBegin; } ///< returns const iterator to the begin of the weights for this layer
604
605 std::shared_ptr<std::function<double(double)>> activationFunction () const { return m_activationFunction; }
606 std::shared_ptr<std::function<double(double)>> inverseActivationFunction () const { return m_inverseActivationFunction; }
607
608 /*! \brief set the drop-out info for this layer
609 *
610 */
611 template <typename Iterator>
612 void setDropOut (Iterator itDrop) { m_itDropOut = itDrop; m_hasDropOut = true; }
613
614 /*! \brief clear the drop-out-data for this layer
615 *
616 *
617 */
618 void clearDropOut () { m_hasDropOut = false; }
619
620 bool hasDropOut () const { return m_hasDropOut; } ///< has this layer drop-out turned on?
621 const_dropout_iterator dropOut () const { assert (m_hasDropOut); return m_itDropOut; } ///< return the begin of the drop-out information
622
623 size_t size () const { return m_size; } ///< return the size of the layer
624
625 private:
626
627 /*! \brief compute the probabilities from the node values
628 *
629 *
630 */
632
633 private:
634
635 size_t m_size; ////< layer size
636
637 const_iterator_type m_itInputBegin; ///< iterator to the first of the nodes in the input node vector
638 const_iterator_type m_itInputEnd; ///< iterator to the end of the nodes in the input node vector
639
640 std::vector<double> m_deltas; ///< stores the deltas for the DNN training
641 std::vector<double> m_valueGradients; ///< stores the gradients of the values (nodes)
642 std::vector<double> m_values; ///< stores the values of the nodes in this layer
643 const_dropout_iterator m_itDropOut; ///< iterator to a container indicating if the corresponding node is to be dropped
644 bool m_hasDropOut; ///< dropOut is turned on?
645
646 const_iterator_type m_itConstWeightBegin; ///< const iterator to the first weight of this layer in the weight vector
647 iterator_type m_itGradientBegin; ///< iterator to the first gradient of this layer in the gradient vector
648
649 std::shared_ptr<std::function<double(double)>> m_activationFunction; ///< activation function for this layer
650 std::shared_ptr<std::function<double(double)>> m_inverseActivationFunction; ///< inverse activation function for this layer
651
652 bool m_isInputLayer; ///< is this layer an input layer
653 bool m_hasWeights; ///< does this layer have weights (it does not if it is the input layer)
654 bool m_hasGradients; ///< does this layer have gradients (only if in training mode)
655
656 ModeOutputValues m_eModeOutput; ///< stores the output mode (DIRECT, SIGMOID, SOFTMAX)
657
658 };
659
660
661
662
663
664 /*! \brief Layer defines the layout of a layer
665 *
666 * Layer defines the layout of a specific layer in the DNN
667 * Objects of this class don't hold the layer data itself (see class "LayerData")
668 *
669 */
670 class Layer
671 {
672 public:
673
674 /*! \brief c'tor for defining a Layer
675 *
676 *
677 */
679
680 ModeOutputValues modeOutputValues () const { return m_eModeOutputValues; } ///< get the mode-output-value (direct, probabilities)
682
683 size_t numNodes () const { return m_numNodes; } ///< return the number of nodes of this layer
684 size_t numWeights (size_t numInputNodes) const { return numInputNodes * numNodes (); } ///< return the number of weights for this layer (fully connected)
685
686 std::shared_ptr<std::function<double(double)>> activationFunction () const { return m_activationFunction; } ///< fetch the activation function for this layer
687 std::shared_ptr<std::function<double(double)>> inverseActivationFunction () const { return m_inverseActivationFunction; } ///< fetch the inverse activation function for this layer
688
689 EnumFunction activationFunctionType () const { return m_activationFunctionType; } ///< get the activation function type for this layer
690
691 private:
692
693
694 std::shared_ptr<std::function<double(double)>> m_activationFunction; ///< stores the activation function
695 std::shared_ptr<std::function<double(double)>> m_inverseActivationFunction; ///< stores the inverse activation function
696
697
699
700 ModeOutputValues m_eModeOutputValues; ///< do the output values of this layer have to be transformed somehow (e.g. to probabilities) or returned as such
702
703 friend class Net;
704 };
705
706
707
708
709
710 template <typename LAYERDATA>
712
713
714 template <typename LAYERDATA>
716
717
718 template <typename LAYERDATA>
720
721
722
723 /*! \brief Settings for the training of the neural net
724 *
725 *
726 */
728 {
729 public:
730
731 /*! \brief c'tor
732 *
733 *
734 */
736 size_t _convergenceSteps = 15, size_t _batchSize = 10, size_t _testRepetitions = 7,
739 double _learningRate = 1e-5, double _momentum = 0.3,
740 int _repetitions = 3,
741 bool _multithreading = true);
742
743 /*! \brief d'tor
744 *
745 *
746 */
747 virtual ~Settings ();
748
749
750 /*! \brief set the drop-out configuration (layer-wise)
751 *
752 * \param begin begin of an array or vector denoting the drop-out probabilities for each layer
753 * \param end end of an array or vector denoting the drop-out probabilities for each layer
754 * \param _dropRepetitions denotes after how many repetitions the drop-out setting (which nodes are dropped out exactly) is changed
755 */
756 template <typename Iterator>
757 void setDropOut (Iterator begin, Iterator end, size_t _dropRepetitions) { m_dropOut.assign (begin, end); m_dropRepetitions = _dropRepetitions; }
758
759 size_t dropRepetitions () const { return m_dropRepetitions; }
760 const std::vector<double>& dropFractions () const { return m_dropOut; }
761
762 void setMonitoring (std::shared_ptr<Monitoring> ptrMonitoring) { fMonitoring = ptrMonitoring; } ///< prepared for monitoring
763
764 size_t convergenceSteps () const { return m_convergenceSteps; } ///< how many steps until training is deemed to have converged
765 size_t batchSize () const { return m_batchSize; } ///< mini-batch size
766 size_t testRepetitions () const { return m_testRepetitions; } ///< how often is the test data tested
767 double factorWeightDecay () const { return m_factorWeightDecay; } ///< get the weight-decay factor
768
769 double learningRate () const { return fLearningRate; } ///< get the learning rate
770 double momentum () const { return fMomentum; } ///< get the momentum (e.g. for SGD)
771 int repetitions () const { return fRepetitions; } ///< how many steps have to be gone until the batch is changed
772 MinimizerType minimizerType () const { return fMinimizerType; } ///< which minimizer shall be used (e.g. SGD)
773
774
775
776
777
778
779 virtual void testSample (double /*error*/, double /*output*/, double /*target*/, double /*weight*/) {} ///< virtual function to be used for monitoring (callback)
780 virtual void startTrainCycle () ///< callback for monitoring and logging
781 {
784 m_minError = 1e10;
785 }
786 virtual void endTrainCycle (double /*error*/) {} ///< callback for monitoring and logging
787
788 virtual void setProgressLimits (double minProgress = 0, double maxProgress = 100) ///< for monitoring and logging (set the current "progress" limits for the display of the progress) \param minProgress minimum value \param maxProgress maximum value
789 {
792 }
793 virtual void startTraining () ///< start drawing the progress bar
794 {
796 }
797 virtual void cycle (double progress, TString text) ///< advance on the progress bar \param progress the new value \param text a label
798 {
800 }
801
802 virtual void startTestCycle () {} ///< callback for monitoring and loggging
803 virtual void endTestCycle () {} ///< callback for monitoring and loggging
804 virtual void testIteration () {} ///< callback for monitoring and loggging
805 virtual void drawSample (const std::vector<double>& /*input*/, const std::vector<double>& /* output */, const std::vector<double>& /* target */, double /* patternWeight */) {} ///< callback for monitoring and logging
806
807 virtual void computeResult (const Net& /* net */, std::vector<double>& /* weights */) {} ///< callback for monitoring and logging
808
809 virtual bool hasConverged (double testError); ///< has this training converged already?
810
811 EnumRegularization regularization () const { return m_regularization; } ///< some regularization of the DNN is turned on?
812
813 bool useMultithreading () const { return m_useMultithreading; } ///< is multithreading turned on?
814
815
816 void pads (int numPads) { if (fMonitoring) fMonitoring->pads (numPads); } ///< preparation for monitoring
817 void create (std::string histoName, int bins, double min, double max) { if (fMonitoring) fMonitoring->create (histoName, bins, min, max); } ///< for monitoring
818 void create (std::string histoName, int bins, double min, double max, int bins2, double min2, double max2) { if (fMonitoring) fMonitoring->create (histoName, bins, min, max, bins2, min2, max2); } ///< for monitoring
819 void addPoint (std::string histoName, double x) { if (fMonitoring) fMonitoring->addPoint (histoName, x); } ///< for monitoring
820 void addPoint (std::string histoName, double x, double y) {if (fMonitoring) fMonitoring->addPoint (histoName, x, y); } ///< for monitoring
821 void plot (std::string histoName, std::string options, int pad, EColor color) { if (fMonitoring) fMonitoring->plot (histoName, options, pad, color); } ///< for monitoring
822 void clear (std::string histoName) { if (fMonitoring) fMonitoring->clear (histoName); } ///< for monitoring
823 bool exists (std::string histoName) { if (fMonitoring) return fMonitoring->exists (histoName); return false; } ///< for monitoring
824
825 size_t convergenceCount () const { return m_convergenceCount; } ///< returns the current convergence count
826 size_t maxConvergenceCount () const { return m_maxConvergenceCount; } ///< returns the max convergence count so far
827 size_t minError () const { return m_minError; } ///< returns the smallest error so far
828
829 public:
830 Timer m_timer; ///< timer for monitoring
831 double m_minProgress; ///< current limits for the progress bar
832 double m_maxProgress; ///< current limits for the progress bar
833
834
835 size_t m_convergenceSteps; ///< number of steps without improvement to consider the DNN to have converged
836 size_t m_batchSize; ///< mini-batch size
839
840 size_t count_E;
841 size_t count_dE;
844
846
848 std::vector<double> m_dropOut;
849
851 double fMomentum;
854
858
859
860 protected:
862
863 std::shared_ptr<Monitoring> fMonitoring;
864 };
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888 /*! \brief Settings for classification
889 *
890 * contains additional settings if the DNN problem is classification
891 */
893 {
894 public:
895 /*! \brief c'tor
896 *
897 *
898 */
917
918 /*! \brief d'tor
919 *
920 *
921 */
923 {
924 }
925
926 void startTrainCycle () override;
927 void endTrainCycle (double /*error*/) override;
928 void testIteration () override { if (fMonitoring) fMonitoring->ProcessEvents (); }
929
930
931 /* void createHistograms () */
932 /* { */
933 /* std::cout << "is hist ROC existing?" << std::endl; */
934 /* if (m_histROC) */
935 /* { */
936 /* std::cout << "--> yes" << std::endl; */
937 /* fMonitoring->ProcessEvents (); */
938 /* return; */
939 /* } */
940
941 /* std::cout << "create histograms" << std::endl; */
942 /* TCanvas* canvas = fMonitoring->GetCanvas (); */
943 /* if (canvas) */
944 /* { */
945 /* std::cout << "canvas divide" << std::endl; */
946 /* canvas->cd (); */
947 /* canvas->Divide (2,2); */
948 /* } */
949 /* if (!m_histROC) */
950 /* { */
951 /* m_histROC = new TH2F ("ROC","ROC", 1000, 0, 1.0, 1000, 0, 1.0); m_histROC->SetDirectory (0); */
952 /* m_histROC->SetLineColor (kBlue); */
953 /* } */
954 /* if (!m_histSignificance) */
955 /* { */
956 /* m_histSignificance = new TH2F ("Significance", "Significance", 1000, 0,1.0, 5, 0.0, 2.0); */
957 /* m_histSignificance->SetDirectory (0); */
958 /* m_histSignificance->SetBit (TH1::kCanRebin); */
959 /* m_histROC->SetLineColor (kRed); */
960 /* } */
961 /* if (!m_histError) */
962 /* { */
963 /* m_histError = new TH1F ("Error", "Error", 100, 0, 100); */
964 /* m_histError->SetDirectory (0); */
965 /* m_histError->SetBit (TH1::kCanRebin); */
966 /* m_histROC->SetLineColor (kGreen); */
967 /* } */
968 /* if (!m_histOutputSignal) */
969 /* { */
970 /* m_histOutputSignal = new TH1F ("Signal", "Signal", 100, 0, 1.0); */
971 /* m_histOutputSignal->SetDirectory (0); */
972 /* m_histOutputSignal->SetBit (TH1::kCanRebin); */
973 /* } */
974 /* if (!m_histOutputBackground) */
975 /* { */
976 /* m_histOutputBackground = new TH1F ("Background", "Background", 100, 0, 1.0); */
977 /* m_histOutputBackground->SetDirectory (0); */
978 /* m_histOutputBackground->SetBit (TH1::kCanRebin); */
979 /* } */
980
981 /* fMonitoring->ProcessEvents (); */
982 /* } */
983
984 void testSample (double error, double output, double target, double weight) override;
985
986 void startTestCycle () override;
987 void endTestCycle () override;
988
989
990 void setWeightSums (double sumOfSigWeights, double sumOfBkgWeights);
991 void setResultComputation (std::string _fileNameNetConfig, std::string _fileNameResult, std::vector<Pattern>* _resultPatternContainer);
992
993 std::vector<double> m_input;
994 std::vector<double> m_output;
995 std::vector<double> m_targets;
996 std::vector<double> m_weights;
997
998 std::vector<double> m_ams;
999 std::vector<double> m_significances;
1000
1001
1005
1007 std::vector<Pattern>* m_pResultPatternContainer;
1008 std::string m_fileNameResult;
1010
1011
1012 /* TH2F* m_histROC; */
1013 /* TH2F* m_histSignificance; */
1014
1015 /* TH1F* m_histError; */
1016 /* TH1F* m_histOutputSignal; */
1017 /* TH1F* m_histOutputBackground; */
1018 };
1019
1020
1021
1022
1023
1024
1025
1026 ///< used to distinguish between different function signatures
1027 enum class ModeOutput
1028 {
1029 FETCH
1030 };
1031
1032 /*! \brief error functions to be chosen from
1033 *
1034 *
1035 */
1037 {
1038 SUMOFSQUARES = 'S',
1039 CROSSENTROPY = 'C',
1041 };
1042
1043 /*! \brief weight initialization strategies to be chosen from
1044 *
1045 *
1046 */
1051
1052
1053
1054 /*! \brief neural net
1055 *
1056 * holds the structure of all layers and some data for the whole net
1057 * does not know the layer data though (i.e. values of the nodes and weights)
1058 */
1059 class Net
1060 {
1061 public:
1062
1063 typedef std::vector<double> container_type;
1064 typedef container_type::iterator iterator_type;
1065 typedef std::pair<iterator_type,iterator_type> begin_end_type;
1066
1067
1068 /*! \brief c'tor
1069 *
1070 *
1071 */
1074 , m_sizeInput (0)
1075 , m_layers ()
1076 {
1077 }
1078
1079 /*! \brief d'tor
1080 *
1081 *
1082 */
1089
1090 void setInputSize (size_t sizeInput) { m_sizeInput = sizeInput; } ///< set the input size of the DNN
1091 void setOutputSize (size_t sizeOutput) { m_sizeOutput = sizeOutput; } ///< set the output size of the DNN
1092 void addLayer (Layer& layer) { m_layers.push_back (layer); } ///< add a layer (layout)
1093 void addLayer (Layer&& layer) { m_layers.push_back (layer); }
1094 void setErrorFunction (ModeErrorFunction eErrorFunction) { m_eErrorFunction = eErrorFunction; } ///< which error function is to be used
1095
1096 size_t inputSize () const { return m_sizeInput; } ///< input size of the DNN
1097 size_t outputSize () const { return m_sizeOutput; } ///< output size of the DNN
1098
1099 /*! \brief set the drop out configuration
1100 *
1101 *
1102 */
1103 template <typename WeightsType, typename DropProbabilities>
1104 void dropOutWeightFactor (WeightsType& weights,
1105 const DropProbabilities& drops,
1106 bool inverse = false);
1107
1108 /*! \brief start the training
1109 *
1110 * \param weights weight vector
1111 * \param trainPattern training pattern
1112 * \param testPattern test pattern
1113 * \param minimizer use this minimizer for training (e.g. SGD)
1114 * \param settings settings used for this training run
1115 */
1116 template <typename Minimizer>
1117 double train (std::vector<double>& weights,
1118 std::vector<Pattern>& trainPattern,
1119 const std::vector<Pattern>& testPattern,
1120 Minimizer& minimizer,
1122
1123 /*! \brief pre-training for future use
1124 *
1125 *
1126 */
1127 template <typename Minimizer>
1128 void preTrain (std::vector<double>& weights,
1129 std::vector<Pattern>& trainPattern,
1130 const std::vector<Pattern>& testPattern,
1131 Minimizer& minimizer, Settings& settings);
1132
1133
1134 /*! \brief executes one training cycle
1135 *
1136 * \param minimizer the minimizer to be used
1137 * \param weights the weight vector to be used
1138 * \param itPatternBegin the pattern to be trained with
1139 * \param itPatternEnd the pattern to be trained with
1140 * \param settings the settings for the training
1141 * \param dropContainer the configuration for DNN drop-out
1142 */
1143 template <typename Iterator, typename Minimizer>
1144 inline double trainCycle (Minimizer& minimizer, std::vector<double>& weights,
1145 Iterator itPatternBegin, Iterator itPatternEnd,
1148
1149 size_t numWeights (size_t trainingStartLayer = 0) const; ///< returns the number of weights in this net
1150 size_t numNodes (size_t trainingStartLayer = 0) const; ///< returns the number of nodes in this net
1151
1152 template <typename Weights>
1153 std::vector<double> compute (const std::vector<double>& input, const Weights& weights) const; ///< compute the net with the given input and the given weights
1154
1155 template <typename Weights, typename PassThrough>
1156 double operator() (PassThrough& settingsAndBatch, const Weights& weights) const; ///< execute computation of the DNN for one mini-batch (used by the minimizer); no computation of gradients
1157
1158 template <typename Weights, typename PassThrough, typename OutContainer>
1159 double operator() (PassThrough& settingsAndBatch, const Weights& weights, ModeOutput eFetch, OutContainer& outputContainer) const; ///< execute computation of the DNN for one mini-batch; helper function
1160
1161 template <typename Weights, typename Gradients, typename PassThrough>
1162 double operator() (PassThrough& settingsAndBatch, Weights& weights, Gradients& gradients) const; ///< execute computation of the DNN for one mini-batch (used by the minimizer); returns gradients as well
1163
1164 template <typename Weights, typename Gradients, typename PassThrough, typename OutContainer>
1165 double operator() (PassThrough& settingsAndBatch, Weights& weights, Gradients& gradients, ModeOutput eFetch, OutContainer& outputContainer) const;
1166
1167
1168 template <typename LayerContainer, typename DropContainer, typename ItWeight, typename ItGradient>
1169 std::vector<std::vector<LayerData>> prepareLayerData (LayerContainer& layers,
1170 Batch& batch,
1176 size_t& totalNumWeights) const;
1177
1178 template <typename LayerContainer>
1180 std::vector<LayerData>& layerData) const;
1181
1182
1183 template <typename LayerContainer, typename LayerPatternContainer>
1184 void forwardBatch (const LayerContainer& _layers,
1186 std::vector<double>& valuesMean,
1187 std::vector<double>& valuesStdDev,
1188 size_t trainFromLayer) const;
1189
1190 template <typename OutputContainer>
1192
1193 template <typename OutputContainer>
1194 void fetchOutput (const std::vector<LayerData>& layerPatternData, OutputContainer& outputContainer) const;
1195
1196
1197 template <typename ItWeight>
1198 std::tuple</*sumError*/double,/*sumWeights*/double> computeError (const Settings& settings,
1199 std::vector<LayerData>& lastLayerData,
1200 Batch& batch,
1202 ItWeight itWeightEnd) const;
1203
1204 template <typename Settings>
1205 void backPropagate (std::vector<std::vector<LayerData>>& layerPatternData,
1206 const Settings& settings,
1207 size_t trainFromLayer,
1208 size_t totalNumWeights) const;
1209
1210
1211
1212 /*! \brief main NN computation function
1213 *
1214 *
1215 */
1216 template <typename LayerContainer, typename PassThrough, typename ItWeight, typename ItGradient, typename OutContainer>
1220 size_t trainFromLayer,
1222
1223
1224
1225 double E ();
1226 void dE ();
1227
1228
1229 /*! \brief computes the error of the DNN
1230 *
1231 *
1232 */
1233 template <typename Container, typename ItWeight>
1238 double patternWeight,
1239 double factorWeightDecay,
1241
1242
1243 const std::vector<Layer>& layers () const { return m_layers; } ///< returns the layers (structure)
1244 std::vector<Layer>& layers () { return m_layers; } ///< returns the layers (structure)
1245
1246 void removeLayer () { m_layers.pop_back (); } ///< remove one layer
1247
1248
1249 void clear () ///< clear one layer
1250 {
1251 m_layers.clear ();
1253 }
1254
1255
1256 template <typename OutIterator>
1258 OutIterator itWeight); ///< initialize the weights with the given strategy
1259
1260 protected:
1261
1262 void fillDropContainer (DropContainer& dropContainer, double dropFraction, size_t numNodes) const; ///< prepare the drop-out-container (select the nodes which are to be dropped out)
1263
1264
1265 private:
1266
1267 ModeErrorFunction m_eErrorFunction; ///< denotes the error function
1268 size_t m_sizeInput; ///< input size of this DNN
1269 size_t m_sizeOutput; ///< output size of this DNN
1270 std::vector<Layer> m_layers; ///< layer-structure-data
1271 };
1272
1273
1274
1275
1276typedef std::tuple<Settings&, Batch&, DropContainer&> pass_through_type;
1277
1278
1279
1280
1281
1282
1283
1284 } // namespace DNN
1285} // namespace TMVA
1286
1287
1288// include the implementations (in header file, because they are templated)
1289#include "TMVA/NeuralNet.icc"
1290
1291#endif
1292
#define R(a, b, c, d, e, f, g, h, i)
Definition RSha256.hxx:110
#define e(i)
Definition RSha256.hxx:103
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
EColor
Definition Rtypes.h:66
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
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 target
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 text
char name[80]
Definition TGX11.cxx:148
The Batch class encapsulates one mini-batch.
Definition NeuralNet.h:233
const_iterator m_itEnd
iterator denoting the end of the batch
Definition NeuralNet.h:249
const_iterator begin() const
Definition NeuralNet.h:242
const_iterator end() const
Definition NeuralNet.h:243
Batch(typename std::vector< Pattern >::const_iterator itBegin, typename std::vector< Pattern >::const_iterator itEnd)
Definition NeuralNet.h:237
size_t size() const
Definition NeuralNet.h:245
std::vector< Pattern >::const_iterator const_iterator
Definition NeuralNet.h:235
const_iterator m_itBegin
iterator denoting the beginning of the batch
Definition NeuralNet.h:248
Settings for classificationused to distinguish between different function signatures.
Definition NeuralNet.h:893
void startTestCycle() override
action to be done when the test cycle is started (e.g.
void endTrainCycle(double) override
action to be done when the training cycle is ended (e.g.
std::vector< Pattern > * m_pResultPatternContainer
Definition NeuralNet.h:1007
void endTestCycle() override
action to be done when the training cycle is ended (e.g.
void setResultComputation(std::string _fileNameNetConfig, std::string _fileNameResult, std::vector< Pattern > *_resultPatternContainer)
preparation for monitoring output
ClassificationSettings(TString name, size_t _convergenceSteps=15, size_t _batchSize=10, size_t _testRepetitions=7, double _factorWeightDecay=1e-5, EnumRegularization _regularization=EnumRegularization::NONE, size_t _scaleToNumEvents=0, MinimizerType _eMinimizerType=MinimizerType::fSteepest, double _learningRate=1e-5, double _momentum=0.3, int _repetitions=3, bool _useMultithreading=true)
c'tor
Definition NeuralNet.h:899
std::vector< double > m_input
Definition NeuralNet.h:993
std::vector< double > m_significances
Definition NeuralNet.h:999
std::vector< double > m_weights
Definition NeuralNet.h:996
virtual ~ClassificationSettings()
d'tor
Definition NeuralNet.h:922
std::vector< double > m_targets
Definition NeuralNet.h:995
void startTrainCycle() override
action to be done when the training cycle is started (e.g.
void testSample(double error, double output, double target, double weight) override
action to be done after the computation of a test sample (e.g.
void testIteration() override
callback for monitoring and loggging
Definition NeuralNet.h:928
void setWeightSums(double sumOfSigWeights, double sumOfBkgWeights)
set the weight sums to be scaled to (preparations for monitoring output)
std::vector< double > m_ams
Definition NeuralNet.h:998
std::vector< double > m_output
Definition NeuralNet.h:994
LayerData holds the data of one layer.
Definition NeuralNet.h:435
const_iterator_type m_itInputBegin
iterator to the first of the nodes in the input node vector
Definition NeuralNet.h:637
const_iterator_type deltasBegin() const
returns const iterator to the begin of the deltas (back-propagation)
Definition NeuralNet.h:592
iterator_type valuesBegin()
returns iterator to the begin of the (node) values
Definition NeuralNet.h:583
const_iterator_type valuesEnd() const
returns iterator to the end of the (node) values
Definition NeuralNet.h:581
bool m_hasGradients
does this layer have gradients (only if in training mode)
Definition NeuralNet.h:654
std::vector< double > m_deltas
stores the deltas for the DNN training
Definition NeuralNet.h:640
container_type::iterator iterator_type
Definition NeuralNet.h:439
LayerData(const_iterator_type itInputBegin, const_iterator_type itInputEnd, ModeOutputValues eModeOutput=ModeOutputValues::DIRECT)
c'tor of LayerData
Definition NeuralNet.cxx:81
void setDropOut(Iterator itDrop)
set the drop-out info for this layer
Definition NeuralNet.h:612
void setInput(const_iterator_type itInputBegin, const_iterator_type itInputEnd)
change the input iterators
Definition NeuralNet.h:563
std::vector< std::function< double(double)> > function_container_type
Definition NeuralNet.h:442
iterator_type valuesEnd()
returns iterator to the end of the (node) values
Definition NeuralNet.h:584
const_dropout_iterator m_itDropOut
iterator to a container indicating if the corresponding node is to be dropped
Definition NeuralNet.h:643
iterator_type valueGradientsBegin()
returns iterator to the begin of the gradients of the node values
Definition NeuralNet.h:595
iterator_type gradientsBegin()
returns iterator to the begin of the gradients
Definition NeuralNet.h:601
iterator_type deltasBegin()
returns iterator to the begin of the deltas (back-propagation)
Definition NeuralNet.h:589
bool m_hasWeights
does this layer have weights (it does not if it is the input layer)
Definition NeuralNet.h:653
const_dropout_iterator dropOut() const
return the begin of the drop-out information
Definition NeuralNet.h:621
LayerData(LayerData &&other)
move c'tor of LayerData
Definition NeuralNet.h:536
std::vector< double > container_type
Definition NeuralNet.h:437
size_t size() const
return the size of the layer
Definition NeuralNet.h:623
const_iterator_type weightsBegin() const
returns const iterator to the begin of the weights for this layer
Definition NeuralNet.h:603
function_container_type::const_iterator const_function_iterator_type
Definition NeuralNet.h:444
LayerData(const LayerData &other)
copy c'tor of LayerData
Definition NeuralNet.h:513
function_container_type::iterator function_iterator_type
Definition NeuralNet.h:443
std::vector< double > m_values
stores the values of the nodes in this layer
Definition NeuralNet.h:642
const_iterator_type m_itInputEnd
iterator to the end of the nodes in the input node vector
Definition NeuralNet.h:638
container_type::const_iterator const_iterator_type
Definition NeuralNet.h:440
ModeOutputValues outputMode() const
returns the output mode
Definition NeuralNet.h:586
iterator_type m_itGradientBegin
iterator to the first gradient of this layer in the gradient vector
Definition NeuralNet.h:647
const_iterator_type gradientsBegin() const
returns const iterator to the begin of the gradients
Definition NeuralNet.h:602
std::shared_ptr< std::function< double(double)> > inverseActivationFunction() const
Definition NeuralNet.h:606
iterator_type deltasEnd()
returns iterator to the end of the deltas (back-propagation)
Definition NeuralNet.h:590
std::vector< double > m_valueGradients
stores the gradients of the values (nodes)
Definition NeuralNet.h:641
const_iterator_type m_itConstWeightBegin
const iterator to the first weight of this layer in the weight vector
Definition NeuralNet.h:646
iterator_type valueGradientsEnd()
returns iterator to the end of the gradients of the node values
Definition NeuralNet.h:596
void clear()
clear the values and the deltas
Definition NeuralNet.h:574
std::shared_ptr< std::function< double(double)> > activationFunction() const
Definition NeuralNet.h:605
container_type computeProbabilities() const
compute the probabilities from the node values
const_iterator_type deltasEnd() const
returns const iterator to the end of the deltas (back-propagation)
Definition NeuralNet.h:593
bool m_hasDropOut
dropOut is turned on?
Definition NeuralNet.h:644
bool m_isInputLayer
is this layer an input layer
Definition NeuralNet.h:652
bool hasDropOut() const
has this layer drop-out turned on?
Definition NeuralNet.h:620
const_iterator_type valueGradientsBegin() const
returns const iterator to the begin of the gradients
Definition NeuralNet.h:598
const_iterator_type valueGradientsEnd() const
returns const iterator to the end of the gradients
Definition NeuralNet.h:599
container_type probabilities() const
computes the probabilities from the current node values and returns them
Definition NeuralNet.h:587
void clearDropOut()
clear the drop-out-data for this layer
Definition NeuralNet.h:618
ModeOutputValues m_eModeOutput
stores the output mode (DIRECT, SIGMOID, SOFTMAX)
Definition NeuralNet.h:656
std::shared_ptr< std::function< double(double)> > m_inverseActivationFunction
inverse activation function for this layer
Definition NeuralNet.h:650
DropContainer::const_iterator const_dropout_iterator
Definition NeuralNet.h:446
const_iterator_type valuesBegin() const
returns const iterator to the begin of the (node) values
Definition NeuralNet.h:580
std::shared_ptr< std::function< double(double)> > m_activationFunction
activation function for this layer
Definition NeuralNet.h:649
Layer defines the layout of a layer.
Definition NeuralNet.h:671
void modeOutputValues(ModeOutputValues eModeOutputValues)
set the mode-output-value
Definition NeuralNet.h:681
std::shared_ptr< std::function< double(double)> > m_activationFunction
stores the activation function
Definition NeuralNet.h:694
std::shared_ptr< std::function< double(double)> > activationFunction() const
fetch the activation function for this layer
Definition NeuralNet.h:686
std::shared_ptr< std::function< double(double)> > m_inverseActivationFunction
stores the inverse activation function
Definition NeuralNet.h:695
size_t numNodes() const
return the number of nodes of this layer
Definition NeuralNet.h:683
ModeOutputValues m_eModeOutputValues
do the output values of this layer have to be transformed somehow (e.g. to probabilities) or returned...
Definition NeuralNet.h:700
size_t numWeights(size_t numInputNodes) const
return the number of weights for this layer (fully connected)
Definition NeuralNet.h:684
std::shared_ptr< std::function< double(double)> > inverseActivationFunction() const
fetch the inverse activation function for this layer
Definition NeuralNet.h:687
EnumFunction m_activationFunctionType
Definition NeuralNet.h:701
Layer(size_t numNodes, EnumFunction activationFunction, ModeOutputValues eModeOutputValues=ModeOutputValues::DIRECT)
c'tor for defining a Layer
EnumFunction activationFunctionType() const
get the activation function type for this layer
Definition NeuralNet.h:689
ModeOutputValues modeOutputValues() const
get the mode-output-value (direct, probabilities)
Definition NeuralNet.h:680
double mean() const
Definition NeuralNet.h:124
double var_corr() const
Definition NeuralNet.h:134
void add(T value, double weight=1.0)
Definition NeuralNet.h:91
double stdDev_corr() const
Definition NeuralNet.h:142
double weights() const
Definition NeuralNet.h:123
void add(ITERATOR itBegin, ITERATOR itEnd)
Definition NeuralNet.h:114
double var() const
Definition NeuralNet.h:125
double stdDev() const
Definition NeuralNet.h:143
neural net
Definition NeuralNet.h:1060
void setInputSize(size_t sizeInput)
set the input size of the DNN
Definition NeuralNet.h:1090
std::vector< Layer > & layers()
returns the layers (structure)
Definition NeuralNet.h:1244
void forwardBatch(const LayerContainer &_layers, LayerPatternContainer &layerPatternData, std::vector< double > &valuesMean, std::vector< double > &valuesStdDev, size_t trainFromLayer) const
Net(const Net &other)
d'tor
Definition NeuralNet.h:1083
std::vector< Layer > m_layers
layer-structure-data
Definition NeuralNet.h:1270
std::vector< double > compute(const std::vector< double > &input, const Weights &weights) const
compute the net with the given input and the given weights
std::vector< double > container_type
Definition NeuralNet.h:1063
container_type::iterator iterator_type
Definition NeuralNet.h:1064
void preTrain(std::vector< double > &weights, std::vector< Pattern > &trainPattern, const std::vector< Pattern > &testPattern, Minimizer &minimizer, Settings &settings)
pre-training for future use
void fetchOutput(const LayerData &lastLayerData, OutputContainer &outputContainer) const
size_t inputSize() const
input size of the DNN
Definition NeuralNet.h:1096
std::pair< iterator_type, iterator_type > begin_end_type
Definition NeuralNet.h:1065
ModeErrorFunction m_eErrorFunction
denotes the error function
Definition NeuralNet.h:1267
void addLayer(Layer &&layer)
Definition NeuralNet.h:1093
size_t numNodes(size_t trainingStartLayer=0) const
returns the number of nodes in this net
double train(std::vector< double > &weights, std::vector< Pattern > &trainPattern, const std::vector< Pattern > &testPattern, Minimizer &minimizer, Settings &settings)
start the training
const std::vector< Layer > & layers() const
returns the layers (structure)
Definition NeuralNet.h:1243
std::vector< std::vector< LayerData > > prepareLayerData(LayerContainer &layers, Batch &batch, const DropContainer &dropContainer, ItWeight itWeightBegin, ItWeight itWeightEnd, ItGradient itGradientBegin, ItGradient itGradientEnd, size_t &totalNumWeights) const
void setErrorFunction(ModeErrorFunction eErrorFunction)
which error function is to be used
Definition NeuralNet.h:1094
void initializeWeights(WeightInitializationStrategy eInitStrategy, OutIterator itWeight)
initialize the weights with the given strategy
size_t outputSize() const
output size of the DNN
Definition NeuralNet.h:1097
double errorFunction(LayerData &layerData, Container truth, ItWeight itWeight, ItWeight itWeightEnd, double patternWeight, double factorWeightDecay, EnumRegularization eRegularization) const
computes the error of the DNN
double forward_backward(LayerContainer &layers, PassThrough &settingsAndBatch, ItWeight itWeightBegin, ItWeight itWeightEnd, ItGradient itGradientBegin, ItGradient itGradientEnd, size_t trainFromLayer, OutContainer &outputContainer, bool fetchOutput) const
main NN computation function
void removeLayer()
remove one layer
Definition NeuralNet.h:1246
size_t m_sizeOutput
output size of this DNN
Definition NeuralNet.h:1269
size_t m_sizeInput
input size of this DNN
Definition NeuralNet.h:1268
double trainCycle(Minimizer &minimizer, std::vector< double > &weights, Iterator itPatternBegin, Iterator itPatternEnd, Settings &settings, DropContainer &dropContainer)
executes one training cycle
double operator()(PassThrough &settingsAndBatch, const Weights &weights) const
execute computation of the DNN for one mini-batch (used by the minimizer); no computation of gradient...
void dropOutWeightFactor(WeightsType &weights, const DropProbabilities &drops, bool inverse=false)
set the drop out configuration
void fillDropContainer(DropContainer &dropContainer, double dropFraction, size_t numNodes) const
prepare the drop-out-container (select the nodes which are to be dropped out)
void addLayer(Layer &layer)
add a layer (layout)
Definition NeuralNet.h:1092
size_t numWeights(size_t trainingStartLayer=0) const
returns the number of weights in this net
std::tuple< double, double > computeError(const Settings &settings, std::vector< LayerData > &lastLayerData, Batch &batch, ItWeight itWeightBegin, ItWeight itWeightEnd) const
void setOutputSize(size_t sizeOutput)
set the output size of the DNN
Definition NeuralNet.h:1091
void forwardPattern(const LayerContainer &_layers, std::vector< LayerData > &layerData) const
void backPropagate(std::vector< std::vector< LayerData > > &layerPatternData, const Settings &settings, size_t trainFromLayer, size_t totalNumWeights) const
Settings for the training of the neural net.
Definition NeuralNet.h:728
size_t m_batchSize
mini-batch size
Definition NeuralNet.h:836
void setDropOut(Iterator begin, Iterator end, size_t _dropRepetitions)
set the drop-out configuration (layer-wise)
Definition NeuralNet.h:757
void create(std::string histoName, int bins, double min, double max, int bins2, double min2, double max2)
for monitoring
Definition NeuralNet.h:818
bool useMultithreading() const
is multithreading turned on?
Definition NeuralNet.h:813
EnumRegularization regularization() const
some regularization of the DNN is turned on?
Definition NeuralNet.h:811
size_t convergenceCount() const
returns the current convergence count
Definition NeuralNet.h:825
double momentum() const
get the momentum (e.g. for SGD)
Definition NeuralNet.h:770
Timer m_timer
timer for monitoring
Definition NeuralNet.h:830
size_t testRepetitions() const
how often is the test data tested
Definition NeuralNet.h:766
void clear(std::string histoName)
for monitoring
Definition NeuralNet.h:822
virtual void endTestCycle()
callback for monitoring and loggging
Definition NeuralNet.h:803
MinimizerType fMinimizerType
Definition NeuralNet.h:853
void addPoint(std::string histoName, double x, double y)
for monitoring
Definition NeuralNet.h:820
void setMonitoring(std::shared_ptr< Monitoring > ptrMonitoring)
prepared for monitoring
Definition NeuralNet.h:762
virtual void testIteration()
callback for monitoring and loggging
Definition NeuralNet.h:804
size_t m_convergenceSteps
number of steps without improvement to consider the DNN to have converged
Definition NeuralNet.h:835
virtual bool hasConverged(double testError)
has this training converged already?
MinimizerType minimizerType() const
which minimizer shall be used (e.g. SGD)
Definition NeuralNet.h:772
std::vector< double > m_dropOut
Definition NeuralNet.h:848
double m_minProgress
current limits for the progress bar
Definition NeuralNet.h:831
virtual void cycle(double progress, TString text)
Definition NeuralNet.h:797
Settings(TString name, size_t _convergenceSteps=15, size_t _batchSize=10, size_t _testRepetitions=7, double _factorWeightDecay=1e-5, TMVA::DNN::EnumRegularization _regularization=TMVA::DNN::EnumRegularization::NONE, MinimizerType _eMinimizerType=MinimizerType::fSteepest, double _learningRate=1e-5, double _momentum=0.3, int _repetitions=3, bool _multithreading=true)
c'tor
virtual void setProgressLimits(double minProgress=0, double maxProgress=100)
Definition NeuralNet.h:788
double m_maxProgress
current limits for the progress bar
Definition NeuralNet.h:832
virtual void endTrainCycle(double)
callback for monitoring and logging
Definition NeuralNet.h:786
virtual void drawSample(const std::vector< double > &, const std::vector< double > &, const std::vector< double > &, double)
callback for monitoring and logging
Definition NeuralNet.h:805
double learningRate() const
get the learning rate
Definition NeuralNet.h:769
const std::vector< double > & dropFractions() const
Definition NeuralNet.h:760
void addPoint(std::string histoName, double x)
for monitoring
Definition NeuralNet.h:819
virtual ~Settings()
d'tor
size_t m_convergenceCount
Definition NeuralNet.h:855
EnumRegularization m_regularization
Definition NeuralNet.h:845
int repetitions() const
how many steps have to be gone until the batch is changed
Definition NeuralNet.h:771
virtual void testSample(double, double, double, double)
virtual function to be used for monitoring (callback)
Definition NeuralNet.h:779
void plot(std::string histoName, std::string options, int pad, EColor color)
for monitoring
Definition NeuralNet.h:821
virtual void startTrainCycle()
Definition NeuralNet.h:780
size_t convergenceSteps() const
how many steps until training is deemed to have converged
Definition NeuralNet.h:764
double m_factorWeightDecay
Definition NeuralNet.h:838
double factorWeightDecay() const
get the weight-decay factor
Definition NeuralNet.h:767
bool exists(std::string histoName)
for monitoring
Definition NeuralNet.h:823
size_t maxConvergenceCount() const
returns the max convergence count so far
Definition NeuralNet.h:826
void pads(int numPads)
preparation for monitoring
Definition NeuralNet.h:816
size_t batchSize() const
mini-batch size
Definition NeuralNet.h:765
virtual void computeResult(const Net &, std::vector< double > &)
callback for monitoring and logging
Definition NeuralNet.h:807
std::shared_ptr< Monitoring > fMonitoring
Definition NeuralNet.h:863
size_t dropRepetitions() const
Definition NeuralNet.h:759
void create(std::string histoName, int bins, double min, double max)
for monitoring
Definition NeuralNet.h:817
size_t minError() const
returns the smallest error so far
Definition NeuralNet.h:827
virtual void startTraining()
Definition NeuralNet.h:793
size_t m_maxConvergenceCount
Definition NeuralNet.h:856
virtual void startTestCycle()
callback for monitoring and loggging
Definition NeuralNet.h:802
Steepest Gradient Descent algorithm (SGD)
Definition NeuralNet.h:332
double m_beta
internal parameter (momentum)
Definition NeuralNet.h:370
std::vector< double > m_localGradients
local gradients for reuse in thread.
Definition NeuralNet.h:374
std::vector< double > m_prevGradients
vector remembers the gradients of the previous step
Definition NeuralNet.h:371
double m_alpha
internal parameter (learningRate)
Definition NeuralNet.h:369
std::vector< double > m_localWeights
local weights for reuse in thread.
Definition NeuralNet.h:373
double operator()(Function &fitnessFunction, Weights &weights, PassThrough &passThrough)
operator to call the steepest gradient descent algorithm
Steepest(double learningRate=1e-4, double momentum=0.5, size_t repetitions=10)
c'tor
Definition NeuralNet.h:346
Timing information for training and evaluation of MVA methods.
Definition Timer.h:58
void DrawProgressBar(Int_t, const TString &comment="")
draws progress bar in color or B&W caution:
Definition Timer.cxx:201
Basic string class.
Definition TString.h:138
const Double_t sigma
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
double sumOfSquares(ItOutput itOutputBegin, ItOutput itOutputEnd, ItTruth itTruthBegin, ItTruth itTruthEnd, ItDelta itDelta, ItDelta itDeltaEnd, ItInvActFnc itInvActFnc, double patternWeight)
double uniformDouble(double minValue, double maxValue)
Definition NeuralNet.cxx:43
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
void applyFunctions(ItValue itValue, ItValue itValueEnd, ItFunction itFunction)
ModeOutputValues operator|(ModeOutputValues lhs, ModeOutputValues rhs)
Definition NeuralNet.h:186
double crossEntropy(ItProbability itProbabilityBegin, ItProbability itProbabilityEnd, ItTruth itTruthBegin, ItTruth itTruthEnd, ItDelta itDelta, ItDelta itDeltaEnd, ItInvActFnc itInvActFnc, double patternWeight)
cross entropy error function
void backward(LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
backward application of the weights (back-propagation of the error)
double weightDecay(double error, ItWeight itWeight, ItWeight itWeightEnd, double factorWeightDecay, EnumRegularization eRegularization)
compute the weight decay for regularization (L1 or L2)
ModeOutputValues operator&=(ModeOutputValues &lhs, ModeOutputValues rhs)
Definition NeuralNet.h:202
auto regularization(const typename Architecture_t::Matrix_t &A, ERegularization R) -> decltype(Architecture_t::L1Regularization(A))
Evaluate the regularization functional for a given weight matrix.
Definition Functions.h:238
ModeErrorFunction
error functions to be chosen from
Definition NeuralNet.h:1037
double softMaxCrossEntropy(ItOutput itProbabilityBegin, ItOutput itProbabilityEnd, ItTruth itTruthBegin, ItTruth itTruthEnd, ItDelta itDelta, ItDelta itDeltaEnd, ItInvActFnc itInvActFnc, double patternWeight)
soft-max-cross-entropy error function (for mutual exclusive cross-entropy)
WeightInitializationStrategy
weight initialization strategies to be chosen from
Definition NeuralNet.h:1048
ModeOutputValues operator|=(ModeOutputValues &lhs, ModeOutputValues rhs)
Definition NeuralNet.h:191
MinimizerType
< list all the minimizer types
Definition NeuralNet.h:319
@ fSteepest
SGD.
Definition NeuralNet.h:320
double gaussDouble(double mean, double sigma)
Definition NeuralNet.cxx:35
ModeOutputValues operator&(ModeOutputValues lhs, ModeOutputValues rhs)
Definition NeuralNet.h:197
void applyWeights(ItSource itSourceBegin, ItSource itSourceEnd, ItWeight itWeight, ItTarget itTargetBegin, ItTarget itTargetEnd)
std::tuple< Settings &, Batch &, DropContainer & > pass_through_type
Definition NeuralNet.h:1276
bool isFlagSet(T flag, T value)
Definition NeuralNet.h:210
int randomInt(int maxValue)
Definition NeuralNet.cxx:52
void update(ItSource itSource, ItSource itSourceEnd, ItDelta itTargetDeltaBegin, ItDelta itTargetDeltaEnd, ItTargetGradient itTargetGradientBegin, ItGradient itGradient)
update the gradients
std::vector< char > DropContainer
Definition NeuralNet.h:225
void applyWeightsBackwards(ItSource itCurrBegin, ItSource itCurrEnd, ItWeight itWeight, ItPrev itPrevBegin, ItPrev itPrevEnd)
create variable transformations