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.

Q
Qiao Longfei 已提交
15
import unittest
16
import numpy as np
17
from op_test import OpTest, randomize_probability
Q
Qiao Longfei 已提交
18 19


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

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

29 30
        X = randomize_probability(batch_size, class_num, dtype='float64')

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

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

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

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

Y
Yan Chunwei 已提交
46

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

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

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

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

    def test_check_output(self):
        self.check_output()

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


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

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

84
        X = randomize_probability(batch_size, class_num)
85 86 87 88
        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 已提交
89

90 91 92 93
        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(
94
            axis=1, keepdims=True).astype("float32")
C
caoying03 已提交
95

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

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
104 105
        self.check_grad(
            ["X"], "Y", max_relative_error=0.05, numeric_grad_delta=0.001)
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
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 已提交
210 211
if __name__ == "__main__":
    unittest.main()