test_understand_sentiment.py 5.5 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 unittest
16
import paddle.v2.fluid as fluid
17 18
import paddle.v2 as paddle
import contextlib
19 20
import math
import sys
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46


def convolution_net(data, label, input_dim, class_dim=2, emb_dim=32,
                    hid_dim=32):
    emb = fluid.layers.embedding(input=data, size=[input_dim, emb_dim])
    conv_3 = fluid.nets.sequence_conv_pool(
        input=emb,
        num_filters=hid_dim,
        filter_size=3,
        act="tanh",
        pool_type="sqrt")
    conv_4 = fluid.nets.sequence_conv_pool(
        input=emb,
        num_filters=hid_dim,
        filter_size=4,
        act="tanh",
        pool_type="sqrt")
    prediction = fluid.layers.fc(input=[conv_3, conv_4],
                                 size=class_dim,
                                 act="softmax")
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
    avg_cost = fluid.layers.mean(x=cost)
    adam_optimizer = fluid.optimizer.Adam(learning_rate=0.002)
    adam_optimizer.minimize(avg_cost)
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
    return avg_cost, accuracy
Q
QI JUN 已提交
47 48


Y
Yu Yang 已提交
49 50 51
def stacked_lstm_net(data,
                     label,
                     input_dim,
Q
QI JUN 已提交
52 53 54 55 56 57
                     class_dim=2,
                     emb_dim=128,
                     hid_dim=512,
                     stacked_num=3):
    assert stacked_num % 2 == 1

58
    emb = fluid.layers.embedding(input=data, size=[input_dim, emb_dim])
Q
QI JUN 已提交
59 60 61
    # add bias attr

    # TODO(qijun) linear act
62 63
    fc1 = fluid.layers.fc(input=emb, size=hid_dim)
    lstm1, cell1 = fluid.layers.dynamic_lstm(input=fc1, size=hid_dim)
Q
QI JUN 已提交
64 65 66 67

    inputs = [fc1, lstm1]

    for i in range(2, stacked_num + 1):
68 69
        fc = fluid.layers.fc(input=inputs, size=hid_dim)
        lstm, cell = fluid.layers.dynamic_lstm(
Q
QI JUN 已提交
70 71 72
            input=fc, size=hid_dim, is_reverse=(i % 2) == 0)
        inputs = [fc, lstm]

73 74
    fc_last = fluid.layers.sequence_pool(input=inputs[0], pool_type='max')
    lstm_last = fluid.layers.sequence_pool(input=inputs[1], pool_type='max')
Q
QI JUN 已提交
75

76 77 78 79 80 81
    prediction = fluid.layers.fc(input=[fc_last, lstm_last],
                                 size=class_dim,
                                 act='softmax')
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
    avg_cost = fluid.layers.mean(x=cost)
    adam_optimizer = fluid.optimizer.Adam(learning_rate=0.002)
Y
Yu Yang 已提交
82
    adam_optimizer.minimize(avg_cost)
83 84
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
    return avg_cost, accuracy
Q
QI JUN 已提交
85

86 87 88 89 90 91 92

def main(word_dict, net_method, use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return

    BATCH_SIZE = 128
    PASS_NUM = 5
Q
QI JUN 已提交
93 94 95
    dict_dim = len(word_dict)
    class_dim = 2

Y
Yu Yang 已提交
96 97 98
    data = fluid.layers.data(
        name="words", shape=[1], dtype="int64", lod_level=1)
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")
99
    cost, acc_out = net_method(
Y
Yu Yang 已提交
100
        data, label, input_dim=dict_dim, class_dim=class_dim)
Q
QI JUN 已提交
101 102 103 104 105

    train_data = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.imdb.train(word_dict), buf_size=1000),
        batch_size=BATCH_SIZE)
106
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
107
    exe = fluid.Executor(place)
Y
Yu Yang 已提交
108
    feeder = fluid.DataFeeder(feed_list=[data, label], place=place)
Q
QI JUN 已提交
109

110
    exe.run(fluid.default_startup_program())
Q
QI JUN 已提交
111 112 113

    for pass_id in xrange(PASS_NUM):
        for data in train_data():
Y
Yu Yang 已提交
114 115 116
            cost_val, acc_val = exe.run(fluid.default_main_program(),
                                        feed=feeder.feed(data),
                                        fetch_list=[cost, acc_out])
117 118 119
            print("cost=" + str(cost_val) + " acc=" + str(acc_val))
            if cost_val < 0.4 and acc_val > 0.8:
                return
120 121
            if math.isnan(float(cost_val)):
                sys.exit("got NaN loss, training failed.")
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    raise AssertionError("Cost is too large for {0}".format(
        net_method.__name__))


class TestUnderstandSentiment(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.word_dict = paddle.dataset.imdb.word_dict()

    @contextlib.contextmanager
    def new_program_scope(self):
        prog = fluid.Program()
        startup_prog = fluid.Program()
        scope = fluid.core.Scope()
        with fluid.scope_guard(scope):
            with fluid.program_guard(prog, startup_prog):
                yield

    def test_conv_cpu(self):
        with self.new_program_scope():
            main(self.word_dict, net_method=convolution_net, use_cuda=False)

    def test_stacked_lstm_cpu(self):
        with self.new_program_scope():
            main(self.word_dict, net_method=stacked_lstm_net, use_cuda=False)

    def test_conv_gpu(self):
        with self.new_program_scope():
            main(self.word_dict, net_method=convolution_net, use_cuda=True)

    def test_stacked_lstm_gpu(self):
        with self.new_program_scope():
            main(self.word_dict, net_method=stacked_lstm_net, use_cuda=True)
Q
QI JUN 已提交
155 156 157


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