-
Notifications
You must be signed in to change notification settings - Fork 3
/
data_utils.py
179 lines (147 loc) · 6.7 KB
/
data_utils.py
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import torch
from torch_geometric.data import Dataset, InMemoryDataset, Data
import os
from tqdm import tqdm
from torch_geometric.utils import dense_to_sparse
class NYCCab(InMemoryDataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.name = 'nyc_cab'
self.cleaned = False
self.graph_file = 'graphs.pt'
self.event_file = 'events.pt'
self.event_types_file = 'event_types.pt'
self.static_features_file = 'static_attrs.pt'
self.dynamic_features_file = 'dynamic_attrs.pt'
self.graph_count = 4464
super(NYCCab, self).__init__(root, transform, pre_transform)
@property
def raw_dir(self) -> str:
name = f'raw{"_cleaned" if self.cleaned else ""}'
return os.path.join(self.root, self.name, name)
@property
def processed_dir(self) -> str:
name = f'processed{"_cleaned" if self.cleaned else ""}'
return os.path.join(self.root, self.name, name)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return [self.graph_file, self.event_file, self.event_types_file, self.static_features_file, self.dynamic_features_file]
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
@property
def num_classes(self) -> int:
r"""Returns the number of classes in the dataset."""
return 2
def download(self):
pass
def process(self):
graphs = torch.load(os.path.join(self.raw_dir, self.graph_file))
labels = torch.load(os.path.join(self.raw_dir, self.event_file))
label_types = torch.load(os.path.join(self.raw_dir, self.event_types_file))
static_features = torch.load(os.path.join(self.raw_dir, self.static_features_file))
dynamic_features = torch.load(os.path.join(self.raw_dir, self.dynamic_features_file))
# TODO: please normalize features or graphs if it is necessary.
for i, g in tqdm(enumerate(graphs)):
edge_index, edge_weights = dense_to_sparse(g)
d = Data(edge_index=edge_index.clone(),
edge_weight=edge_weights.clone(),
x=torch.cat([static_features.clone(), dynamic_features[i].clone()], dim=1).float(),
y=labels[i].clone().long(),
# -1 for 0 labels (no event)
y_type=label_types[i].clone().long())
torch.save(d, os.path.join(self.processed_dir, f'data_{i}.pt'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
class TwitterWeather(InMemoryDataset):
def __init__(self, root, transform=None, pre_transform=None):
"""
root = Where the dataset should be stored. This folder is split
into raw_dir (downloaded dataset) and processed_dir (processed data).
"""
self.root = root
self.name = 'twitter_weather'
self.cleaned = False
self.graph_file = 'graphs.pt'
self.event_file = 'events.pt'
self.event_types_file = 'event_types.pt'
self.static_features_file = 'static_attrs.pt'
self.dynamic_features_file = 'dynamic_attrs.pt'
self.graph_count = 2557
super(TwitterWeather, self).__init__(root, transform, pre_transform)
@property
def raw_dir(self) -> str:
name = f'raw{"_cleaned" if self.cleaned else ""}'
return os.path.join(self.root, self.name, name)
@property
def processed_dir(self) -> str:
name = f'processed{"_cleaned" if self.cleaned else ""}'
return os.path.join(self.root, self.name, name)
@property
def raw_file_names(self):
""" If this file exists in raw_dir, the download is not triggered.
(The download func. is not implemented here)
"""
return [self.graph_file, self.event_file, self.event_types_file, self.static_features_file, self.dynamic_features_file]
@property
def processed_file_names(self):
""" If these files are found in processed_dir, processing is skipped"""
return [f'data_{i}.pt' for i in range(self.graph_count)]
@property
def num_classes(self) -> int:
r"""Returns the number of classes in the dataset."""
return 2
def download(self):
pass
def process(self):
graphs = torch.load(os.path.join(self.raw_dir, self.graph_file))
labels = torch.load(os.path.join(self.raw_dir, self.event_file))
label_types = torch.load(os.path.join(self.raw_dir, self.event_types_file))
static_features = torch.load(os.path.join(self.raw_dir, self.static_features_file))
dynamic_features = torch.load(os.path.join(self.raw_dir, self.dynamic_features_file))
# TODO: please normalize features or graphs if it is necessary.
for i, g in tqdm(enumerate(graphs)):
edge_index, edge_weights = dense_to_sparse(g)
d = Data(edge_index=edge_index.clone(),
edge_weight=edge_weights.clone(),
x=torch.cat([static_features.clone(), dynamic_features[i].clone()], dim=1).float(),
y=labels[i].clone().long(),
# -1 for 0 labels (no event)
y_type=label_types[i].clone().long())
torch.save(d, os.path.join(self.processed_dir, f'data_{i}.pt'))
def len(self):
return self.graph_count
def get(self, idx):
""" - Equivalent to __getitem__ in pytorch
- Is not needed for PyG's InMemoryDataset
"""
data = torch.load(os.path.join(self.processed_dir,
f'data_{idx}.pt'))
return data
def load_dataset(dataset_name):
if dataset_name == 'nyc_cab':
data = NYCCab(root='data/')
elif dataset_name == 'twitter_weather':
data = TwitterWeather(root='data/')
else:
raise NotImplementedError(f'Dataset: {dataset_name} is not implemented!')
return data
if __name__ == '__main__':
dataset = load_dataset('twitter_weather')
print(f'Size: {len(dataset)}')
print(f'Labels sum: {sum([graph.y for graph in dataset]) / len(dataset)}')