test_top_k_op.py 2.0 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#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.
武毅 已提交
14 15
import unittest
import numpy as np
Q
qijun 已提交
16
from op_test import OpTest
武毅 已提交
17 18


Q
qijun 已提交
19
class TestTopkOp(OpTest):
武毅 已提交
20
    def setUp(self):
Q
qijun 已提交
21
        self.op_type = "top_k"
武毅 已提交
22 23 24
        k = 1
        input = np.random.random((32, 84)).astype("float32")
        output = np.ndarray((32, k))
F
fengjiayi 已提交
25
        indices = np.ndarray((32, k)).astype("int64")
武毅 已提交
26 27 28 29 30 31 32 33 34 35 36

        self.inputs = {'X': input}
        self.attrs = {'k': k}

        for rowid in xrange(32):
            row = input[rowid]
            output[rowid] = np.sort(row)[-k:]
            indices[rowid] = row.argsort()[-k:]

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

37 38 39
    def test_check_output(self):
        self.check_output()

武毅 已提交
40

Q
qijun 已提交
41
class TestTopkOp3d(OpTest):
武毅 已提交
42
    def setUp(self):
Q
qijun 已提交
43
        self.op_type = "top_k"
武毅 已提交
44 45 46 47
        k = 1
        input = np.random.random((32, 2, 84)).astype("float32")
        input_flat_2d = input.reshape(64, 84)
        output = np.ndarray((64, k))
F
fengjiayi 已提交
48
        indices = np.ndarray((64, k)).astype("int64")
武毅 已提交
49 50 51 52 53 54 55 56 57 58 59 60

        # FIXME: should use 'X': input for a 3d input
        self.inputs = {'X': input_flat_2d}
        self.attrs = {'k': k}

        for rowid in xrange(64):
            row = input_flat_2d[rowid]
            output[rowid] = np.sort(row)[-k:]
            indices[rowid] = row.argsort()[-k:]

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

61 62 63
    def test_check_output(self):
        self.check_output()

武毅 已提交
64

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