test_cross_entropy_op.py 3.4 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#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 已提交
14
import unittest
15
import numpy as np
16
from op_test import OpTest, randomize_probability
Q
Qiao Longfei 已提交
17 18


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

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

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

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

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

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

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

Y
Yan Chunwei 已提交
45

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

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

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

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

    def test_check_output(self):
        self.check_output()

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


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

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

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

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

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

    def test_check_output(self):
        self.check_output()

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


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