ActivationFunctor.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (C) 2017 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef ANDROID_ML_NN_ACTIVATION_FUNCTOR_H
  17. #define ANDROID_ML_NN_ACTIVATION_FUNCTOR_H
  18. #include "android/log.h"
  19. #include <algorithm>
  20. #include <cmath>
  21. enum ActivationFn {
  22. kActivationNone = 0,
  23. kActivationRelu,
  24. kActivationRelu1,
  25. kActivationRelu6,
  26. kActivationTanh,
  27. kActivationSignBit,
  28. kActivationSigmoid,
  29. };
  30. class ActivationFunctor {
  31. public:
  32. explicit ActivationFunctor(ActivationFn act) : act_(act) {}
  33. float operator()(float a) const {
  34. switch (act_) {
  35. case kActivationNone:
  36. return a;
  37. case kActivationRelu:
  38. return a < 0.f ? 0.f : a;
  39. case kActivationRelu6:
  40. return std::max(0.f, std::min(a, 6.f));
  41. case kActivationTanh:
  42. return std::tanh(a);
  43. case kActivationSigmoid:
  44. return 1.0f / (1.0f + std::exp(-a));
  45. default:
  46. __android_log_print(ANDROID_LOG_ERROR, "NN API",
  47. "Invalid enum value for activation function: 0x%0X",
  48. act_);
  49. abort();
  50. }
  51. }
  52. private:
  53. ActivationFn act_;
  54. };
  55. #endif // ANDROID_ML_NN_ACTIVATION_FUNCTOR_H