postprocessor.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #include "ultra_infer/vision/classification/ppcls/postprocessor.h"
  15. #include "ultra_infer/vision/utils/utils.h"
  16. namespace ultra_infer {
  17. namespace vision {
  18. namespace classification {
  19. PaddleClasPostprocessor::PaddleClasPostprocessor(int topk) {
  20. topk_ = topk;
  21. initialized_ = true;
  22. }
  23. bool PaddleClasPostprocessor::Run(const std::vector<FDTensor> &infer_result,
  24. std::vector<ClassifyResult> *results) {
  25. if (!initialized_) {
  26. FDERROR << "Postprocessor is not initialized." << std::endl;
  27. return false;
  28. }
  29. int batch = infer_result[0].shape[0];
  30. int num_classes = infer_result[0].shape[1];
  31. const float *infer_result_data =
  32. reinterpret_cast<const float *>(infer_result[0].Data());
  33. results->resize(batch);
  34. int topk = std::min(num_classes, topk_);
  35. for (int i = 0; i < batch; ++i) {
  36. (*results)[i].label_ids = utils::TopKIndices(
  37. infer_result_data + i * num_classes, num_classes, topk);
  38. (*results)[i].scores.resize(topk);
  39. for (int j = 0; j < topk; ++j) {
  40. (*results)[i].scores[j] =
  41. infer_result_data[i * num_classes + (*results)[i].label_ids[j]];
  42. }
  43. }
  44. return true;
  45. }
  46. } // namespace classification
  47. } // namespace vision
  48. } // namespace ultra_infer