test_cross_entropy_op.py 9.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

Q
Qiao Longfei 已提交
17
import unittest
18
import numpy as np
C
chengduo 已提交
19
import paddle.fluid.core as core
20
from op_test import OpTest, randomize_probability
Q
Qiao Longfei 已提交
21 22


C
chengduo 已提交
23
class TestCrossEntropyOp(OpTest):
C
caoying03 已提交
24
    """Test cross-entropy with discrete one-hot labels.
25 26
    """

Q
Qiao Longfei 已提交
27
    def setUp(self):
28
        self.op_type = "cross_entropy"
C
chengduo 已提交
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
        self.soft_label = False
        self.ignore_index = -100
        self.dtype = np.float64
        self.batch_size = 30
        self.class_num = 10

        self.init_dtype_type()
        self.init_attr_type()
        self.init_bs_class_num()
        self.init_x()
        self.init_label()
        self.get_cross_entropy()

        self.inputs = {"X": self.x, "Label": self.label}
        self.outputs = {"Y": self.cross_entropy}
        self.attrs = {
            "soft_label": self.soft_label,
            "ignore_index": self.ignore_index
        }

    def init_x(self):
        self.x = randomize_probability(
            self.batch_size, self.class_num, dtype=self.dtype)

    def init_label(self):
        self.label = np.random.randint(
            0, self.class_num, (self.batch_size, 1), dtype="int64")

    def get_cross_entropy(self):
        self.cross_entropy = np.asmatrix(
            [[-np.log(self.x[i][self.label[i][0]])]
             for i in range(self.x.shape[0])],
            dtype="float64")
C
caoying03 已提交
62

C
chengduo 已提交
63 64
    def init_attr_type(self):
        pass
65

C
chengduo 已提交
66 67
    def init_dtype_type(self):
        pass
C
caoying03 已提交
68

C
chengduo 已提交
69 70
    def init_bs_class_num(self):
        pass
Q
Qiao Longfei 已提交
71

72
    def test_check_output(self):
Q
qijun 已提交
73
        self.check_output()
Q
Qiao Longfei 已提交
74

75
    def test_check_grad(self):
76
        self.check_grad(["X"], "Y", numeric_grad_delta=0.001)
77

Y
Yan Chunwei 已提交
78

C
chengduo 已提交
79
class TestCrossEntropyOp2(TestCrossEntropyOp):
C
caoying03 已提交
80
    """Test cross-entropy with vectorized soft labels.
81 82
    """

C
chengduo 已提交
83 84 85 86
    def init_label(self):
        self.label = np.random.uniform(
            0.1, 1.0, [self.batch_size, self.class_num]).astype(self.dtype)
        self.label /= self.label.sum(axis=1, keepdims=True)
C
caoying03 已提交
87

C
chengduo 已提交
88 89 90
    def get_cross_entropy(self):
        self.cross_entropy = (-self.label * np.log(self.x)).sum(
            axis=1, keepdims=True).astype(self.dtype)
C
caoying03 已提交
91

C
chengduo 已提交
92 93
    def init_attr_type(self):
        self.soft_label = True
94

C
chengduo 已提交
95 96 97 98 99 100
    def init_dtype_type(self):
        self.dtype = np.float32

    def init_bs_class_num(self):
        self.batch_size = 5
        self.class_num = 37
101 102

    def test_check_grad(self):
103 104
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)
105 106


C
chengduo 已提交
107
class TestCrossEntropyOp3(TestCrossEntropyOp):
C
caoying03 已提交
108
    """Test cross-entropy with vectorized one-hot representation of labels.
109 110
    """

C
chengduo 已提交
111 112 113 114 115
    def init_label(self):
        self.label_index = np.random.randint(0, self.class_num,
                                             (self.batch_size))
        self.label = np.zeros(self.x.shape).astype(self.dtype)
        self.label[np.arange(self.batch_size), self.label_index] = 1
C
caoying03 已提交
116

C
chengduo 已提交
117 118 119 120
    def get_cross_entropy(self):
        self.cross_entropy = np.asmatrix(
            [[-np.log(self.x[i][self.label_index[i]])]
             for i in range(self.x.shape[0])]).astype(self.dtype)
C
caoying03 已提交
121

C
chengduo 已提交
122 123
    def init_attr_type(self):
        self.soft_label = True
C
caoying03 已提交
124

C
chengduo 已提交
125 126
    def init_dtype_type(self):
        self.dtype = np.float32
127

C
chengduo 已提交
128 129 130
    def init_bs_class_num(self):
        self.batch_size = 5
        self.class_num = 17
131 132

    def test_check_grad(self):
133 134
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)
135 136


C
chengduo 已提交
137
class TestCrossEntropyOp4(TestCrossEntropyOp):
138 139 140
    """Test high rank tensor cross-entropy with discrete one-hot labels.
    """

C
chengduo 已提交
141 142 143 144 145 146
    def init_x(self):
        self.shape = [10, 2, 4]
        self.ins_num = np.prod(np.array(self.shape))
        self.X_2d = randomize_probability(self.ins_num,
                                          self.class_num).astype(self.dtype)
        self.x = self.X_2d.reshape(self.shape + [self.class_num])
147

C
chengduo 已提交
148 149 150 151
    def init_label(self):
        self.label_2d = np.random.randint(
            0, self.class_num, (self.ins_num, 1), dtype="int64")
        self.label = self.label_2d.reshape(self.shape + [1])
152

C
chengduo 已提交
153
    def get_cross_entropy(self):
154
        cross_entropy_2d = np.asmatrix(
C
chengduo 已提交
155 156 157 158
            [[-np.log(self.X_2d[i][self.label_2d[i][0]])]
             for i in range(self.X_2d.shape[0])]).astype(self.dtype)
        self.cross_entropy = np.array(cross_entropy_2d).reshape(self.shape +
                                                                [1])
159

C
chengduo 已提交
160 161
    def init_attr_type(self):
        self.soft_label = False
162

C
chengduo 已提交
163 164
    def init_dtype_type(self):
        self.dtype = np.float64
165

C
chengduo 已提交
166 167
    def init_bs_class_num(self):
        self.class_num = 10
168 169


C
chengduo 已提交
170
class TestCrossEntropyOp5(TestCrossEntropyOp):
171 172 173
    """Test high rank tensor cross-entropy with vectorized soft labels.
    """

C
chengduo 已提交
174 175 176 177 178 179
    def init_x(self):
        self.shape = [4, 3]
        self.ins_num = np.prod(np.array(self.shape))
        self.X_2d = randomize_probability(self.ins_num,
                                          self.class_num).astype(self.dtype)
        self.x = self.X_2d.reshape(self.shape + [self.class_num])
180

C
chengduo 已提交
181 182 183 184 185
    def init_label(self):
        self.label_2d = np.random.uniform(
            0.1, 1.0, [self.ins_num, self.class_num]).astype(self.dtype)
        self.label_2d /= self.label_2d.sum(axis=1, keepdims=True)
        self.label = self.label_2d.reshape(self.shape + [self.class_num])
186

C
chengduo 已提交
187 188 189 190 191
    def get_cross_entropy(self):
        cross_entropy_2d = (-self.label_2d * np.log(self.X_2d)).sum(
            axis=1, keepdims=True).astype(self.dtype)
        self.cross_entropy = np.array(cross_entropy_2d).reshape(self.shape +
                                                                [1])
192

C
chengduo 已提交
193 194
    def init_attr_type(self):
        self.soft_label = True
195

C
chengduo 已提交
196 197 198 199 200
    def init_dtype_type(self):
        self.dtype = np.float32

    def init_bs_class_num(self):
        self.class_num = 37
201 202 203 204 205 206

    def test_check_grad(self):
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)


C
chengduo 已提交
207
class TestCrossEntropyOp6(TestCrossEntropyOp):
208 209 210
    """Test high rank tensor cross-entropy with vectorized one-hot representation of labels.
    """

C
chengduo 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    def init_x(self):
        self.shape = [4, 3, 2]
        self.ins_num = np.prod(np.array(self.shape))
        self.X_2d = randomize_probability(self.ins_num,
                                          self.class_num).astype(self.dtype)
        self.x = self.X_2d.reshape(self.shape + [self.class_num])

    def init_label(self):
        self.label_index_2d = np.random.randint(
            0, self.class_num, (self.ins_num), dtype="int64")
        label_2d = np.zeros(self.X_2d.shape)
        label_2d[np.arange(self.ins_num), self.label_index_2d] = 1
        self.label = label_2d.reshape(self.shape + [self.class_num]).astype(
            self.dtype)

    def get_cross_entropy(self):
227
        cross_entropy_2d = np.asmatrix(
C
chengduo 已提交
228 229 230 231
            [[-np.log(self.X_2d[i][self.label_index_2d[i]])]
             for i in range(self.X_2d.shape[0])])
        self.cross_entropy = np.array(cross_entropy_2d).reshape(
            self.shape + [1]).astype(self.dtype)
232

C
chengduo 已提交
233 234
    def init_attr_type(self):
        self.soft_label = True
235

C
chengduo 已提交
236 237
    def init_dtype_type(self):
        self.dtype = np.float32
238

C
chengduo 已提交
239 240
    def init_bs_class_num(self):
        self.class_num = 17
241 242 243 244 245 246

    def test_check_grad(self):
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)


C
chengduo 已提交
247
class TestCrossEntropyOp7(TestCrossEntropyOp):
248 249 250
    """Test cross-entropy with ignore index.
    """

C
chengduo 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    def init_label(self):
        self.label = np.random.randint(
            0, self.class_num, (self.batch_size, 1), dtype="int64")

    def get_cross_entropy(self):
        self.cross_entropy = np.asmatrix(
            [[-np.log(self.x[i][self.label[i][0]])]
             if self.label[i][0] != self.ignore_index else [0]
             for i in range(self.x.shape[0])]).astype(self.dtype)

    def init_attr_type(self):
        self.soft_label = False
        self.ignore_index = 3

    def init_dtype_type(self):
        self.dtype = np.float64

    def init_bs_class_num(self):
        self.batch_size = 30
        self.class_num = 10


# Add Fp16 test
def create_test_class(parent, cls_name):
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestCrossEntropyFP16Op(parent):
        def init_dtype_type(self):
            return np.float16

        def test_check_output(self):
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
                self.check_output_with_place(place, atol=2e-1)

        def test_check_grad(self):
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
                self.check_grad_with_place(
                    place, ['X'], 'Y', max_relative_error=0.9)

    cls_name = "{0}".format(cls_name)
    TestCrossEntropyFP16Op.__name__ = cls_name
    globals()[cls_name] = TestCrossEntropyFP16Op


create_test_class(TestCrossEntropyOp, "TestCrossEntropyF16Op")
#create_test_class(TestCrossEntropyOp2, "TestCrossEntropyF16Op2")
create_test_class(TestCrossEntropyOp3, "TestCrossEntropyF16Op3")
create_test_class(TestCrossEntropyOp4, "TestCrossEntropyF16Op4")
#create_test_class(TestCrossEntropyOp5, "TestCrossEntropyF16Op5")
create_test_class(TestCrossEntropyOp6, "TestCrossEntropyF16Op6")
create_test_class(TestCrossEntropyOp7, "TestCrossEntropyF16Op7")
304

Q
Qiao Longfei 已提交
305 306
if __name__ == "__main__":
    unittest.main()