train_conv.py 5.8 KB
Newer Older
S
sidgoyal78 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2018 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.

from __future__ import print_function

17
import os
S
sidgoyal78 已提交
18 19 20 21
import paddle
import paddle.fluid as fluid
from functools import partial
import numpy as np
Y
Yu Yang 已提交
22 23 24 25 26 27 28 29 30 31 32
import sys

try:
    from paddle.fluid.contrib.trainer import *
    from paddle.fluid.contrib.inferencer import *
except ImportError:
    print(
        "In the fluid 1.0, the trainer and inferencer are moving to paddle.fluid.contrib",
        file=sys.stderr)
    from paddle.fluid.trainer import *
    from paddle.fluid.inferencer import *
S
sidgoyal78 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

CLASS_DIM = 2
EMB_DIM = 128
HID_DIM = 512
BATCH_SIZE = 128


def convolution_net(data, input_dim, class_dim, emb_dim, hid_dim):
    emb = fluid.layers.embedding(
        input=data, size=[input_dim, emb_dim], is_sparse=True)
    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")
    return prediction


def inference_program(word_dict):
    data = fluid.layers.data(
        name="words", shape=[1], dtype="int64", lod_level=1)

    dict_dim = len(word_dict)
    net = convolution_net(data, dict_dim, CLASS_DIM, EMB_DIM, HID_DIM)
    return net


def train_program(word_dict):
    prediction = inference_program(word_dict)
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
    avg_cost = fluid.layers.mean(cost)
    accuracy = fluid.layers.accuracy(input=prediction, label=label)
    return [avg_cost, accuracy]


def optimizer_func():
    return fluid.optimizer.Adagrad(learning_rate=0.002)


def train(use_cuda, train_program, params_dirname):
83 84
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    print("Loading IMDB word dict....")
S
sidgoyal78 已提交
85
    word_dict = paddle.dataset.imdb.word_dict()
86 87 88 89 90 91 92 93 94 95 96

    print("Reading training data....")
    train_reader = paddle.batch(
        paddle.reader.shuffle(
            paddle.dataset.imdb.train(word_dict), buf_size=25000),
        batch_size=BATCH_SIZE)

    print("Reading testing data....")
    test_reader = paddle.batch(
        paddle.dataset.imdb.test(word_dict), batch_size=BATCH_SIZE)

Y
yuyang 已提交
97
    trainer = Trainer(
S
sidgoyal78 已提交
98 99 100 101
        train_func=partial(train_program, word_dict),
        place=place,
        optimizer_func=optimizer_func)

102 103
    feed_order = ['words', 'label']

S
sidgoyal78 已提交
104
    def event_handler(event):
Y
yuyang 已提交
105
        if isinstance(event, EndStepEvent):
106 107 108
            if event.step % 10 == 0:
                avg_cost, acc = trainer.test(
                    reader=test_reader, feed_order=feed_order)
S
sidgoyal78 已提交
109

110 111
                print('Step {0}, Test Loss {1:0.2}, Acc {2:0.2}'.format(
                    event.step, avg_cost, acc))
S
sidgoyal78 已提交
112

113
                print("Step {0}, Epoch {1} Metrics {2}".format(
M
minqiyang 已提交
114 115
                    event.step, event.epoch, list(map(np.array,
                                                      event.metrics))))
116

Y
yuyang 已提交
117
        elif isinstance(event, EndEpochEvent):
118
            trainer.save_params(params_dirname)
S
sidgoyal78 已提交
119 120 121 122 123

    trainer.train(
        num_epochs=1,
        event_handler=event_handler,
        reader=train_reader,
124
        feed_order=feed_order)
S
sidgoyal78 已提交
125 126 127 128 129 130


def infer(use_cuda, inference_program, params_dirname=None):
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    word_dict = paddle.dataset.imdb.word_dict()

Y
yuyang 已提交
131
    inferencer = Inferencer(
S
sidgoyal78 已提交
132 133 134 135 136
        infer_func=partial(inference_program, word_dict),
        param_path=params_dirname,
        place=place)

    # Setup input by creating LoDTensor to represent sequence of words.
137 138
    # Here each word is the basic element of the LoDTensor and the shape of
    # each word (base_shape) should be [1] since it is simply an index to
S
sidgoyal78 已提交
139 140
    # look up for the corresponding word vector.
    # Suppose the length_based level of detail (lod) info is set to [[3, 4, 2]],
141 142 143 144
    # which has only one lod level. Then the created LoDTensor will have only
    # one higher level structure (sequence of words, or sentence) than the basic
    # element (word). Hence the LoDTensor will hold data for three sentences of
    # length 3, 4 and 2, respectively.
S
sidgoyal78 已提交
145
    # Note that lod info should be a list of lists.
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

    reviews_str = [
        'read the book forget the movie', 'this is a great movie',
        'this is very bad'
    ]
    reviews = [c.split() for c in reviews_str]

    UNK = word_dict['<unk>']
    lod = []
    for c in reviews:
        lod.append([word_dict.get(words, UNK) for words in c])

    base_shape = [[len(c) for c in lod]]

    tensor_words = fluid.create_lod_tensor(lod, base_shape, place)
S
sidgoyal78 已提交
161
    results = inferencer.infer({'words': tensor_words})
162 163 164 165

    for i, r in enumerate(results[0]):
        print("Predict probability of ", r[0], " to be positive and ", r[1],
              " to be negative for review \'", reviews_str[i], "\'")
S
sidgoyal78 已提交
166 167 168 169 170 171 172 173 174 175 176


def main(use_cuda):
    if use_cuda and not fluid.core.is_compiled_with_cuda():
        return
    params_dirname = "understand_sentiment_conv.inference.model"
    train(use_cuda, train_program, params_dirname)
    infer(use_cuda, inference_program, params_dirname)


if __name__ == '__main__':
W
Wang,Jeff 已提交
177
    use_cuda = False  # set to True if training with GPU
178
    main(use_cuda)