utils.py 2.3 KB
Newer Older
1
import os
R
root 已提交
2 3
import sys
import time
G
gmcather 已提交
4 5 6 7 8
import numpy as np

import paddle.fluid as fluid
import paddle.v2 as paddle

G
gmcather 已提交
9

R
root 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
def to_lodtensor(data, place):
    """
    convert to LODtensor
    """
    seq_lens = [len(seq) for seq in data]
    cur_len = 0
    lod = [cur_len]
    for l in seq_lens:
        cur_len += l
        lod.append(cur_len)
    flattened_data = np.concatenate(data, axis=0).astype("int64")
    flattened_data = flattened_data.reshape([len(flattened_data), 1])
    res = fluid.LoDTensor()
    res.set(flattened_data, place)
    res.set_lod([lod])
    return res


def load_vocab(filename):
    """
    load imdb vocabulary
    """
    vocab = {}
    with open(filename) as f:
        wid = 0
        for line in f:
            vocab[line.strip()] = wid
            wid += 1
    vocab["<unk>"] = len(vocab)
    return vocab


def data2tensor(data, place):
    """
    data2tensor
    """
G
gmcather 已提交
46
    input_seq = to_lodtensor(map(lambda x: x[0], data), place)
R
root 已提交
47 48 49 50 51
    y_data = np.array(map(lambda x: x[1], data)).astype("int64")
    y_data = y_data.reshape([-1, 1])
    return {"words": input_seq, "label": y_data}


G
gmcather 已提交
52 53 54 55
def prepare_data(data_type="imdb",
                 self_dict=False,
                 batch_size=128,
                 buf_size=50000):
R
root 已提交
56 57 58 59 60 61 62 63 64 65 66 67
    """
    prepare data
    """
    if self_dict:
        word_dict = load_vocab(data_type + ".vocab")
    else:
        if data_type == "imdb":
            word_dict = paddle.dataset.imdb.word_dict()
        else:
            raise RuntimeError("No such dataset")

    if data_type == "imdb":
68
        if "CE_MODE_X" in os.environ:
69 70
            train_reader = paddle.batch(
                paddle.dataset.imdb.train(word_dict), batch_size=batch_size)
G
gmcather 已提交
71

72 73 74 75 76 77 78 79 80 81 82 83
            test_reader = paddle.batch(
                paddle.dataset.imdb.test(word_dict), batch_size=batch_size)
        else:
            train_reader = paddle.batch(
                paddle.reader.shuffle(
                    paddle.dataset.imdb.train(word_dict), buf_size=buf_size),
                batch_size=batch_size)

            test_reader = paddle.batch(
                paddle.reader.shuffle(
                    paddle.dataset.imdb.test(word_dict), buf_size=buf_size),
                batch_size=batch_size)
R
root 已提交
84 85 86 87
    else:
        raise RuntimeError("no such dataset")

    return word_dict, train_reader, test_reader