cls_head.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import math
  18. import paddle
  19. from paddle import nn, ParamAttr
  20. import paddle.nn.functional as F
  21. class ClsHead(nn.Layer):
  22. """
  23. Class orientation
  24. Args:
  25. params(dict): super parameters for build Class network
  26. """
  27. def __init__(self, in_channels, class_dim, **kwargs):
  28. super(ClsHead, self).__init__()
  29. self.pool = nn.AdaptiveAvgPool2D(1)
  30. stdv = 1.0 / math.sqrt(in_channels * 1.0)
  31. self.fc = nn.Linear(
  32. in_channels,
  33. class_dim,
  34. weight_attr=ParamAttr(
  35. name="fc_0.w_0",
  36. initializer=nn.initializer.Uniform(-stdv, stdv)),
  37. bias_attr=ParamAttr(name="fc_0.b_0"), )
  38. def forward(self, x):
  39. x = self.pool(x)
  40. x = paddle.reshape(x, shape=[x.shape[0], x.shape[1]])
  41. x = self.fc(x)
  42. if not self.training:
  43. x = F.softmax(x, axis=1)
  44. return x