local_train.py 2.2 KB
Newer Older
G
guru4elephant 已提交
1 2 3 4 5 6
from __future__ import print_function

from args import parse_args
import os
import paddle.fluid as fluid
import sys
G
guru4elephant 已提交
7
from network_conf import dnn_model
G
guru4elephant 已提交
8 9 10

dense_feature_dim = 13

G
guru4elephant 已提交
11

G
guru4elephant 已提交
12 13
def train():
    args = parse_args()
G
guru4elephant 已提交
14
    sparse_only = args.sparse_only
G
guru4elephant 已提交
15 16 17 18 19 20 21 22 23
    if not os.path.isdir(args.model_output_dir):
        os.mkdir(args.model_output_dir)
    dense_input = fluid.layers.data(
        name="dense_input", shape=[dense_feature_dim], dtype='float32')
    sparse_input_ids = [
        fluid.layers.data(name="C" + str(i), shape=[1], lod_level=1, dtype="int64")
        for i in range(1, 27)]
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')

G
guru4elephant 已提交
24 25 26 27
    #nn_input = None if sparse_only else dense_input
    nn_input = dense_input
    predict_y, loss, auc_var, batch_auc_var = dnn_model(
        nn_input, sparse_input_ids, label,
G
guru4elephant 已提交
28 29 30 31 32 33 34 35 36
        args.embedding_size, args.sparse_feature_dim)

    optimizer = fluid.optimizer.SGD(learning_rate=1e-4)
    optimizer.minimize(loss)

    exe = fluid.Executor(fluid.CPUPlace())
    exe.run(fluid.default_startup_program())
    dataset = fluid.DatasetFactory().create_dataset("InMemoryDataset")
    dataset.set_use_var([dense_input] + sparse_input_ids + [label])
G
guru4elephant 已提交
37

G
guru4elephant 已提交
38
    python_executable = "python"
G
guru4elephant 已提交
39 40 41
    pipe_command = "{} criteo_reader.py {}".format(
        python_executable, args.sparse_feature_dim)

G
guru4elephant 已提交
42 43 44 45
    dataset.set_pipe_command(pipe_command)
    dataset.set_batch_size(128)
    thread_num = 10
    dataset.set_thread(thread_num)
G
guru4elephant 已提交
46 47 48 49

    whole_filelist = ["raw_data/part-%d" % x for x in
                      range(len(os.listdir("raw_data")))]

G
guru4elephant 已提交
50 51 52 53 54
    dataset.set_filelist(whole_filelist[:thread_num])
    dataset.load_into_memory()

    epochs = 1
    for i in range(epochs):
G
guru4elephant 已提交
55 56 57
        exe.train_from_dataset(
            program=fluid.default_main_program(),
            dataset=dataset, debug=True)
G
guru4elephant 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71
        print("epoch {} finished".format(i))

    import paddle_serving_client.io as server_io
    feed_var_dict = {}
    for i, sparse in enumerate(sparse_input_ids):
        feed_var_dict["sparse_{}".format(i)] = sparse
    fetch_var_dict = {"prob": predict_y}

    server_io.save_model(
        "ctr_serving_model", "ctr_client_conf",
        feed_var_dict, fetch_var_dict, fluid.default_main_program())

if __name__ == '__main__':
    train()