ctr_dataset_reader.py 5.9 KB
Newer Older
T
tangwei12 已提交
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
T
tangwei12 已提交
18 19
import logging
import tarfile
20
import tempfile
21
import random
22
import warnings
T
tangwei12 已提交
23 24

import paddle
25
import paddle.distributed.fleet as fleet
T
tangwei12 已提交
26 27 28 29 30 31 32 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

logging.basicConfig()
logger = logging.getLogger("paddle")
logger.setLevel(logging.INFO)

DATA_URL = "http://paddle-ctr-data.bj.bcebos.com/avazu_ctr_data.tgz"
DATA_MD5 = "c11df99fbd14e53cd4bfa6567344b26e"
"""
avazu_ctr_data/train.txt
avazu_ctr_data/infer.txt
avazu_ctr_data/test.txt
avazu_ctr_data/data.meta.txt
"""


def download_file():
    file_name = "avazu_ctr_data"
    path = paddle.dataset.common.download(DATA_URL, file_name, DATA_MD5)

    dir_name = os.path.dirname(path)
    text_file_dir_name = os.path.join(dir_name, file_name)

    if not os.path.exists(text_file_dir_name):
        tar = tarfile.open(path, "r:gz")
        tar.extractall(dir_name)
    return text_file_dir_name


def load_dnn_input_record(sent):
    return list(map(int, sent.split()))


def load_lr_input_record(sent):
    res = []
    for _ in [x.split(':') for x in sent.split()]:
61
        res.append(int(_[0]) % 10000)
T
tangwei12 已提交
62 63 64
    return res


1
123malin 已提交
65
class CtrReader(object):
66

1
123malin 已提交
67 68 69 70
    def __init__(self):
        pass

    def _reader_creator(self, filelist):
71

72 73 74
        def get_rand(low=0.0, high=1.0):
            return random.random()

1
123malin 已提交
75 76 77 78
        def reader():
            for file in filelist:
                with open(file, 'r') as f:
                    for line in f:
79 80 81 82 83 84
                        if get_rand() < 0.05:
                            fs = line.strip().split('\t')
                            dnn_input = load_dnn_input_record(fs[0])
                            lr_input = load_lr_input_record(fs[1])
                            click = [int(fs[2])]
                            yield [dnn_input] + [lr_input] + [click]
1
123malin 已提交
85 86 87 88

        return reader


89
class DatasetCtrReader(fleet.MultiSlotDataGenerator):
90

T
tangwei12 已提交
91
    def generate_sample(self, line):
92

93 94 95
        def get_rand(low=0.0, high=1.0):
            return random.random()

T
tangwei12 已提交
96
        def iter():
97
            if get_rand() < 0.05:
98 99 100 101 102 103 104
                fs = line.strip().split('\t')
                dnn_input = load_dnn_input_record(fs[0])
                lr_input = load_lr_input_record(fs[1])
                click = [int(fs[2])]
                yield ("dnn_data", dnn_input), \
                      ("lr_data", lr_input), \
                      ("click", click)
T
tangwei12 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

        return iter


def prepare_data():
    """
    load data meta info from path, return (dnn_input_dim, lr_input_dim)
    """
    file_dir_name = download_file()
    meta_file_path = os.path.join(file_dir_name, 'data.meta.txt')
    train_file_path = os.path.join(file_dir_name, 'train.txt')
    with open(meta_file_path, "r") as f:
        lines = f.readlines()
    err_info = "wrong meta format"
    assert len(lines) == 2, err_info
120
    assert 'dnn_input_dim:' in lines[0] and 'lr_input_dim:' in lines[1], err_info
T
tangwei12 已提交
121 122 123 124 125 126
    res = map(int, [_.split(':')[1] for _ in lines])
    res = list(res)
    dnn_input_dim = res[0]
    lr_input_dim = res[1]
    logger.info('dnn input dim: %d' % dnn_input_dim)
    logger.info('lr input dim: %d' % lr_input_dim)
127

T
tangwei12 已提交
128 129 130
    return dnn_input_dim, lr_input_dim, train_file_path


131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
def gen_fake_line(dnn_data_num=7,
                  dnn_data_range=1e5,
                  lr_data_num=5,
                  lr_data_range=1e5):
    line = ""

    # for deep data
    for index in range(dnn_data_num):
        data = str(random.randint(0, dnn_data_range - 1))
        if index < dnn_data_num - 1:
            data += " "
        line += data
    line += "\t"

    # for wide data
    for index in range(lr_data_num):
        data = str(random.randint(0, lr_data_range - 1)) + ":" + str(1)
        if index < lr_data_num - 1:
            data += " "
        line += data
    line += "\t"

    # for label
    line += str(random.randint(0, 1))
    line += "\n"
    return line


1
123malin 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
def gen_zero_line(dnn_data_num=7, lr_data_num=5):
    # for embedding zero padding test
    line = ""

    # for deep data
    for index in range(dnn_data_num):
        data = str(0)
        if index < dnn_data_num - 1:
            data += " "
        line += data
    line += "\t"

    # for wide data
    for index in range(lr_data_num):
        data = str(0) + ":" + str(1)
        if index < lr_data_num - 1:
            data += " "
        line += data
    line += "\t"

    # for label
    line += str(random.randint(0, 1))
    line += "\n"
    return line


185
def prepare_fake_data(file_nums=4, file_lines=500):
186 187 188 189 190 191 192 193 194 195 196
    """
    Create fake data with same type as avazu_ctr_data
    """
    file_dir = tempfile.mkdtemp()
    warnings.warn("Fake data write in {}".format(file_dir))
    for file_index in range(file_nums):
        with open(
                os.path.join(file_dir,
                             "ctr_train_data_part_{}".format(file_index)),
                'w+') as fin:
            file_str = ""
1
123malin 已提交
197 198
            file_str += gen_zero_line()
            for line_index in range(file_lines - 1):
199 200
                file_str += gen_fake_line()
            fin.write(file_str)
201 202
            warnings.warn(
                "Write done ctr_train_data_part_{}".format(file_index))
203 204 205 206 207 208 209

    file_list = [os.path.join(file_dir, x) for x in os.listdir(file_dir)]
    assert len(file_list) == file_nums

    return file_list


T
tangwei12 已提交
210 211 212
if __name__ == "__main__":
    pairwise_reader = DatasetCtrReader()
    pairwise_reader.run_from_stdin()