activation.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle.nn as nn
  15. class Activation(nn.Layer):
  16. """
  17. The wrapper of activations.
  18. Args:
  19. act (str, optional): The activation name in lowercase. It must be one of ['elu', 'gelu',
  20. 'hardshrink', 'tanh', 'hardtanh', 'prelu', 'relu', 'relu6', 'selu', 'leakyrelu', 'sigmoid',
  21. 'softmax', 'softplus', 'softshrink', 'softsign', 'tanhshrink', 'logsigmoid', 'logsoftmax',
  22. 'hsigmoid']. Default: None, means identical transformation.
  23. Returns:
  24. A callable object of Activation.
  25. Raises:
  26. KeyError: When parameter `act` is not in the optional range.
  27. Examples:
  28. from paddlex.paddleseg.models.common.activation import Activation
  29. relu = Activation("relu")
  30. print(relu)
  31. # <class 'paddle.nn.layer.activation.ReLU'>
  32. sigmoid = Activation("sigmoid")
  33. print(sigmoid)
  34. # <class 'paddle.nn.layer.activation.Sigmoid'>
  35. not_exit_one = Activation("not_exit_one")
  36. # KeyError: "not_exit_one does not exist in the current dict_keys(['elu', 'gelu', 'hardshrink',
  37. # 'tanh', 'hardtanh', 'prelu', 'relu', 'relu6', 'selu', 'leakyrelu', 'sigmoid', 'softmax',
  38. # 'softplus', 'softshrink', 'softsign', 'tanhshrink', 'logsigmoid', 'logsoftmax', 'hsigmoid'])"
  39. """
  40. def __init__(self, act=None):
  41. super(Activation, self).__init__()
  42. self._act = act
  43. upper_act_names = nn.layer.activation.__dict__.keys()
  44. lower_act_names = [act.lower() for act in upper_act_names]
  45. act_dict = dict(zip(lower_act_names, upper_act_names))
  46. if act is not None:
  47. if act in act_dict.keys():
  48. act_name = act_dict[act]
  49. self.act_func = eval("nn.layer.activation.{}()".format(
  50. act_name))
  51. else:
  52. raise KeyError("{} does not exist in the current {}".format(
  53. act, act_dict.keys()))
  54. def forward(self, x):
  55. if self._act is not None:
  56. return self.act_func(x)
  57. else:
  58. return x