test_cross_entropy_op.py 5.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


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
class TestCrossEntropyStable(unittest.TestCase):
    def main(self, place):
        if isinstance(
                place,
                fluid.CUDAPlace) and not fluid.core.is_compiled_with_cuda():
            return

        class DataRandom(object):
            def __init__(self):
                self.random = np.random.RandomState(seed=1)

            def next(self):
                return {
                    'input': self.random.uniform(
                        low=-1, high=1, size=(64, 200)).astype('float32'),
                    'label': self.random.uniform(
                        low=0, high=10000, size=(64, 1)).astype('int64'),
                }

        losses = []
        for _ in xrange(2):
            startup = fluid.Program()
            startup.random_seed = 1
            main = fluid.Program()
            scope = fluid.core.Scope()
            with fluid.scope_guard(scope):
                with fluid.program_guard(main, startup):
                    img = fluid.layers.data('input', shape=[200])
                    label = fluid.layers.data('label', shape=[1], dtype='int64')
                    prediction = fluid.layers.fc(input=img,
                                                 size=10000,
                                                 act='softmax')
                    xe = fluid.layers.cross_entropy(
                        input=prediction, label=label)
                    loss = fluid.layers.mean(xe)
                    adam = fluid.optimizer.Adam()
                    adam.minimize(loss)

                    exe = fluid.Executor(place)
                    exe.run(startup)
                    data = DataRandom()
                    for i in xrange(1000):
                        exe.run(feed=next(data))
                    losses.append(
                        exe.run(feed=next(data), fetch_list=[loss])[0])
        print losses
        self.assertAlmostEqual(losses[0][0], losses[1][0])

    def test_cpu(self):
        self.main(fluid.CPUPlace())

    def test_cuda(self):
        self.main(fluid.CUDAPlace(0))


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