test_bincount_op.py 7.3 KB
Newer Older
S
smallv0221 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   Copyright (c) 2019 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
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid import Program, program_guard
P
phlrain 已提交
23
from paddle.fluid.framework import _test_eager_guard
S
smallv0221 已提交
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 60 61 62 63 64 65
from op_test import OpTest

paddle.enable_static()


class TestBincountOpAPI(unittest.TestCase):
    """Test bincount api."""

    def test_static_graph(self):
        startup_program = fluid.Program()
        train_program = fluid.Program()
        with fluid.program_guard(train_program, startup_program):
            inputs = fluid.data(name='input', dtype='int64', shape=[7])
            weights = fluid.data(name='weights', dtype='int64', shape=[7])
            output = paddle.bincount(inputs, weights=weights)
            place = fluid.CPUPlace()
            if fluid.core.is_compiled_with_cuda():
                place = fluid.CUDAPlace(0)
            exe = fluid.Executor(place)
            exe.run(startup_program)
            img = np.array([0, 1, 1, 3, 2, 1, 7]).astype(np.int64)
            w = np.array([0, 1, 1, 2, 2, 1, 0]).astype(np.int64)
            res = exe.run(train_program,
                          feed={'input': img,
                                'weights': w},
                          fetch_list=[output])
            actual = np.array(res[0])
            expected = np.bincount(img, weights=w)
            self.assertTrue(
                (actual == expected).all(),
                msg='bincount output is wrong, out =' + str(actual))

    def test_dygraph(self):
        with fluid.dygraph.guard():
            inputs_np = np.array([0, 1, 1, 3, 2, 1, 7]).astype(np.int64)
            inputs = fluid.dygraph.to_variable(inputs_np)
            actual = paddle.bincount(inputs)
            expected = np.bincount(inputs)
            self.assertTrue(
                (actual.numpy() == expected).all(),
                msg='bincount output is wrong, out =' + str(actual.numpy()))

P
phlrain 已提交
66 67 68 69 70 71 72 73
            with _test_eager_guard():
                inputs = fluid.dygraph.to_variable(inputs_np)
                actual = paddle.bincount(inputs)
                expected = np.bincount(inputs)
                self.assertTrue(
                    (actual.numpy() == expected).all(),
                    msg='bincount output is wrong, out =' + str(actual.numpy()))

S
smallv0221 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

class TestBincountOpError(unittest.TestCase):
    """Test bincount op error."""

    def run_network(self, net_func):
        with fluid.dygraph.guard():
            net_func()

    def test_input_value_error(self):
        """Test input tensor should be non-negative."""

        def net_func():
            input_value = paddle.to_tensor([1, 2, 3, 4, -5])
            paddle.bincount(input_value)

        with self.assertRaises(ValueError):
            self.run_network(net_func)

    def test_input_shape_error(self):
        """Test input tensor should be 1-D tansor."""

        def net_func():
            input_value = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
            paddle.bincount(input_value)

        with self.assertRaises(ValueError):
            self.run_network(net_func)

    def test_minlength_value_error(self):
        """Test minlength is non-negative ints."""

        def net_func():
            input_value = paddle.to_tensor([1, 2, 3, 4, 5])
            paddle.bincount(input_value, minlength=-1)

        with self.assertRaises(IndexError):
            self.run_network(net_func)

    def test_input_type_errors(self):
        """Test input tensor should only contain non-negative ints."""

        def net_func():
            input_value = paddle.to_tensor([1., 2., 3., 4., 5.])
            paddle.bincount(input_value)

        with self.assertRaises(TypeError):
            self.run_network(net_func)

    def test_weights_shape_error(self):
        """Test weights tensor should have the same shape as input tensor."""

        def net_func():
            input_value = paddle.to_tensor([1, 2, 3, 4, 5])
            weights = paddle.to_tensor([1, 1, 1, 1, 1, 1])
            paddle.bincount(input_value, weights=weights)

        with self.assertRaises(ValueError):
            self.run_network(net_func)


class TestBincountOp(OpTest):
    # without weights
    def setUp(self):
        self.op_type = "bincount"
        self.init_test_case()
        self.inputs = {"X": self.np_input}
        self.attrs = {"minlength": self.minlength}
        self.outputs = {"Out": self.Out}

    def init_test_case(self):
        self.minlength = 0
        self.np_input = np.random.randint(low=0, high=20, size=10)
        self.Out = np.bincount(self.np_input, minlength=self.minlength)

    def test_check_output(self):
        self.check_output()


class TestCase1(TestBincountOp):
    # with weights(FLOAT32)
    def setUp(self):
        self.op_type = "bincount"
        self.init_test_case()
        self.inputs = {"X": self.np_input, "Weights": self.np_weights}
        self.attrs = {"minlength": self.minlength}
        self.outputs = {"Out": self.Out}

    def init_test_case(self):
        self.minlength = 0
        self.np_weights = np.random.randint(
            low=0, high=20, size=10).astype(np.float32)
        self.np_input = np.random.randint(low=0, high=20, size=10)
        self.Out = np.bincount(
            self.np_input, weights=self.np_weights,
            minlength=self.minlength).astype(np.float32)


class TestCase2(TestBincountOp):
    # with weights(other)
    def setUp(self):
        self.op_type = "bincount"
        self.init_test_case()
        self.inputs = {"X": self.np_input, "Weights": self.np_weights}
        self.attrs = {"minlength": self.minlength}
        self.outputs = {"Out": self.Out}

    def init_test_case(self):
        self.minlength = 0
        self.np_weights = np.random.randint(low=0, high=20, size=10)
        self.np_input = np.random.randint(low=0, high=20, size=10)
        self.Out = np.bincount(
            self.np_input, weights=self.np_weights, minlength=self.minlength)


class TestCase3(TestBincountOp):
    # empty input
    def init_test_case(self):
        self.minlength = 0
        self.np_input = np.array([], dtype=np.int64)
        self.Out = np.bincount(self.np_input, minlength=self.minlength)


class TestCase4(TestBincountOp):
    # with input(INT32)
    def init_test_case(self):
        self.minlength = 0
        self.np_input = np.random.randint(
            low=0, high=20, size=10).astype(np.int32)
        self.Out = np.bincount(self.np_input, minlength=self.minlength)


class TestCase5(TestBincountOp):
    # with minlength greater than max(X)
    def init_test_case(self):
        self.minlength = 20
        self.np_input = np.random.randint(low=0, high=10, size=10)
        self.Out = np.bincount(self.np_input, minlength=self.minlength)


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