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
15 #include "argmax.h"
16
17 #include <functional>
18
19 namespace ncnn {
20
ArgMax()21 ArgMax::ArgMax()
22 {
23 one_blob_only = true;
24 }
25
load_param(const ParamDict & pd)26 int ArgMax::load_param(const ParamDict& pd)
27 {
28 out_max_val = pd.get(0, 0);
29 topk = pd.get(1, 1);
30
31 return 0;
32 }
33
forward(const Mat & bottom_blob,Mat & top_blob,const Option & opt) const34 int ArgMax::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
35 {
36 int size = bottom_blob.total();
37
38 if (out_max_val)
39 top_blob.create(topk, 2, 4u, opt.blob_allocator);
40 else
41 top_blob.create(topk, 1, 4u, opt.blob_allocator);
42 if (top_blob.empty())
43 return -100;
44
45 const float* ptr = bottom_blob;
46
47 // partial sort topk with index
48 // optional value
49 std::vector<std::pair<float, int> > vec;
50 vec.resize(size);
51 for (int i = 0; i < size; i++)
52 {
53 vec[i] = std::make_pair(ptr[i], i);
54 }
55
56 std::partial_sort(vec.begin(), vec.begin() + topk, vec.end(),
57 std::greater<std::pair<float, int> >());
58
59 float* outptr = top_blob;
60 if (out_max_val)
61 {
62 float* valptr = outptr + topk;
63 for (int i = 0; i < topk; i++)
64 {
65 outptr[i] = vec[i].first;
66 valptr[i] = vec[i].second;
67 }
68 }
69 else
70 {
71 for (int i = 0; i < topk; i++)
72 {
73 outptr[i] = vec[i].second;
74 }
75 }
76
77 return 0;
78 }
79
80 } // namespace ncnn
81