fullyconnected.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. ///////////////////////////////////////////////////////////////////////
  2. // File: fullyconnected.h
  3. // Description: Simple feed-forward layer with various non-linearities.
  4. // Author: Ray Smith
  5. // Created: Wed Feb 26 14:46:06 PST 2014
  6. //
  7. // (C) Copyright 2014, Google Inc.
  8. // Licensed under the Apache License, Version 2.0 (the "License");
  9. // you may not use this file except in compliance with the License.
  10. // You may obtain a copy of the License at
  11. // http://www.apache.org/licenses/LICENSE-2.0
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. ///////////////////////////////////////////////////////////////////////
  18. #ifndef TESSERACT_LSTM_FULLYCONNECTED_H_
  19. #define TESSERACT_LSTM_FULLYCONNECTED_H_
  20. #include "network.h"
  21. #include "networkscratch.h"
  22. namespace tesseract {
  23. // C++ Implementation of the Softmax (output) class from lstm.py.
  24. class FullyConnected : public Network {
  25. public:
  26. FullyConnected(const STRING& name, int ni, int no, NetworkType type);
  27. ~FullyConnected() override = default;
  28. // Returns the shape output from the network given an input shape (which may
  29. // be partially unknown ie zero).
  30. StaticShape OutputShape(const StaticShape& input_shape) const override;
  31. STRING spec() const override {
  32. STRING spec;
  33. if (type_ == NT_TANH)
  34. spec.add_str_int("Ft", no_);
  35. else if (type_ == NT_LOGISTIC)
  36. spec.add_str_int("Fs", no_);
  37. else if (type_ == NT_RELU)
  38. spec.add_str_int("Fr", no_);
  39. else if (type_ == NT_LINEAR)
  40. spec.add_str_int("Fl", no_);
  41. else if (type_ == NT_POSCLIP)
  42. spec.add_str_int("Fp", no_);
  43. else if (type_ == NT_SYMCLIP)
  44. spec.add_str_int("Fs", no_);
  45. else if (type_ == NT_SOFTMAX)
  46. spec.add_str_int("Fc", no_);
  47. else
  48. spec.add_str_int("Fm", no_);
  49. return spec;
  50. }
  51. // Changes the type to the given type. Used to commute a softmax to a
  52. // non-output type for adding on other networks.
  53. void ChangeType(NetworkType type) {
  54. type_ = type;
  55. }
  56. // Suspends/Enables training by setting the training_ flag. Serialize and
  57. // DeSerialize only operate on the run-time data if state is false.
  58. void SetEnableTraining(TrainingState state) override;
  59. // Sets up the network for training. Initializes weights using weights of
  60. // scale `range` picked according to the random number generator `randomizer`.
  61. int InitWeights(float range, TRand* randomizer) override;
  62. // Recursively searches the network for softmaxes with old_no outputs,
  63. // and remaps their outputs according to code_map. See network.h for details.
  64. int RemapOutputs(int old_no, const std::vector<int>& code_map) override;
  65. // Converts a float network to an int network.
  66. void ConvertToInt() override;
  67. // Provides debug output on the weights.
  68. void DebugWeights() override;
  69. // Writes to the given file. Returns false in case of error.
  70. bool Serialize(TFile* fp) const override;
  71. // Reads from the given file. Returns false in case of error.
  72. bool DeSerialize(TFile* fp) override;
  73. // Runs forward propagation of activations on the input line.
  74. // See Network for a detailed discussion of the arguments.
  75. void Forward(bool debug, const NetworkIO& input,
  76. const TransposedArray* input_transpose, NetworkScratch* scratch,
  77. NetworkIO* output) override;
  78. // Components of Forward so FullyConnected can be reused inside LSTM.
  79. void SetupForward(const NetworkIO& input,
  80. const TransposedArray* input_transpose);
  81. void ForwardTimeStep(int t, double* output_line);
  82. void ForwardTimeStep(const double* d_input, int t, double* output_line);
  83. void ForwardTimeStep(const int8_t* i_input, int t, double* output_line);
  84. // Runs backward propagation of errors on the deltas line.
  85. // See Network for a detailed discussion of the arguments.
  86. bool Backward(bool debug, const NetworkIO& fwd_deltas,
  87. NetworkScratch* scratch, NetworkIO* back_deltas) override;
  88. // Components of Backward so FullyConnected can be reused inside LSTM.
  89. void BackwardTimeStep(const NetworkIO& fwd_deltas, int t, double* curr_errors,
  90. TransposedArray* errors_t, double* backprop);
  91. void FinishBackward(const TransposedArray& errors_t);
  92. // Updates the weights using the given learning rate, momentum and adam_beta.
  93. // num_samples is used in the adam computation iff use_adam_ is true.
  94. void Update(float learning_rate, float momentum, float adam_beta,
  95. int num_samples) override;
  96. // Sums the products of weight updates in *this and other, splitting into
  97. // positive (same direction) in *same and negative (different direction) in
  98. // *changed.
  99. void CountAlternators(const Network& other, double* same,
  100. double* changed) const override;
  101. protected:
  102. // Weight arrays of size [no, ni + 1].
  103. WeightMatrix weights_;
  104. // Transposed copy of input used during training of size [ni, width].
  105. TransposedArray source_t_;
  106. // Pointer to transposed input stored elsewhere. If not null, this is used
  107. // in preference to calculating the transpose and storing it in source_t_.
  108. const TransposedArray* external_source_;
  109. // Activations from forward pass of size [width, no].
  110. NetworkIO acts_;
  111. // Memory of the integer mode input to forward as softmax always outputs
  112. // float, so the information is otherwise lost.
  113. bool int_mode_;
  114. };
  115. } // namespace tesseract.
  116. #endif // TESSERACT_LSTM_FULLYCONNECTED_H_