reading_data.py 7.02 KB
Newer Older
1
import os
2
3
4
5
import pickle
import random
import time

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
6
7
import dgl

8
9
10
import numpy as np
import scipy.sparse as sp
import torch
11
12
13
14
15
16
from dgl.data.utils import (
    _get_dgl_url,
    download,
    extract_archive,
    get_download_dir,
)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
17
from torch.utils.data import DataLoader
18

19
20

def ReadTxtNet(file_path="", undirected=True):
21
    """Read the txt network file.
22
23
24
25
26
27
28
29
30
31
    Notations: The network is unweighted.

    Parameters
    ----------
    file_path str : path of network file
    undirected bool : whether the edges are undirected

    Return
    ------
    net dict : a dict recording the connections in the graph
32
    node2id dict : a dict mapping the nodes to their embedding indices
33
34
    id2node dict : a dict mapping nodes embedding indices to the nodes
    """
35
    if file_path == "youtube" or file_path == "blog":
36
37
        name = file_path
        dir = get_download_dir()
38
39
40
41
42
43
44
45
        zip_file_path = "{}/{}.zip".format(dir, name)
        download(
            _get_dgl_url(
                os.path.join("dataset/DeepWalk/", "{}.zip".format(file_path))
            ),
            path=zip_file_path,
        )
        extract_archive(zip_file_path, "{}/{}".format(dir, name))
46
47
48
49
50
51
52
53
54
55
56
57
58
        file_path = "{}/{}/{}-net.txt".format(dir, name, name)

    node2id = {}
    id2node = {}
    cid = 0

    src = []
    dst = []
    weight = []
    net = {}
    with open(file_path, "r") as f:
        for line in f.readlines():
            tup = list(map(int, line.strip().split(" ")))
59
60
61
62
            assert len(tup) in [
                2,
                3,
            ], "The format of network file is unrecognizable."
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            if len(tup) == 3:
                n1, n2, w = tup
            elif len(tup) == 2:
                n1, n2 = tup
                w = 1
            if n1 not in node2id:
                node2id[n1] = cid
                id2node[cid] = n1
                cid += 1
            if n2 not in node2id:
                node2id[n2] = cid
                id2node[cid] = n2
                cid += 1

            n1 = node2id[n1]
            n2 = node2id[n2]
            if n1 not in net:
                net[n1] = {n2: w}
                src.append(n1)
                dst.append(n2)
                weight.append(w)
            elif n2 not in net[n1]:
                net[n1][n2] = w
                src.append(n1)
                dst.append(n2)
                weight.append(w)
89

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            if undirected:
                if n2 not in net:
                    net[n2] = {n1: w}
                    src.append(n2)
                    dst.append(n1)
                    weight.append(w)
                elif n1 not in net[n2]:
                    net[n2][n1] = w
                    src.append(n2)
                    dst.append(n1)
                    weight.append(w)

    print("node num: %d" % len(net))
    print("edge num: %d" % len(src))
    assert max(net.keys()) == len(net) - 1, "error reading net, quit"

106
    sm = sp.coo_matrix((np.array(weight), (src, dst)), dtype=np.float32)
107
108
109

    return net, node2id, id2node, sm

110

111
def net2graph(net_sm):
112
    """Transform the network to DGL graph
113

114
    Return
115
116
117
118
119
120
121
122
123
124
    ------
    G DGLGraph : graph by DGL
    """
    start = time.time()
    G = dgl.DGLGraph(net_sm)
    end = time.time()
    t = end - start
    print("Building DGLGraph in %.2fs" % t)
    return G

125

126
127
128
129
def make_undirected(G):
    G.add_edges(G.edges()[1], G.edges()[0])
    return G

130

131
def find_connected_nodes(G):
132
    nodes = torch.nonzero(G.out_degrees(), as_tuple=False).squeeze(-1)
133
134
    return nodes

135

136
class LineDataset:
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    def __init__(
        self,
        net_file,
        batch_size,
        num_samples,
        negative=5,
        gpus=[0],
        fast_neg=True,
        ogbl_name="",
        load_from_ogbl=False,
        ogbn_name="",
        load_from_ogbn=False,
    ):
        """This class has the following functions:
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        1. Transform the txt network file into DGL graph;
        2. Generate random walk sequences for the trainer;
        3. Provide the negative table if the user hopes to sample negative
        nodes according to nodes' degrees;

        Parameter
        ---------
        net_file str : path of the dgl network file
        walk_length int : number of nodes in a sequence
        window_size int : context window size
        num_walks int : number of walks for each node
        batch_size int : number of node sequences in each batch
        negative int : negative samples for each positve node pair
        fast_neg bool : whether do negative sampling inside a batch
        """
        self.batch_size = batch_size
        self.negative = negative
        self.num_samples = num_samples
        self.num_procs = len(gpus)
        self.fast_neg = fast_neg

        if load_from_ogbl:
173
174
175
            assert (
                len(gpus) == 1
            ), "ogb.linkproppred is not compatible with multi-gpu training."
176
            from load_dataset import load_from_ogbl_with_name
177

178
179
            self.G = load_from_ogbl_with_name(ogbl_name)
        elif load_from_ogbn:
180
181
182
            assert (
                len(gpus) == 1
            ), "ogb.linkproppred is not compatible with multi-gpu training."
183
            from load_dataset import load_from_ogbn_with_name
184

185
186
187
188
189
190
            self.G = load_from_ogbn_with_name(ogbn_name)
        else:
            self.G = dgl.load_graphs(net_file)[0][0]
        self.G = make_undirected(self.G)
        print("Finish reading graph")

191
        self.num_nodes = self.G.num_nodes()
192
193

        start = time.time()
194
        seeds = np.random.choice(
195
            np.arange(self.G.num_edges()), self.num_samples, replace=True
196
197
198
199
200
201
        )  # edge index
        self.seeds = torch.split(
            torch.LongTensor(seeds),
            int(np.ceil(self.num_samples / self.num_procs)),
            0,
        )
202
203
204
205
206
207
208
209
210
211
212
213
        end = time.time()
        t = end - start
        print("generate %d samples in %.2fs" % (len(seeds), t))

        # negative table for true negative sampling
        self.valid_nodes = find_connected_nodes(self.G)
        if not fast_neg:
            node_degree = self.G.out_degrees(self.valid_nodes).numpy()
            node_degree = np.power(node_degree, 0.75)
            node_degree /= np.sum(node_degree)
            node_degree = np.array(node_degree * 1e8, dtype=np.int)
            self.neg_table = []
214

215
216
217
218
219
220
221
            for idx, node in enumerate(self.valid_nodes):
                self.neg_table += [node] * node_degree[idx]
            self.neg_table_size = len(self.neg_table)
            self.neg_table = np.array(self.neg_table, dtype=np.long)
            del node_degree

    def create_sampler(self, i):
222
        """create random walk sampler"""
223
224
225
226
227
228
        return EdgeSampler(self.G, self.seeds[i])

    def save_mapping(self, map_file):
        with open(map_file, "wb") as f:
            pickle.dump(self.node2id, f)

229

230
231
232
233
class EdgeSampler(object):
    def __init__(self, G, seeds):
        self.G = G
        self.seeds = seeds
234
235
236
237
        self.edges = torch.cat(
            (self.G.edges()[0].unsqueeze(0), self.G.edges()[1].unsqueeze(0)), 0
        ).t()

238
    def sample(self, seeds):
239
        """seeds torch.LongTensor : a batch of indices of edges"""
240
        return self.edges[torch.LongTensor(seeds)]