test_cross_entropy_op.py 3.4 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
18
import paddle.fluid as fluid
Q
Qiao Longfei 已提交
19 20


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

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

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

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

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

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

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

Y
Yan Chunwei 已提交
47

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

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

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

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

    def test_check_output(self):
        self.check_output()

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


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

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

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

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

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

    def test_check_output(self):
        self.check_output()

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


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