test_top_k_op.py 1.9 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
import unittest
16

武毅 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest
19

H
hong 已提交
20
import paddle
武毅 已提交
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
29
        self.check_cinn = True
W
Wu Yi 已提交
30 31
        self.init_dtype()

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

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

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

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

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

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

57
    def test_check_output(self):
58
        self.check_output(check_cinn=self.check_cinn)
59

60
    def test_check_grad(self):
61
        self.check_grad({'X'}, 'Out', check_cinn=self.check_cinn)
W
whs 已提交
62 63


Q
qijun 已提交
64
if __name__ == "__main__":
H
hong 已提交
65
    paddle.enable_static()
武毅 已提交
66
    unittest.main()