test_if_else_op.py 7.6 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.

15
import paddle
16
import paddle.fluid.layers as layers
17
from paddle.fluid.framework import Program, program_guard
18 19 20
from paddle.fluid.executor import Executor
from paddle.fluid.optimizer import MomentumOptimizer
import paddle.fluid.core as core
21
import paddle.fluid as fluid
Y
Yu Yang 已提交
22 23 24 25 26 27
import unittest
import numpy as np


class TestMNISTIfElseOp(unittest.TestCase):
    def test_raw_api(self):
28 29 30 31
        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            image = layers.data(name='x', shape=[784], dtype='float32')
Y
Yu Yang 已提交
32

33
            label = layers.data(name='y', shape=[1], dtype='int64')
Y
Yu Yang 已提交
34

35
            limit = layers.fill_constant(shape=[1], dtype='int64', value=5)
36 37 38
            cond = layers.less_than(x=label, y=limit)
            true_image, false_image = layers.split_lod_tensor(
                input=image, mask=cond)
Y
Yu Yang 已提交
39

40
            true_out = layers.create_tensor(dtype='float32')
41
            true_cond = layers.ConditionalBlock([cond])
Y
Yu Yang 已提交
42

43 44 45 46
            with true_cond.block():
                hidden = layers.fc(input=true_image, size=100, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                layers.assign(input=prob, output=true_out)
Y
Yu Yang 已提交
47

48
            false_out = layers.create_tensor(dtype='float32')
49
            false_cond = layers.ConditionalBlock([cond])
Y
Yu Yang 已提交
50

51 52 53 54
            with false_cond.block():
                hidden = layers.fc(input=false_image, size=200, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                layers.assign(input=prob, output=false_out)
Y
Yu Yang 已提交
55

56 57 58
            prob = layers.merge_lod_tensor(
                in_true=true_out, in_false=false_out, mask=cond, x=image)
            loss = layers.cross_entropy(input=prob, label=label)
Y
Yu Yang 已提交
59
            avg_loss = layers.mean(loss)
Y
Yu Yang 已提交
60

61 62
            optimizer = MomentumOptimizer(learning_rate=0.001, momentum=0.9)
            optimizer.minimize(avg_loss, startup_prog)
Y
Yu Yang 已提交
63 64 65 66

        train_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.mnist.train(), buf_size=8192),
67
            batch_size=10)
Y
Yu Yang 已提交
68 69 70 71

        place = core.CPUPlace()
        exe = Executor(place)

72
        exe.run(startup_prog)
Y
Yu Yang 已提交
73 74 75 76 77 78 79
        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for data in train_reader():
                x_data = np.array(map(lambda x: x[0], data)).astype("float32")
                y_data = np.array(map(lambda x: x[1], data)).astype("int64")
                y_data = np.expand_dims(y_data, axis=1)

80
                outs = exe.run(prog,
D
dzhwinter 已提交
81 82 83
                               feed={'x': x_data,
                                     'y': y_data},
                               fetch_list=[avg_loss])
Y
Yu Yang 已提交
84 85 86 87 88 89
                print outs[0]
                if outs[0] < 1.0:
                    return
        self.assertFalse(True)

    def test_ifelse(self):
90 91 92 93 94 95 96
        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            image = layers.data(name='x', shape=[784], dtype='float32')

            label = layers.data(name='y', shape=[1], dtype='int64')

97
            limit = layers.fill_constant(shape=[1], dtype='int64', value=5)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
            cond = layers.less_than(x=label, y=limit)
            ie = layers.IfElse(cond)

            with ie.true_block():
                true_image = ie.input(image)
                hidden = layers.fc(input=true_image, size=100, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                ie.output(prob)

            with ie.false_block():
                false_image = ie.input(image)
                hidden = layers.fc(input=false_image, size=200, act='tanh')
                prob = layers.fc(input=hidden, size=10, act='softmax')
                ie.output(prob)

            prob = ie()
            loss = layers.cross_entropy(input=prob[0], label=label)
Y
Yu Yang 已提交
115
            avg_loss = layers.mean(loss)
116 117 118

            optimizer = MomentumOptimizer(learning_rate=0.001, momentum=0.9)
            optimizer.minimize(avg_loss, startup_prog)
Y
Yu Yang 已提交
119 120 121 122 123 124 125 126
        train_reader = paddle.batch(
            paddle.reader.shuffle(
                paddle.dataset.mnist.train(), buf_size=8192),
            batch_size=200)

        place = core.CPUPlace()
        exe = Executor(place)

127
        exe.run(startup_prog)
Y
Yu Yang 已提交
128 129 130 131 132
        PASS_NUM = 100
        for pass_id in range(PASS_NUM):
            for data in train_reader():
                x_data = np.array(map(lambda x: x[0], data)).astype("float32")
                y_data = np.array(map(lambda x: x[1], data)).astype("int64")
D
dzhwinter 已提交
133
                y_data = y_data.reshape((y_data.shape[0], 1))
Y
Yu Yang 已提交
134

135
                outs = exe.run(prog,
D
dzhwinter 已提交
136 137 138
                               feed={'x': x_data,
                                     'y': y_data},
                               fetch_list=[avg_loss])
Y
Yu Yang 已提交
139 140 141 142 143 144
                print outs[0]
                if outs[0] < 1.0:
                    return
        self.assertFalse(True)


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
class TestIfElse(unittest.TestCase):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
        self.cond_value = 0.5
        self.data = np.random.rand(25, 1).astype(np.float32)

    def compare_ifelse_op_and_numpy(self, place):
        self.set_test_case()

        prog = Program()
        startup_prog = Program()
        with program_guard(prog, startup_prog):
            src = layers.data(name='data', shape=[1], dtype='float32')
            cond = layers.fill_constant(
                [1], dtype='float32', value=self.cond_value)
            ifcond = layers.less_than(x=src, y=cond)
            ie = layers.IfElse(ifcond)
            with ie.true_block():
                true_target = ie.input(src)
                ie.output(true_target)

            with ie.false_block():
                false_target = ie.input(src)
                ie.output(false_target)
            if_out = ie()
            out = layers.reduce_sum(if_out)

            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
            fetch_list = [out]
            o1, = exe.run(fluid.default_main_program(),
                          feed={'data': self.data},
                          fetch_list=[out])
            o2 = np.sum(self.data)
            self.assertTrue(
                np.allclose(
                    o1, o2, atol=1e-8),
                "IfElse result : " + str(o1) + "\n Numpy result :" + str(o2))

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

    def test_cuda(self):
        if not core.is_compiled_with_cuda():
            return
        self.compare_ifelse_op_and_numpy(fluid.CUDAPlace(0))


class TestIfElseTrueBranch(TestIfElse):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
        self.cond_value = 10.
        self.data = np.random.rand(25, 1).astype(np.float32)


class TestIfElseFalseBranch(TestIfElse):
    def set_test_case(self):
        # condiction is: self.data < self.cond_value
        self.cond_value = -10.
        self.data = np.random.rand(25, 1).astype(np.float32)


Y
Yu Yang 已提交
207
if __name__ == '__main__':
208
    unittest.main()