train_v2.py 6.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# 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.

H
hedaoyuan 已提交
15
import sys
H
hedaoyuan 已提交
16
import paddle.v2 as paddle
17 18


Y
Yu Yang 已提交
19
def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
20 21 22 23 24 25 26 27 28 29 30 31
    data = paddle.layer.data("word",
                             paddle.data_type.integer_value_sequence(input_dim))
    emb = paddle.layer.embedding(input=data, size=emb_dim)
    conv_3 = paddle.networks.sequence_conv_pool(
        input=emb, context_len=3, hidden_size=hid_dim)
    conv_4 = paddle.networks.sequence_conv_pool(
        input=emb, context_len=4, hidden_size=hid_dim)
    output = paddle.layer.fc(input=[conv_3, conv_4],
                             size=class_dim,
                             act=paddle.activation.Softmax())
    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
H
hedaoyuan 已提交
32 33 34 35 36 37 38
    return cost


def stacked_lstm_net(input_dim,
                     class_dim=2,
                     emb_dim=128,
                     hid_dim=512,
Y
Yu Yang 已提交
39
                     stacked_num=3):
H
hedaoyuan 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    """
    A Wrapper for sentiment classification task.
    This network uses bi-directional recurrent network,
    consisting three LSTM layers. This configure is referred to
    the paper as following url, but use fewer layrs.
        http://www.aclweb.org/anthology/P15-1109

    input_dim: here is word dictionary dimension.
    class_dim: number of categories.
    emb_dim: dimension of word embedding.
    hid_dim: dimension of hidden layer.
    stacked_num: number of stacked lstm-hidden layer.
    """
    assert stacked_num % 2 == 1

55 56 57
    layer_attr = paddle.attr.Extra(drop_rate=0.5)
    fc_para_attr = paddle.attr.Param(learning_rate=1e-3)
    lstm_para_attr = paddle.attr.Param(initial_std=0., learning_rate=1.)
H
hedaoyuan 已提交
58
    para_attr = [fc_para_attr, lstm_para_attr]
59
    bias_attr = paddle.attr.Param(initial_std=0., l2_rate=0.)
60 61 62 63 64 65 66 67 68 69 70 71
    relu = paddle.activation.Relu()
    linear = paddle.activation.Linear()

    data = paddle.layer.data("word",
                             paddle.data_type.integer_value_sequence(input_dim))
    emb = paddle.layer.embedding(input=data, size=emb_dim)

    fc1 = paddle.layer.fc(input=emb,
                          size=hid_dim,
                          act=linear,
                          bias_attr=bias_attr)
    lstm1 = paddle.layer.lstmemory(
H
hedaoyuan 已提交
72 73 74 75
        input=fc1, act=relu, bias_attr=bias_attr, layer_attr=layer_attr)

    inputs = [fc1, lstm1]
    for i in range(2, stacked_num + 1):
76 77 78 79 80 81
        fc = paddle.layer.fc(input=inputs,
                             size=hid_dim,
                             act=linear,
                             param_attr=para_attr,
                             bias_attr=bias_attr)
        lstm = paddle.layer.lstmemory(
H
hedaoyuan 已提交
82 83 84 85 86 87 88
            input=fc,
            reverse=(i % 2) == 0,
            act=relu,
            bias_attr=bias_attr,
            layer_attr=layer_attr)
        inputs = [fc, lstm]

89 90 91 92
    fc_last = paddle.layer.pooling(
        input=inputs[0], pooling_type=paddle.pooling.Max())
    lstm_last = paddle.layer.pooling(
        input=inputs[1], pooling_type=paddle.pooling.Max())
93 94 95 96 97
    output = paddle.layer.fc(input=[fc_last, lstm_last],
                             size=class_dim,
                             act=paddle.activation.Softmax(),
                             bias_attr=bias_attr,
                             param_attr=para_attr)
H
hedaoyuan 已提交
98

99 100
    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
101 102 103 104 105
    return cost


if __name__ == '__main__':
    # init
106
    paddle.init(use_gpu=False, log_clipping=True)
107

108
    #data
H
hedaoyuan 已提交
109
    print 'load dictionary...'
110
    word_dict = paddle.dataset.imdb.word_dict()
H
hedaoyuan 已提交
111 112
    dict_dim = len(word_dict)
    class_dim = 2
113 114 115 116 117 118 119 120
    train_reader = paddle.batch(
        paddle.reader.shuffle(
            lambda: paddle.dataset.imdb.train(word_dict), buf_size=1000),
        batch_size=100)
    test_reader = paddle.batch(
        lambda: paddle.dataset.imdb.test(word_dict), batch_size=100)

    feeding = {'word': 0, 'label': 1}
H
hedaoyuan 已提交
121

122
    # network config
H
hedaoyuan 已提交
123 124 125 126
    # Please choose the way to build the network
    # by uncommenting the corresponding line.
    cost = convolution_net(dict_dim, class_dim=class_dim)
    # cost = stacked_lstm_net(dict_dim, class_dim=class_dim, stacked_num=3)
127 128 129 130

    # create parameters
    parameters = paddle.parameters.create(cost)

H
hedaoyuan 已提交
131
    # create optimizer
H
hedaoyuan 已提交
132 133
    adam_optimizer = paddle.optimizer.Adam(
        learning_rate=2e-3,
134
        gradient_clipping_threshold=0.003,
H
hedaoyuan 已提交
135 136
        regularization=paddle.optimizer.L2Regularization(rate=8e-4),
        model_average=paddle.optimizer.ModelAverage(average_window=0.5))
137

H
hedaoyuan 已提交
138
    # End batch and end pass event handler
139 140
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
H
hedaoyuan 已提交
141
            if event.batch_id % 100 == 0:
H
hedaoyuan 已提交
142
                print "\nPass %d, Batch %d, Cost %f, %s" % (
143
                    event.pass_id, event.batch_id, event.cost, event.metrics)
H
hedaoyuan 已提交
144 145 146
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
H
hedaoyuan 已提交
147
        if isinstance(event, paddle.event.EndPass):
148
            result = trainer.test(reader=test_reader, feeding=feeding)
H
hedaoyuan 已提交
149
            print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)
150

H
hedaoyuan 已提交
151
    # create trainer
152 153 154 155 156
    trainer = paddle.trainer.SGD(cost=cost,
                                 parameters=parameters,
                                 update_equation=adam_optimizer)

    trainer.train(
157
        reader=train_reader,
158
        event_handler=event_handler,
159 160
        feeding=feeding,
        num_passes=2)