You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

argmax.cpp 2.1 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "argmax.h"
  15. #include <algorithm>
  16. #include <functional>
  17. namespace ncnn {
  18. DEFINE_LAYER_CREATOR(ArgMax)
  19. ArgMax::ArgMax()
  20. {
  21. one_blob_only = true;
  22. }
  23. int ArgMax::load_param(const ParamDict& pd)
  24. {
  25. out_max_val = pd.get(0, 0);
  26. topk = pd.get(1, 1);
  27. return 0;
  28. }
  29. int ArgMax::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
  30. {
  31. int size = bottom_blob.total();
  32. if (out_max_val)
  33. top_blob.create(topk, 2, 4u, opt.blob_allocator);
  34. else
  35. top_blob.create(topk, 1, 4u, opt.blob_allocator);
  36. if (top_blob.empty())
  37. return -100;
  38. const float* ptr = bottom_blob;
  39. // partial sort topk with index
  40. // optional value
  41. std::vector<std::pair<float, int> > vec;
  42. vec.resize(size);
  43. for (int i = 0; i < size; i++)
  44. {
  45. vec[i] = std::make_pair(ptr[i], i);
  46. }
  47. std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
  48. std::greater<std::pair<float, int> >());
  49. float* outptr = top_blob;
  50. if (out_max_val)
  51. {
  52. float* valptr = outptr + topk;
  53. for (int i = 0; i < topk; i++)
  54. {
  55. outptr[i] = vec[i].first;
  56. valptr[i] = vec[i].second;
  57. }
  58. }
  59. else
  60. {
  61. for (int i = 0; i < topk; i++)
  62. {
  63. outptr[i] = vec[i].second;
  64. }
  65. }
  66. return 0;
  67. }
  68. } // namespace ncnn