evaluate_reader.py 5.4 KB
Newer Older
T
tangwei 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
M
add gnn  
malin10 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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.
T
tangwei 已提交
14

M
add gnn  
malin10 已提交
15 16
import copy
import random
T
tangwei 已提交
17 18 19

import numpy as np

C
Chengmo 已提交
20
from paddlerec.core.reader import ReaderBase
21
from paddlerec.core.utils import envs
M
add gnn  
malin10 已提交
22 23


C
Chengmo 已提交
24
class Reader(ReaderBase):
M
add gnn  
malin10 已提交
25
    def init(self):
M
malin10 已提交
26 27
        self.batch_size = envs.get_global_env(
            "dataset.dataset_infer.batch_size")
T
for mat  
tangwei 已提交
28

M
add gnn  
malin10 已提交
29 30 31 32 33 34
        self.input = []
        self.length = None

    def base_read(self, files):
        res = []
        for f in files:
T
for mat  
tangwei 已提交
35
            with open(f, "r") as fin:
M
add gnn  
malin10 已提交
36
                for line in fin:
T
for mat  
tangwei 已提交
37
                    line = line.strip().split('\t')
T
tangwei 已提交
38 39
                    res.append(
                        tuple([map(int, line[0].split(',')), int(line[1])]))
M
add gnn  
malin10 已提交
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
        return res

    def make_data(self, cur_batch, batch_size):
        cur_batch = [list(e) for e in cur_batch]
        max_seq_len = 0
        for e in cur_batch:
            max_seq_len = max(max_seq_len, len(e[0]))
        last_id = []
        for e in cur_batch:
            last_id.append(len(e[0]) - 1)
            e[0] += [0] * (max_seq_len - len(e[0]))

        max_uniq_len = 0
        for e in cur_batch:
            max_uniq_len = max(max_uniq_len, len(np.unique(e[0])))

        items, adj_in, adj_out, seq_index, last_index = [], [], [], [], []
        mask, label = [], []

        id = 0
        for e in cur_batch:
            node = np.unique(e[0])
            items.append(node.tolist() + (max_uniq_len - len(node)) * [0])
            adj = np.zeros((max_uniq_len, max_uniq_len))

            for i in np.arange(len(e[0]) - 1):
                if e[0][i + 1] == 0:
                    break
                u = np.where(node == e[0][i])[0][0]
                v = np.where(node == e[0][i + 1])[0][0]
                adj[u][v] = 1

            u_deg_in = np.sum(adj, 0)
            u_deg_in[np.where(u_deg_in == 0)] = 1
            adj_in.append(np.divide(adj, u_deg_in).transpose())

            u_deg_out = np.sum(adj, 1)
            u_deg_out[np.where(u_deg_out == 0)] = 1
            adj_out.append(np.divide(adj.transpose(), u_deg_out).transpose())

T
tangwei 已提交
80 81
            seq_index.append([[id, np.where(node == i)[0][0]] for i in e[0]])
            last_index.append([id, np.where(node == e[0][last_id[id]])[0][0]])
M
add gnn  
malin10 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
            label.append(e[1] - 1)
            mask.append([[1] * (last_id[id] + 1) + [0] *
                         (max_seq_len - last_id[id] - 1)])
            id += 1

        items = np.array(items).astype("int64").reshape((batch_size, -1))
        seq_index = np.array(seq_index).astype("int32").reshape(
            (batch_size, -1, 2))
        last_index = np.array(last_index).astype("int32").reshape(
            (batch_size, 2))
        adj_in = np.array(adj_in).astype("float32").reshape(
            (batch_size, max_uniq_len, max_uniq_len))
        adj_out = np.array(adj_out).astype("float32").reshape(
            (batch_size, max_uniq_len, max_uniq_len))
        mask = np.array(mask).astype("float32").reshape((batch_size, -1, 1))
        label = np.array(label).astype("int64").reshape((batch_size, 1))
        return zip(items, seq_index, last_index, adj_in, adj_out, mask, label)

    def batch_reader(self, batch_size, batch_group_size, train=True):
        def _reader():
            random.shuffle(self.input)
            group_remain = self.length % batch_group_size
T
tangwei 已提交
104 105 106 107
            for bg_id in range(0, self.length - group_remain,
                               batch_group_size):
                cur_bg = copy.deepcopy(self.input[bg_id:bg_id +
                                                  batch_group_size])
M
add gnn  
malin10 已提交
108
                if train:
T
tangwei 已提交
109 110
                    cur_bg = sorted(
                        cur_bg, key=lambda x: len(x[0]), reverse=True)
M
add gnn  
malin10 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
                for i in range(0, batch_group_size, batch_size):
                    cur_batch = cur_bg[i:i + batch_size]
                    yield self.make_data(cur_batch, batch_size)

            if group_remain == 0:
                return
            remain_data = copy.deepcopy(self.input[-group_remain:])
            if train:
                remain_data = sorted(
                    remain_data, key=lambda x: len(x[0]), reverse=True)
            for i in range(0, group_remain, batch_size):
                if i + batch_size <= group_remain:
                    cur_batch = remain_data[i:i + batch_size]
                    yield self.make_data(cur_batch, batch_size)
                else:
                    # Due to fixed batch_size, discard the remaining ins
                    return
T
for mat  
tangwei 已提交
128 129 130
                    # cur_batch = remain_data[i:]
                    # yield self.make_data(cur_batch, group_remain % batch_size)

M
add gnn  
malin10 已提交
131
        return _reader
T
for mat  
tangwei 已提交
132

M
add gnn  
malin10 已提交
133 134 135 136 137 138 139 140
    def generate_batch_from_trainfiles(self, files):
        self.input = self.base_read(files)
        self.length = len(self.input)
        return self.batch_reader(self.batch_size, self.batch_size * 20, False)

    def generate_sample(self, line):
        def data_iter():
            yield []
T
for mat  
tangwei 已提交
141

M
add gnn  
malin10 已提交
142
        return data_iter