train.py 5.9 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.

D
dzhwinter 已提交
15
import sys, os
16 17
import paddle.v2 as paddle

D
dzhwinter 已提交
18
with_gpu = os.getenv('WITH_GPU', '0') != '0'
19

H
Helin Wang 已提交
20

Y
Yi Wang 已提交
21
def convolution_net(input_dim, class_dim=2, emb_dim=128, hid_dim=128):
22 23 24 25 26 27 28
    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)
29 30
    output = paddle.layer.fc(
        input=[conv_3, conv_4], size=class_dim, act=paddle.activation.Softmax())
31 32
    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
F
fengjiayi 已提交
33
    return cost, output
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55


def stacked_lstm_net(input_dim,
                     class_dim=2,
                     emb_dim=128,
                     hid_dim=512,
                     stacked_num=3):
    """
    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

H
hedaoyuan 已提交
56 57
    fc_para_attr = paddle.attr.Param(learning_rate=1e-3)
    lstm_para_attr = paddle.attr.Param(initial_std=0., learning_rate=1.)
58
    para_attr = [fc_para_attr, lstm_para_attr]
H
hedaoyuan 已提交
59
    bias_attr = paddle.attr.Param(initial_std=0., l2_rate=0.)
60 61 62 63 64 65 66
    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)

67 68
    fc1 = paddle.layer.fc(
        input=emb, size=hid_dim, act=linear, bias_attr=bias_attr)
F
Format  
fengjiayi 已提交
69
    lstm1 = paddle.layer.lstmemory(input=fc1, act=relu, bias_attr=bias_attr)
70 71 72

    inputs = [fc1, lstm1]
    for i in range(2, stacked_num + 1):
73 74 75 76 77 78
        fc = paddle.layer.fc(
            input=inputs,
            size=hid_dim,
            act=linear,
            param_attr=para_attr,
            bias_attr=bias_attr)
79
        lstm = paddle.layer.lstmemory(
F
Format  
fengjiayi 已提交
80
            input=fc, reverse=(i % 2) == 0, act=relu, bias_attr=bias_attr)
81 82
        inputs = [fc, lstm]

H
hedaoyuan 已提交
83 84 85 86
    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())
87 88 89 90 91 92
    output = paddle.layer.fc(
        input=[fc_last, lstm_last],
        size=class_dim,
        act=paddle.activation.Softmax(),
        bias_attr=bias_attr,
        param_attr=para_attr)
93 94 95

    lbl = paddle.layer.data("label", paddle.data_type.integer_value(2))
    cost = paddle.layer.classification_cost(input=output, label=lbl)
F
fengjiayi 已提交
96
    return cost, output
97 98 99 100


if __name__ == '__main__':
    # init
D
dzhwinter 已提交
101
    paddle.init(use_gpu=with_gpu)
102 103 104 105 106 107

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

H
hedaoyuan 已提交
115
    feeding = {'word': 0, 'label': 1}
116 117 118 119

    # network config
    # Please choose the way to build the network
    # by uncommenting the corresponding line.
F
fengjiayi 已提交
120 121
    [cost, output] = convolution_net(dict_dim, class_dim=class_dim)
    # [cost, output] = stacked_lstm_net(dict_dim, class_dim=class_dim, stacked_num=3)
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

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

    # create optimizer
    adam_optimizer = paddle.optimizer.Adam(
        learning_rate=2e-3,
        regularization=paddle.optimizer.L2Regularization(rate=8e-4),
        model_average=paddle.optimizer.ModelAverage(average_window=0.5))

    # End batch and end pass event handler
    def event_handler(event):
        if isinstance(event, paddle.event.EndIteration):
            if event.batch_id % 100 == 0:
                print "\nPass %d, Batch %d, Cost %f, %s" % (
                    event.pass_id, event.batch_id, event.cost, event.metrics)
            else:
                sys.stdout.write('.')
                sys.stdout.flush()
        if isinstance(event, paddle.event.EndPass):
F
fengjiayi 已提交
142 143 144
            with open('./params_pass_%d.tar' % event.pass_id, 'w') as f:
                parameters.to_tar(f)

H
hedaoyuan 已提交
145
            result = trainer.test(reader=test_reader, feeding=feeding)
146 147 148
            print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

    # create trainer
149 150
    trainer = paddle.trainer.SGD(
        cost=cost, parameters=parameters, update_equation=adam_optimizer)
F
fengjiayi 已提交
151 152 153 154
    # Save the inference topology to protobuf.
    inference_topology = paddle.topology.Topology(layers=output)
    with open("./inference_topology.pkl", 'wb') as f:
        inference_topology.serialize_for_inference(f)
155 156 157 158

    trainer.train(
        reader=train_reader,
        event_handler=event_handler,
H
hedaoyuan 已提交
159
        feeding=feeding,
F
fengjiayi 已提交
160
        num_passes=20)