home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 618a.lha / NeuralNetwork / neural_network.h < prev    next >
C/C++ Source or Header  |  1992-03-02  |  16KB  |  321 lines

  1.  
  2. #ifndef _NEURAL_NETWORK_H_
  3. #define _NEURAL_NETWORK_H_
  4.  
  5. #define SLOPE    1.0
  6. #define S(x)    (1.0 / (1.0 + exp (0.0 - SLOPE*(x))))
  7.  
  8. #define WRONG    0
  9. #define GOOD     1
  10. #define CORRECT  2
  11.  
  12.  
  13. //****************************************************************************
  14. //
  15. // Neural_network class:
  16. //
  17. //      This class performs all the necessary functions needed to train
  18. //      a Neural Network.  The network has an input layer, two hidden
  19. //      layers, and an output layer.  The size of each layer is specified
  20. //      a run time so there is no restriction on size except memory.
  21. //      This is a feed-forward network with full connctions from one
  22. //      layer to the next.
  23. //
  24. //      The network can perform straight back-propagation with no
  25. //      modifications (Rumelhart, Hinton, and Williams, 1985) which
  26. //      will find a solution but not very quickly.  The network can also
  27. //      perform back-propagation with the delta-bar-delta rule developed
  28. //      by Robert A. Jacobs, University of Massachusetts
  29. //      (Neural Networks, Vol 1. pp.295-307, 1988).  The basic idea of this
  30. //      rule is that every weight has its own learning rate and each
  31. //      learning rate should be continously changed according to the
  32. //      following rules -
  33. //      - If the weight changes in the same direction as the previous update,
  34. //        then the learning rate for that weight should increase by a constant.
  35. //      - If the weight changes in the opposite direction as the previous
  36. //        update, then the learning rate for that weight should decrease
  37. //        exponentially.
  38. //
  39. //      learning rate = e(t) for each individual weight
  40. //      The exact formula for the change in learning rate (DELTA e(t)) is
  41. //
  42. //
  43. //                   | K          if DELTA_BAR(t-1)*DELTA(t) > 0
  44. //      DELTA e(t) = | -PHI*e(t)  if DELTA_BAR(t-1)*DELTA(t) < 0
  45. //                   | 0          otherwise
  46. //
  47. //      where DELTA(t) = dJ(t) / dw(t) ---> Partial derivative
  48. //
  49. //      and DELTA_BAR(t) = (1 - THETA)*DELTA(t) + THETA*DELTA_BAR(t-1).
  50. //
  51. //      For full details of the algorithm, read the article in
  52. //      Neural Networks.
  53. //
  54. //
  55. //      To perform straight back-propagation, just construct a Neural_network
  56. //      with no learning parameters specified (they default to straight
  57. //      back-propagation) or set them to
  58. //      K = 0, PHI = 0, THETA = 1.0
  59. //
  60. //      However, using the delta-bar-delta rule should increase your rate of
  61. //      convergence by a factor of 10 to 100 generally.  The parameters for
  62. //      the delta-bar-delta rule I use are
  63. //      K = 0.025, PHI = 0.2, THETA = 0.8
  64. //
  65. //      One more heuristic method has been employed in this Neural net class-
  66. //      the skip heuristic.  This is something I thought of and I am sure
  67. //      other people have also.  If the output activation is within
  68. //      skip_epsilon of its desired for each output, then the calc_forward
  69. //      routine returns the skip_flag = 1.  This allows you to not waste
  70. //      time trying to push already very close examples to the exact value.
  71. //      If the skip_flag comes back '1', then don't bother calculating forward
  72. //      or back-propagating the example for X number of epochs.  You must
  73. //      write the routine to skip the example yourself, but the Neural_network
  74. //      will tell you when to skip the example.  This heuristic also has the
  75. //      advantage of reducing memorization and increases generalization.
  76. //      Typical values I use for this heuristic -
  77. //      skip_epsilon = 0.01 - 0.05
  78. //      number skipped = 2-10.
  79. //
  80. //      Experiment with all the values to see which work best for your
  81. //      application.
  82. //
  83. //
  84. //      Comments and suggestions are welcome and can be emailed to me
  85. //      anstey@sun.soe.clarkson.edu
  86. //
  87. //****************************************************************************
  88.  
  89.  
  90.  
  91.  
  92.  
  93. class Neural_network {
  94. private:
  95.   //  We need
  96.   //
  97.   //  Matrix for hidden layer 1 activation [num_hidden1]
  98.   //  Matrix for hidden layer 2 activation [num_hidden2]
  99.   //  Matrix for output layer activation [num_outputs]
  100.   //
  101.   //  Matrix for input to first hidden layer weights [num_inputs] [num_hidden1]
  102.   //  Matrix for hidden layer 1 to hidden layer 2 weights [hidden1] [hidden2]
  103.   //  Matrix for hidden layer 2 to output layer weights [hidden2] [outputs]
  104.  
  105.   //  3 Matrices for sum of all the deltas in an epoch - Back propagation
  106.   //  2 Matrices for sum of deltas * weight for each neuron in hidden layers
  107.   //    1 and 2 for backpropagation - Back propagation
  108.   //
  109.   //  3 Matrices for each weight's learning rate - delta-bar-delta rule
  110.   //  3 Matrices for each weight's learning delta - delta-bar-delta rule
  111.   //  3 Matrices for each weight's learning delta_bar - delta-bar-delta rule
  112.  
  113.   int     num_inputs;
  114.   int     num_hidden1;
  115.   int     num_hidden2;
  116.   int     num_outputs;
  117.  
  118.   double  epsilon;
  119.   double  skip_epsilon;
  120.   double  learning_rate;
  121.   double  theta;
  122.   double  phi;
  123.   double  K;
  124.   long    training_examples;
  125.   long    examples_since_update;
  126.  
  127.   double  *hidden1_act;
  128.   double  *hidden2_act;
  129.   double  *output_act;
  130.  
  131.   double  *input_weights;
  132.   double  *hidden1_weights;
  133.   double  *hidden2_weights;
  134.  
  135.   double  *input_learning_rate;
  136.   double  *hidden1_learning_rate;
  137.   double  *hidden2_learning_rate;
  138.  
  139.   double  *input_learning_delta;
  140.   double  *hidden1_learning_delta;
  141.   double  *hidden2_learning_delta;
  142.  
  143.   double  *input_learning_delta_bar;
  144.   double  *hidden1_learning_delta_bar;
  145.   double  *hidden2_learning_delta_bar;
  146.  
  147.   double  *input_weights_sum_delta;
  148.   double  *hidden1_weights_sum_delta;
  149.   double  *hidden2_weights_sum_delta;
  150.  
  151.   double  *hidden1_sum_delta_weight;
  152.   double  *hidden2_sum_delta_weight;
  153.  
  154.   void    allocate_matrices ();
  155.   void    initialize_matrices (double range);
  156.   void    deallocate_matrices ();
  157.  
  158. public:
  159.  
  160.   //***********************************************************************
  161.   // Constructors :                                                       *
  162.   //    Full size specifications and learning parameters.                 *
  163.   //         Learning parameters are provided defaults which are set to   *
  164.   //         just use the BP algorithm with no modifications.             *
  165.   //                                                                      *
  166.   //    Read constructor which reads in the size and all the weights from *
  167.   //         a file.  The network is resized to match the size specified  *
  168.   //         by the file.  Learning parameters must be specified          *
  169.   //         separately.                                                  *
  170.   //***********************************************************************
  171.  
  172.   Neural_network (int number_inputs = 1, int number_hidden1 = 1,
  173.                   int number_hidden2 = 1,
  174.                   int number_outputs = 1, double t_epsilon = 0.1,
  175.                   double t_skip_epsilon = 0.0, double t_learning_rate = 0.1,
  176.                   double t_theta = 1.0, double t_phi = 0.0, double t_K = 0.0,
  177.                   double range = 3.0);
  178.   Neural_network (char *filename, int& file_error, double t_epsilon = 0.1,
  179.                   double t_skip_epsilon = 0.0, double t_learning_rate = 0.1,
  180.                   double t_theta = 1.0, double t_phi = 0.0, double t_K = 0.0);
  181.   ~Neural_network () { deallocate_matrices ();};
  182.  
  183.  
  184.   //**************************************************************************
  185.   // Weight parameter routines:                                              *
  186.   //     save_weights : This routine saves the weights of the network        *
  187.   //          to the file <filename>.                                        *
  188.   //                                                                         *
  189.   //     read_weights : This routine reads the weight values from the file   *
  190.   //          <filename>.  The network is automatically resized to the       *
  191.   //          size specified by the file.                                    *
  192.   //                                                                         *
  193.   //     Activation routines return the node activation after a calc_forward *
  194.   //          has been performed.                                            *
  195.   //                                                                         *
  196.   //     get_weight routines return the weight between node1 and node2.      *
  197.   //                                                                         *
  198.   //**************************************************************************
  199.  
  200.   int    save_weights (char *filename);
  201.   int    read_weights (char *filename);
  202.  
  203.   double get_hidden1_activation (int node) { return (hidden1_act [node]); };
  204.   double get_hidden2_activation (int node) { return (hidden2_act [node]); };
  205.   double get_output_activation (int node) { return (output_act [node]); };
  206.  
  207.   double get_input_weight (int input_node, int hidden1_node) {
  208.          return (input_weights [hidden1_node * num_inputs + input_node]);};
  209.   double get_hidden1_weight (int hidden1_node, int hidden2_node) {
  210.          return (hidden1_weights [hidden2_node * num_hidden1 + hidden1_node]);};
  211.   double get_hidden2_weight (int hidden2_node, int output_node) {
  212.          return (hidden2_weights [output_node * num_hidden2 + hidden2_node]);};
  213.  
  214.  
  215.   //*******************************************************************
  216.   // Size parameters of network.                                      *
  217.   // The size of the network may be changed at any time.  The weights *
  218.   // will be copied from the old size to the new size.  If the new    *
  219.   // size is larger, then the extra weights will be randomly set      *
  220.   // between +-range.  The matrices used to hold learning updates     *
  221.   // and activations will be re-initialized (cleared).                *
  222.   //*******************************************************************
  223.  
  224.   int get_number_of_inputs () { return (num_inputs); };
  225.   int get_number_of_hidden1 () { return (num_hidden1); };
  226.   int get_number_of_hidden2 () { return (num_hidden2); };
  227.   int get_number_of_outputs () { return (num_outputs); };
  228.   void set_size_parameters (int number_inputs, int number_hidden1,
  229.                             int number_hidden2, int number_outputs,
  230.                             double range = 3.0);
  231.  
  232.  
  233.   //*******************************************************************
  234.   // Learning parameters functions.  These parameters may be changed  *
  235.   // on the fly.  The learning rate and K may have to be reduced as   *
  236.   // more and more training is done to prevent oscillations.          *
  237.   //*******************************************************************
  238.  
  239.   void set_epsilon (double eps) { epsilon = eps; };
  240.   void set_skip_epsilon (double eps) { skip_epsilon = eps; };
  241.   void set_learning_rate (double l_rate) { learning_rate = l_rate; };
  242.   void set_theta (double t_theta) { theta = t_theta; };
  243.   void set_phi (double t_phi) { phi = t_phi; };
  244.   void set_K (double t_K) { K = t_K; };
  245.  
  246.   double get_epsilon () { return (epsilon); };
  247.   double get_skip_epsilon () { return (skip_epsilon); };
  248.   double get_learning_rate () { return (learning_rate); };
  249.   double get_theta () { return (theta); };
  250.   double get_phi () { return (phi); };
  251.   double get_K () { return (K); };
  252.   long   get_iterations () { return (training_examples); };
  253.  
  254.  
  255.   //**************************************************************************
  256.   // The main neural network routines:                                       *
  257.   //                                                                         *
  258.   //      The network input is an array of doubles which has a size of       *
  259.   //           number_inputs.                                                *
  260.   //      The network desired output is an array of doubles which has a size *
  261.   //           of number_outputs.                                            *
  262.   //                                                                         *
  263.   //      back_propagation : Calculates how each weight should be changed.   *
  264.   //           Assumes that calc_forward has been called just prior to       *
  265.   //           this routine to calculate all of the node activations.        *
  266.   //                                                                         *
  267.   //      calc_forward : Calculates the output for a given input.  Finds     *
  268.   //           all node activations which are needed for back_propagation    *
  269.   //           to calculate weight adjustment.  Returns abs (error).         *
  270.   //           The parameter skip is for use with the skip_epsilon           *
  271.   //           parameter.  What it means is if the output is within          *
  272.   //           skip_epsilon of the desired, then it is so close that it      *
  273.   //           should be skipped from being calculated the next X times.     *
  274.   //           Careful use of this parameter can significantly increase      *
  275.   //           the rate of convergence and also help prevent over-learning.  *
  276.   //                                                                         *
  277.   //      calc_forward_test : Calculates the output for a given input.  This *
  278.   //           routine is used for testing rather than training.  It returns *
  279.   //           whether the test was CORRECT, GOOD or WRONG which is          *
  280.   //           determined by the parameters correct_epsilon and              *
  281.   //           good_epsilon.  CORRECT > GOOD > WRONG.                        *
  282.   //                                                                         *
  283.   //      update_weights : Actually adjusts all the weights according to     *
  284.   //           the calculations of back_propagation.  This routine should    *
  285.   //           be called at the end of every training epoch.  The weights    *
  286.   //           can be updated by the straight BP algorithm, or by the        *
  287.   //           delta-bar-delta algorithm developed by Robert A. Jacobs       *
  288.   //           which increases the rate of convergence generally by at       *
  289.   //           least a factor of 10.  The parameters THETA, PHI, and K       *
  290.   //           determine which algorithm is used.  The default settings      *
  291.   //           for these parameters cause update_weights to use the straight *
  292.   //           BP algorithm.                                                 *
  293.   //                                                                         *
  294.   //      kick_weights : This routine changes all weights by a random amount *
  295.   //           within +-range.  It is useful in case the network gets        *
  296.   //           'stuck' and is having trouble converging to a solution.  I    *
  297.   //           use it when the number wrong has not changed for the last 200 *
  298.   //           epochs.  Getting the range right will take some trial and     *
  299.   //           error as it depends on the application and the weights'       *
  300.   //           actual values.                                                *
  301.   //                                                                         *
  302.   //**************************************************************************
  303.  
  304.   void back_propagation (double input [], double desired_output [],
  305.                          int& done);
  306.  
  307.   double calc_forward (double input [], double desired_output [],
  308.                        int& num_wrong, int& skip, int print_it,
  309.                        int& actual_printed);
  310.  
  311.   int calc_forward_test (double input [], double desired_output [],
  312.                          int print_it, double correct_eps, double good_eps);
  313.  
  314.   void update_weights ();
  315.  
  316.   void kick_weights (double range);
  317.  
  318. };
  319.  
  320. #endif
  321.