test_conditional_block.py 1.2 KB
Newer Older
Y
Yu Yang 已提交
1
import unittest
Q
Qiao Longfei 已提交
2 3
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.core as core
Y
Yu Yang 已提交
4
from paddle.v2.fluid.framework import default_startup_program, default_main_program
Q
Qiao Longfei 已提交
5 6
from paddle.v2.fluid.executor import Executor
from paddle.v2.fluid.backward import append_backward_ops
Y
Yu Yang 已提交
7 8 9 10 11
import numpy


class ConditionalBlock(unittest.TestCase):
    def test_forward(self):
F
fengjiayi 已提交
12
        data = layers.data(name='X', shape=[1], dtype='float32')
Y
Yu Yang 已提交
13 14 15 16 17 18 19 20 21
        data.stop_gradient = False
        cond = layers.ConditionalBlock(inputs=[data])
        out = layers.create_tensor(dtype='float32')
        with cond.block():
            hidden = layers.fc(input=data, size=10)
            layers.assign(hidden, out)

        cpu = core.CPUPlace()
        exe = Executor(cpu)
Y
Yu Yang 已提交
22
        exe.run(default_startup_program())
Y
Yu Yang 已提交
23

D
dzhwinter 已提交
24
        x = numpy.random.random(size=(10, 1)).astype('float32')
Y
Yu Yang 已提交
25

D
dzhwinter 已提交
26
        outs = exe.run(feed={'X': x}, fetch_list=[out])[0]
Y
Yu Yang 已提交
27 28 29
        print outs
        loss = layers.mean(x=out)
        append_backward_ops(loss=loss)
D
dzhwinter 已提交
30 31
        outs = exe.run(
            feed={'X': x},
Y
Yu Yang 已提交
32 33 34
            fetch_list=[
                default_main_program().block(0).var(data.name + "@GRAD")
            ])[0]
Y
Yu Yang 已提交
35 36 37 38 39
        print outs


if __name__ == '__main__':
    unittest.main()