test_top_k_op.py 1.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
from __future__ import print_function

武毅 已提交
17 18
import unittest
import numpy as np
19
from op_test import OpTest
20
import paddle.fluid.core as core
武毅 已提交
21 22


Q
qijun 已提交
23
class TestTopkOp(OpTest):
武毅 已提交
24
    def setUp(self):
W
whs 已提交
25
        self.variable_k = False
Q
qingqing01 已提交
26
        self.set_args()
Q
qijun 已提交
27
        self.op_type = "top_k"
28
        self.dtype = np.float64
W
Wu Yi 已提交
29 30
        self.init_dtype()

Q
qingqing01 已提交
31
        k = self.top_k
W
Wu Yi 已提交
32
        input = np.random.random((self.row, k)).astype(self.dtype)
Q
qingqing01 已提交
33 34
        output = np.ndarray((self.row, k))
        indices = np.ndarray((self.row, k)).astype("int64")
武毅 已提交
35
        self.inputs = {'X': input}
W
whs 已提交
36 37 38 39 40

        if self.variable_k:
            self.inputs['K'] = np.array([k]).astype("int32")
        else:
            self.attrs = {'k': k}
武毅 已提交
41

Q
qingqing01 已提交
42
        for rowid in range(self.row):
武毅 已提交
43
            row = input[rowid]
Q
qingqing01 已提交
44 45
            output[rowid] = np.sort(row)[::-1][:k]
            indices[rowid] = row.argsort()[::-1][:k]
武毅 已提交
46 47 48

        self.outputs = {'Out': output, 'Indices': indices}

W
Wu Yi 已提交
49 50 51
    def init_dtype(self):
        pass

Q
qingqing01 已提交
52
    def set_args(self):
53
        self.row = 100
Q
qingqing01 已提交
54 55
        self.top_k = 1

56 57 58
    def test_check_output(self):
        self.check_output()

59 60
    def test_check_grad(self):
        self.check_grad(set(['X']), 'Out')
W
whs 已提交
61 62


Q
qijun 已提交
63
if __name__ == "__main__":
武毅 已提交
64
    unittest.main()