test_conditional_block.py 1.8 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.
Y
Yu Yang 已提交
14
import unittest
Q
Qiao Longfei 已提交
15 16
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.core as core
Y
Yu Yang 已提交
17
from paddle.v2.fluid.framework import default_startup_program, default_main_program
Q
Qiao Longfei 已提交
18
from paddle.v2.fluid.executor import Executor
F
fengjiayi 已提交
19
from paddle.v2.fluid.backward import append_backward
Y
Yu Yang 已提交
20 21 22 23 24
import numpy


class ConditionalBlock(unittest.TestCase):
    def test_forward(self):
F
fengjiayi 已提交
25
        data = layers.data(name='X', shape=[1], dtype='float32')
Y
Yu Yang 已提交
26 27 28 29 30 31 32 33 34
        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 已提交
35
        exe.run(default_startup_program())
Y
Yu Yang 已提交
36

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

D
dzhwinter 已提交
39
        outs = exe.run(feed={'X': x}, fetch_list=[out])[0]
Y
Yu Yang 已提交
40 41
        print outs
        loss = layers.mean(x=out)
F
fengjiayi 已提交
42
        append_backward(loss=loss)
D
dzhwinter 已提交
43 44
        outs = exe.run(
            feed={'X': x},
Y
Yu Yang 已提交
45 46 47
            fetch_list=[
                default_main_program().block(0).var(data.name + "@GRAD")
            ])[0]
Y
Yu Yang 已提交
48 49 50 51 52
        print outs


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