test_mode_op.py 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# 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.

from __future__ import print_function

import unittest
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid as fluid


def _mode1D(a):
    sorted_inds = np.argsort(a, kind='stable')
    sorted_array = a[sorted_inds]
    max_freq = 0
    cur_freq = 0
    mode = -1
    for i in range(len(sorted_array)):
        cur_freq += 1
        if i == len(sorted_array) - 1 or sorted_array[i] != sorted_array[i + 1]:
            if cur_freq > max_freq:
                mode = sorted_array[i]
                index = sorted_inds[i]
                max_freq = cur_freq
        cur_freq = 0
    return mode, index


def cal_mode(a, axis, keepdim=False):
    if axis < 0:
        axis = len(a.shape) + axis
    in_dims = list(range(a.ndim))
    a_view = np.transpose(a, in_dims[:axis] + in_dims[axis + 1:] + [axis])
    inds = np.ndindex(a_view.shape[:-1])
    modes = np.empty(a_view.shape[:-1], dtype=a.dtype)
    indexes = np.empty(a_view.shape[:-1], dtype=np.int64)
    for ind in inds:
        modes[ind], indexes[ind] = _mode1D(a_view[ind])
    if keepdim:
        newshape = list(a.shape)
        newshape[axis] = 1
        modes = modes.reshape(newshape)
        indexes = indexes.reshape(newshape)
    return modes, indexes


class TestModeOp(OpTest):
60

61 62 63 64 65
    def init_args(self):
        self.axis = 1

    def setUp(self):
        self.op_type = "mode"
66
        self.python_api = paddle.mode
67 68 69 70 71 72 73 74 75 76 77
        self.dtype = np.float64
        np.random.seed(666)
        self.input_data = np.random.rand(2, 64, 1)
        self.init_args()
        self.inputs = {'X': self.input_data}
        self.attrs = {'axis': self.axis}
        output, indices = cal_mode(self.input_data, axis=self.axis)
        self.outputs = {'Out': output, 'Indices': indices}

    def test_check_output(self):
        paddle.enable_static()
78
        self.check_output(check_eager=True)
79 80 81

    def test_check_grad(self):
        paddle.enable_static()
82
        self.check_grad(set(['X']), 'Out', check_eager=True)
83 84 85


class TestModeOpLastdim(OpTest):
86

87 88 89 90 91
    def init_args(self):
        self.axis = -1

    def setUp(self):
        self.op_type = "mode"
92
        self.python_api = paddle.mode
93 94 95 96 97 98 99 100 101 102 103
        self.dtype = np.float64
        np.random.seed(666)
        self.input_data = np.random.rand(2, 1, 1, 2, 30)
        self.init_args()
        self.inputs = {'X': self.input_data}
        self.attrs = {'axis': self.axis}
        output, indices = cal_mode(self.input_data, axis=self.axis)
        self.outputs = {'Out': output, 'Indices': indices}

    def test_check_output(self):
        paddle.enable_static()
104
        self.check_output(check_eager=True)
105 106 107

    def test_check_grad(self):
        paddle.enable_static()
108
        self.check_grad(set(['X']), 'Out', check_eager=True)
109 110 111


class TestModeOpKernels(unittest.TestCase):
112

113 114 115 116 117 118
    def setUp(self):
        self.axises = [-1, 1]
        np.random.seed(666)
        self.inputs = np.ceil(np.random.rand(2, 10, 10) * 1000)

    def test_mode_op(self):
119

120 121 122 123 124 125 126 127
        def test_cpu_kernel():
            paddle.set_device('cpu')
            tensor = paddle.to_tensor(self.inputs)
            for axis in self.axises:
                value_expect, indice_expect = cal_mode(self.inputs, axis)
                v, inds = paddle.mode(tensor, axis)
                self.assertTrue(np.allclose(v.numpy(), value_expect))

128 129 130
                value_expect, indice_expect = cal_mode(self.inputs,
                                                       axis,
                                                       keepdim=True)
131 132 133 134 135 136 137 138 139 140 141
                v, inds = paddle.mode(tensor, axis, keepdim=True)
                self.assertTrue(np.allclose(v.numpy(), value_expect))

        def test_gpu_kernel():
            paddle.set_device('gpu')
            tensor = paddle.to_tensor(self.inputs)
            for axis in self.axises:
                value_expect, indice_expect = cal_mode(self.inputs, axis)
                v, inds = paddle.mode(tensor, axis)
                self.assertTrue(np.allclose(v.numpy(), value_expect))

142 143 144
                value_expect, indice_expect = cal_mode(self.inputs,
                                                       axis,
                                                       keepdim=True)
145 146 147 148 149 150 151 152 153 154
                v, inds = paddle.mode(tensor, axis, keepdim=True)
                self.assertTrue(np.allclose(v.numpy(), value_expect))

        paddle.disable_static()
        test_cpu_kernel()
        if fluid.core.is_compiled_with_cuda():
            test_gpu_kernel()


class TestModeOpErrors(unittest.TestCase):
155

156 157 158 159 160 161 162 163 164 165
    def setUp(self):
        self.x = paddle.uniform([2, 10, 20, 25], dtype='float32')

        def test_dim_range_error():
            self.x.mode(axis=5)

        self.assertRaises(ValueError, test_dim_range_error)


class TestModeOpInStatic(unittest.TestCase):
166

167 168
    def setUp(self):
        np.random.seed(666)
169 170
        self.input_data = np.ceil(np.random.random((2, 10, 10)) * 1000,
                                  dtype=np.float64)
171 172 173 174 175

    def test_run_static(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program(),
                                         paddle.static.Program()):
176 177 178
            input_tensor = paddle.static.data(name="x",
                                              shape=[2, 10, 10],
                                              dtype="float64")
179 180 181 182 183 184 185 186 187 188 189

            result = paddle.mode(input_tensor, axis=1)
            expect_value = cal_mode(self.input_data, axis=1)[0]
            exe = paddle.static.Executor(paddle.CPUPlace())
            paddle_result = exe.run(feed={"x": self.input_data},
                                    fetch_list=[result])[0]
            self.assertTrue(np.allclose(paddle_result, expect_value))


if __name__ == '__main__':
    unittest.main()