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
H
hong 已提交
21
import paddle
武毅 已提交
22 23


Q
qijun 已提交
24
class TestTopkOp(OpTest):
武毅 已提交
25
    def setUp(self):
W
whs 已提交
26
        self.variable_k = False
Q
qingqing01 已提交
27
        self.set_args()
Q
qijun 已提交
28
        self.op_type = "top_k"
29
        self.dtype = np.float64
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 58 59
    def test_check_output(self):
        self.check_output()

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


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