-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebKB.py
More file actions
148 lines (122 loc) · 5.04 KB
/
WebKB.py
File metadata and controls
148 lines (122 loc) · 5.04 KB
1
2
3
4
5
6
7
8
9
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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import os.path as osp
from os import makedirs
from typing import Callable, List, Optional
import numpy as np
import torch
from torch_geometric.data import Data, InMemoryDataset, download_url
from torch_geometric.data.dataset import _repr
from torch_geometric.utils import coalesce
class WebKB(InMemoryDataset):
r"""The WebKB datasets used in the
`"Geom-GCN: Geometric Graph Convolutional Networks"
<https://openreview.net/forum?id=S1e2agrFvS>`_ paper.
Nodes represent web pages and edges represent hyperlinks between them.
Node features are the bag-of-words representation of web pages.
The task is to classify the nodes into one of the five categories, student,
project, course, staff, and faculty.
Args:
root (str): Root directory where the dataset should be saved.
name (str): The name of the dataset (:obj:`"Cornell"`, :obj:`"Texas"`,
:obj:`"Wisconsin"`).
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object and returns a transformed
version. The data object will be transformed before every access.
(default: :obj:`None`)
pre_transform (callable, optional): A function/transform that takes in
an :obj:`torch_geometric.data.Data` object and returns a
transformed version. The data object will be transformed before
being saved to disk. (default: :obj:`None`)
**STATS:**
.. list-table::
:widths: 10 10 10 10 10
:header-rows: 1
* - Name
- #nodes
- #edges
- #features
- #classes
* - Cornell
- 183
- 298
- 1,703
- 5
* - Texas
- 183
- 325
- 1,703
- 5
* - Wisconsin
- 251
- 515
- 1,703
- 5
"""
url = 'https://raw.githubusercontent.com/graphdml-uiuc-jlu/geom-gcn/master'
def __init__(
self,
root: str,
name: str,
transform: Optional[Callable] = None,
pre_transform: Optional[Callable] = None,
):
self.name = name.lower()
assert self.name in ['cornell', 'texas', 'wisconsin']
super().__init__(root, transform, pre_transform)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_dir(self) -> str:
return osp.join(self.root, self.name, 'raw')
@property
def processed_dir(self) -> str:
return osp.join(self.root, self.name, 'processed')
@property
def raw_file_names(self) -> List[str]:
out = ['out1_node_feature_label.txt', 'out1_graph_edges.txt']
out += [f'{self.name}_split_0.6_0.2_{i}.npz' for i in range(10)]
return out
@property
def processed_file_names(self) -> str:
return 'data.pt'
def download(self):
# for f in self.raw_file_names[:2]:
# download_url(f'{self.url}/new_data/{self.name}/{f}', self.raw_dir)
# for f in self.raw_file_names[2:]:
# download_url(f'{self.url}/splits/{f}', self.raw_dir)
pass
def process(self):
with open(self.raw_paths[0], 'r') as f:
data = f.read().split('\n')[1:-1]
x = [[float(v) for v in r.split('\t')[1].split(',')] for r in data]
x = torch.tensor(x, dtype=torch.float)
y = [int(r.split('\t')[2]) for r in data]
y = torch.tensor(y, dtype=torch.long)
with open(self.raw_paths[1], 'r') as f:
data = f.read().split('\n')[1:-1]
data = [[int(v) for v in r.split('\t')] for r in data]
edge_index = torch.tensor(data, dtype=torch.long).t().contiguous()
edge_index = coalesce(edge_index, num_nodes=x.size(0))
train_masks, val_masks, test_masks = [], [], []
for f in self.raw_paths[2:]:
tmp = np.load(f)
train_masks += [torch.from_numpy(tmp['train_mask']).to(torch.bool)]
val_masks += [torch.from_numpy(tmp['val_mask']).to(torch.bool)]
test_masks += [torch.from_numpy(tmp['test_mask']).to(torch.bool)]
train_mask = torch.stack(train_masks, dim=1)
val_mask = torch.stack(val_masks, dim=1)
test_mask = torch.stack(test_masks, dim=1)
data = Data(x=x, edge_index=edge_index, y=y, train_mask=train_mask,
val_mask=val_mask, test_mask=test_mask)
data = data if self.pre_transform is None else self.pre_transform(data)
torch.save(self.collate([data]), self.processed_paths[0])
# print('process successfully!')
# makedirs(self.processed_dir)
# self.process()
# path = osp.join(self.processed_dir, 'pre_transform.pt')
# torch.save(_repr(self.pre_transform), path)
# path = osp.join(self.processed_dir, 'pre_filter.pt')
# torch.save(_repr(self.pre_filter), path)
def __repr__(self) -> str:
return f'{self.name}()'
# if __name__ == "__main__":
# dataset = WebKB(root='WebKB', name='Wisconsin')
# dataset.process()