test_cross_entropy_op.py 6.7 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
19
from op_test import OpTest, randomize_probability
Q
Qiao Longfei 已提交
20 21


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

Q
Qiao Longfei 已提交
26
    def setUp(self):
27
        self.op_type = "cross_entropy"
Q
qijun 已提交
28 29
        batch_size = 30
        class_num = 10
C
caoying03 已提交
30

31 32
        X = randomize_probability(batch_size, class_num, dtype='float64')

33
        label = np.random.randint(0, class_num, (batch_size, 1), dtype="int64")
34 35
        cross_entropy = np.asmatrix(
            [[-np.log(X[i][label[i][0]])] for i in range(X.shape[0])],
36
            dtype="float64")
C
caoying03 已提交
37

38
        self.inputs = {"X": X, "Label": label}
39
        self.outputs = {"Y": cross_entropy}
Q
qijun 已提交
40
        self.attrs = {"soft_label": False}
Q
Qiao Longfei 已提交
41

42
    def test_check_output(self):
Q
qijun 已提交
43
        self.check_output()
Q
Qiao Longfei 已提交
44

45
    def test_check_grad(self):
46
        self.check_grad(["X"], "Y", numeric_grad_delta=0.001)
47

Y
Yan Chunwei 已提交
48

49
class TestCrossEntropyOp2(OpTest):
C
caoying03 已提交
50
    """Test cross-entropy with vectorized soft labels.
51 52
    """

53 54
    def setUp(self):
        self.op_type = "cross_entropy"
C
caoying03 已提交
55
        batch_size = 5
56
        class_num = 37
C
caoying03 已提交
57

58
        X = randomize_probability(batch_size, class_num)
59 60
        label = np.random.uniform(0.1, 1.0,
                                  [batch_size, class_num]).astype("float32")
61
        label /= label.sum(axis=1, keepdims=True)
62 63
        cross_entropy = (-label * np.log(X)).sum(
            axis=1, keepdims=True).astype("float32")
C
caoying03 已提交
64

C
caoying03 已提交
65 66
        self.inputs = {"X": X, "Label": label}
        self.outputs = {"Y": cross_entropy}
67
        self.attrs = {"soft_label": True}
68 69 70 71 72

    def test_check_output(self):
        self.check_output()

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


class TestCrossEntropyOp3(OpTest):
C
caoying03 已提交
78
    """Test cross-entropy with vectorized one-hot representation of labels.
79 80 81 82
    """

    def setUp(self):
        self.op_type = "cross_entropy"
C
caoying03 已提交
83 84
        batch_size = 5
        class_num = 17
C
caoying03 已提交
85

86
        X = randomize_probability(batch_size, class_num)
87 88 89 90
        label_index = np.random.randint(
            0, class_num, (batch_size), dtype="int32")
        label = np.zeros(X.shape)
        label[np.arange(batch_size), label_index] = 1
C
caoying03 已提交
91

92 93 94 95
        cross_entropy = np.asmatrix(
            [[-np.log(X[i][label_index[i]])] for i in range(X.shape[0])],
            dtype="float32")
        cross_entropy2 = (-label * np.log(X)).sum(
96
            axis=1, keepdims=True).astype("float32")
C
caoying03 已提交
97

Y
Yu Yang 已提交
98
        self.inputs = {"X": X, "Label": label.astype(np.float32)}
C
caoying03 已提交
99
        self.outputs = {"Y": cross_entropy}
100
        self.attrs = {"soft_label": True}
101 102 103 104 105

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
106 107
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)
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
class TestCrossEntropyOp4(OpTest):
    """Test high rank tensor cross-entropy with discrete one-hot labels.
    """

    def setUp(self):
        self.op_type = "cross_entropy"
        shape = [10, 2, 4]
        ins_num = np.prod(np.array(shape))
        class_num = 10

        X_2d = randomize_probability(ins_num, class_num, dtype='float64')

        label_2d = np.random.randint(0, class_num, (ins_num, 1), dtype="int64")
        cross_entropy_2d = np.asmatrix(
            [[-np.log(X_2d[i][label_2d[i][0]])] for i in range(X_2d.shape[0])],
            dtype="float64")

        X = X_2d.reshape(shape + [class_num])
        label = label_2d.reshape(shape + [1])
        cross_entropy = np.array(cross_entropy_2d).reshape(shape + [1])

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

    def test_check_output(self):
        self.check_output()

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


class TestCrossEntropyOp5(OpTest):
    """Test high rank tensor cross-entropy with vectorized soft labels.
    """

    def setUp(self):
        self.op_type = "cross_entropy"
        shape = [4, 3]
        ins_num = np.prod(np.array(shape))
        class_num = 37

        X_2d = randomize_probability(ins_num, class_num)
        label_2d = np.random.uniform(0.1, 1.0,
                                     [ins_num, class_num]).astype("float32")
        label_2d /= label_2d.sum(axis=1, keepdims=True)
        cross_entropy_2d = (-label_2d * np.log(X_2d)).sum(
            axis=1, keepdims=True).astype("float32")

        X = X_2d.reshape(shape + [class_num])
        label = label_2d.reshape(shape + [class_num])
        cross_entropy = np.array(cross_entropy_2d).reshape(shape + [1])

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

    def test_check_output(self):
        self.check_output()

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


class TestCrossEntropyOp6(OpTest):
    """Test high rank tensor cross-entropy with vectorized one-hot representation of labels.
    """

    def setUp(self):
        self.op_type = "cross_entropy"
        shape = [4, 3, 2]
        ins_num = np.prod(np.array(shape))
        class_num = 17

        X_2d = randomize_probability(ins_num, class_num)
        label_index_2d = np.random.randint(
            0, class_num, (ins_num), dtype="int32")
        label_2d = np.zeros(X_2d.shape)
        label_2d[np.arange(ins_num), label_index_2d] = 1

        cross_entropy_2d = np.asmatrix(
            [[-np.log(X_2d[i][label_index_2d[i]])]
             for i in range(X_2d.shape[0])],
            dtype="float32")

        X = X_2d.reshape(shape + [class_num])
        label = label_2d.reshape(shape + [class_num])
        cross_entropy = np.array(cross_entropy_2d).reshape(shape + [1])

        self.inputs = {"X": X, "Label": label.astype(np.float32)}
        self.outputs = {"Y": cross_entropy}
        self.attrs = {"soft_label": True}

    def test_check_output(self):
        self.check_output()

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


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