test_cross_entropy_op.py 3.4 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
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


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