Home | History | Annotate | Download | only in include
      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 
     17 #ifndef ANDROID_ML_NN_ACTIVATION_FUNCTOR_H
     18 #define ANDROID_ML_NN_ACTIVATION_FUNCTOR_H
     19 
     20 #include "android/log.h"
     21 
     22 #include <algorithm>
     23 #include <cmath>
     24 
     25 enum ActivationFn {
     26     kActivationNone = 0,
     27     kActivationRelu,
     28     kActivationRelu1,
     29     kActivationRelu6,
     30     kActivationTanh,
     31     kActivationSignBit,
     32     kActivationSigmoid,
     33 };
     34 
     35 class ActivationFunctor {
     36  public:
     37   explicit ActivationFunctor(ActivationFn act) : act_(act) {}
     38 
     39   float operator()(float a) const {
     40     switch (act_) {
     41       case kActivationNone:
     42         return a;
     43       case kActivationRelu:
     44         return a < 0.f ? 0.f : a;
     45       case kActivationRelu6:
     46         return std::max(0.f, std::min(a, 6.f));
     47       case kActivationTanh:
     48         return std::tanh(a);
     49       case kActivationSigmoid:
     50         return 1.0f / (1.0f + std::exp(-a));
     51       default:
     52         __android_log_print(ANDROID_LOG_ERROR, "NN API",
     53                             "Invalid enum value for activation function: 0x%0X",
     54                             act_);
     55         abort();
     56     }
     57   }
     58 
     59  private:
     60   ActivationFn act_;
     61 };
     62 
     63 #endif  // ANDROID_ML_NN_ACTIVATION_FUNCTOR_H
     64