test_conditional_block.py 1.8 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.

Y
Yu Yang 已提交
15
import unittest
Q
Qiao Longfei 已提交
16 17
import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.core as core
Y
Yu Yang 已提交
18
from paddle.v2.fluid.framework import default_startup_program, default_main_program
Q
Qiao Longfei 已提交
19
from paddle.v2.fluid.executor import Executor
F
fengjiayi 已提交
20
from paddle.v2.fluid.backward import append_backward
Y
Yu Yang 已提交
21 22 23 24 25
import numpy


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

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

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


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