test_conditional_block.py 1.2 KB
Newer Older
Y
Yu Yang 已提交
1
import unittest
Q
Qiao Longfei 已提交
2 3 4 5 6
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.core as core
from paddle.v2.fluid.framework import g_startup_program, g_main_program
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 22 23
        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)
        exe.run(g_startup_program)

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 32
        outs = exe.run(
            feed={'X': x},
            fetch_list=[g_main_program.block(0).var(data.name + "@GRAD")])[0]
Y
Yu Yang 已提交
33 34 35 36 37
        print outs


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