activation.hpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #ifndef ACTIVATION_LAYER_HPP
  2. #define ACTIVATION_LAYER_HPP
  3. #include "layer.hpp"
  4. #include "math.hpp"
  5. namespace Layer{
  6. /** Enumeration type for the different implemented actiovation map */
  7. enum ActivationMap{
  8. Sigmoid /**< \f$x\mapsto \frac{1}{1+e^{-x}}\f$ */
  9. };
  10. /** Activation map.*/
  11. template<ActivationMap A> Real activation_map(Real);
  12. /** Derivative of activation map.*/
  13. template<ActivationMap A> Real activation_diff_map(Real);
  14. /**
  15. * Class for activation layer.
  16. * The Output vector is obtained by applying activation map to each entry of the input vector.
  17. */
  18. template<ActivationMap A> class ActivationLayer:public Layer{
  19. public:
  20. ActivationLayer(const size_t);
  21. ~ActivationLayer(){};
  22. /** \f$y[i]:=\alpha(x[i])\f$ where \f$\alpha\f$ is the activation map.*/
  23. Vector feed_forward(Vector x) override;
  24. /**Null.*/
  25. void init_nabla() override {};
  26. /** \f$d[i]:=\alpha'(x[i])\times \e[i]\f$ where \f$\alpha\f$ is the activation map and $e$ the difference output vector.*/
  27. Vector back_propagation(Vector e) override;
  28. /**Null.*/
  29. void update(Real eta) override{};
  30. };
  31. template<ActivationMap A>
  32. inline
  33. ActivationLayer<A>::ActivationLayer(size_t n):Layer(n,n){
  34. }
  35. template<ActivationMap A>
  36. inline Vector
  37. ActivationLayer<A>::feed_forward(Vector x_){
  38. x=x_;
  39. for(size_t i=0;i<n;++i){
  40. y[i]=activation_map<A>(x[i]);
  41. }
  42. return y;
  43. }
  44. template<ActivationMap A>
  45. inline Vector
  46. ActivationLayer<A>::back_propagation(Vector e){
  47. for(size_t i=0;i<n;++i){
  48. d[i]=activation_diff_map<A>(x[i])*e[i];
  49. }
  50. return d;
  51. }
  52. template<>
  53. inline Real
  54. activation_map<Sigmoid>(Real x){
  55. return 1.0/(1.0+exp(-x));
  56. }
  57. template<>
  58. inline Real
  59. activation_diff_map<Sigmoid>(Real x){
  60. Real t=activation_map<Sigmoid>(x);
  61. return t*(1.0-t);
  62. }
  63. }
  64. #endif