resnet_embedding.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright (c) 2022 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 os
  15. import paddle
  16. import paddle.nn.functional as F
  17. from paddle import nn
  18. from .resnet import ResNet50, ResNet101
  19. from ppdet.core.workspace import register
  20. __all__ = ['ResNetEmbedding']
  21. @register
  22. class ResNetEmbedding(nn.Layer):
  23. in_planes = 2048
  24. def __init__(self, model_name='ResNet50', last_stride=1):
  25. super(ResNetEmbedding, self).__init__()
  26. assert model_name in ['ResNet50', 'ResNet101'], "Unsupported ReID arch: {}".format(model_name)
  27. self.base = eval(model_name)(last_conv_stride=last_stride)
  28. self.gap = nn.AdaptiveAvgPool2D(output_size=1)
  29. self.flatten = nn.Flatten(start_axis=1, stop_axis=-1)
  30. self.bn = nn.BatchNorm1D(self.in_planes, bias_attr=False)
  31. def forward(self, x):
  32. base_out = self.base(x)
  33. global_feat = self.gap(base_out)
  34. global_feat = self.flatten(global_feat)
  35. global_feat = self.bn(global_feat)
  36. return global_feat