local_train.py 2.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
B
barrierye 已提交
14
# pylint: disable=doc-string-missing
15 16 17 18 19 20 21 22 23 24
import os
import sys
import paddle
import logging
import paddle.fluid as fluid

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger("fluid")
logger.setLevel(logging.INFO)

M
MRXLT 已提交
25

26 27 28 29 30 31 32 33 34 35
def load_vocab(filename):
    vocab = {}
    with open(filename) as f:
        wid = 0
        for line in f:
            vocab[line.strip()] = wid
            wid += 1
    vocab["<unk>"] = len(vocab)
    return vocab

M
MRXLT 已提交
36

37
if __name__ == "__main__":
M
MRXLT 已提交
38 39
    from nets import lstm_net
    model_name = "imdb_lstm"
40 41 42
    vocab = load_vocab('imdb.vocab')
    dict_dim = len(vocab)

M
MRXLT 已提交
43 44
    data = fluid.layers.data(
        name="words", shape=[1], dtype="int64", lod_level=1)
45 46 47 48 49
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")

    dataset = fluid.DatasetFactory().create_dataset()
    filelist = ["train_data/%s" % x for x in os.listdir("train_data")]
    dataset.set_use_var([data, label])
M
MRXLT 已提交
50
    pipe_command = "python imdb_reader.py"
51
    dataset.set_pipe_command(pipe_command)
G
guru4elephant 已提交
52
    dataset.set_batch_size(128)
53 54
    dataset.set_filelist(filelist)
    dataset.set_thread(10)
55
    avg_cost, acc, prediction = lstm_net(data, label, dict_dim)
56 57 58 59 60
    optimizer = fluid.optimizer.SGD(learning_rate=0.01)
    optimizer.minimize(avg_cost)

    exe = fluid.Executor(fluid.CPUPlace())
    exe.run(fluid.default_startup_program())
G
guru4elephant 已提交
61
    epochs = 6
G
guru4elephant 已提交
62

G
guru4elephant 已提交
63 64
    import paddle_serving_client.io as serving_io

65
    for i in range(epochs):
M
MRXLT 已提交
66 67
        exe.train_from_dataset(
            program=fluid.default_main_program(), dataset=dataset, debug=False)
68
        logger.info("TRAIN --> pass: {}".format(i))
G
guru4elephant 已提交
69
        if i == 5:
70 71
            serving_io.save_model("{}_model".format(model_name),
                                  "{}_client_conf".format(model_name),
G
guru4elephant 已提交
72 73
                                  {"words": data}, {"prediction": prediction},
                                  fluid.default_main_program())