-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
220 lines (182 loc) · 6.85 KB
/
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
import pickle
from collections import defaultdict
import ipdb
class RedditDataset(Dataset):
def __init__(self,edges,u_to_idx,sr_to_idx,prefetch_to_gpu=False):
self.dataset = edges
self.u_to_idx = u_to_idx
self.sr_to_idx = sr_to_idx
self.prefetch_to_gpu = prefetch_to_gpu
self.edges = edges
def __len__(self):
return len(self.dataset)
def get_mapping(self,edge):
if edge[0].split('_')[0] == 'U':
user = torch.LongTensor([self.u_to_idx[edge[0]]])
sr = torch.LongTensor([self.sr_to_idx[edge[1]]])
else:
user = torch.LongTensor([self.u_to_idx[edge[1]]])
sr = torch.LongTensor([self.sr_to_idx[edge[0]]])
datum = torch.cat((user,sr),0)
return datum
def __getitem__(self, idx):
''' Always return [User, SR] '''
edge = self.dataset[idx]
if edge[0].split('_')[0] == 'U':
user = torch.LongTensor([self.u_to_idx[edge[0]]])
sr = torch.LongTensor([self.sr_to_idx[edge[1]]])
else:
user = torch.LongTensor([self.u_to_idx[edge[1]]])
sr = torch.LongTensor([self.sr_to_idx[edge[0]]])
datum = torch.cat((user,sr),0)
return datum
def shuffle(self):
data = self.dataset
np.random.shuffle(data)
class KBDataset(Dataset):
def __init__(self,data_split,prefetch_to_gpu=False):
self.prefetch_to_gpu = prefetch_to_gpu
self.dataset = np.ascontiguousarray(data_split)
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
return self.dataset[idx]
def shuffle(self):
if self.dataset.is_cuda:
self.dataset = self.dataset.cpu()
data = self.dataset
np.random.shuffle(data)
data = np.ascontiguousarray(data)
self.dataset = ltensor(data)
if self.prefetch_to_gpu:
self.dataset = self.dataset.cuda().contiguous()
class FBDataset(Dataset):
def __init__(self, path, prefetch_to_gpu=False):
self.prefetch_to_gpu = prefetch_to_gpu
self.dataset = np.ascontiguousarray(np.array(pickle.load(open(path, 'rb'))))
if prefetch_to_gpu:
self.dataset = torch.LongTensor(self.dataset).cuda()
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
return self.dataset[idx]
def shuffle(self):
if self.dataset.is_cuda:
self.dataset = self.dataset.cpu()
data = self.dataset.numpy()
np.random.shuffle(data)
data = np.ascontiguousarray(data)
self.dataset = torch.LongTensor(data)
if self.prefetch_to_gpu:
self.dataset = self.dataset.cuda().contiguous()
class NodeClassification(Dataset):
def __init__(self,data_split,prefetch_to_gpu=False):
self.prefetch_to_gpu = prefetch_to_gpu
self.dataset = np.ascontiguousarray(data_split)
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
return self.dataset[idx]
def shuffle(self):
if self.dataset.is_cuda:
self.dataset = self.dataset.cpu()
data = self.dataset
data = np.ascontiguousarray(data)
self.dataset = ltensor(data)
if self.prefetch_to_gpu:
self.dataset = self.dataset.cuda().contiguous()
class PredBias(Dataset):
def __init__(self,use_1M,movies,users,attribute,prefetch_to_gpu=False):
self.prefetch_to_gpu = prefetch_to_gpu
self.dataset = np.ascontiguousarray(movies)
self.users = users
self.groups = defaultdict(list)
if attribute == 'gender':
users_sex = self.users['sex']
self.num_groups = 2
[self.groups[val].append(ind) for ind,val in enumerate(users_sex)]
elif attribute == 'occupation':
users_occupation = self.users['occupation']
if use_1M:
[self.groups[val].append(ind) for ind,val in \
enumerate(users_occupation)]
self.num_groups = 21
else:
users_occupation_list = sorted(set(users_occupation))
occ_to_idx = {}
for i, occ in enumerate(users_occupation_list):
occ_to_idx[occ] = i
users_occupation = [occ_to_idx[occ] for occ in users_occupation]
elif attribute == 'random':
users_random = self.users['rand']
self.num_groups = 2
[self.groups[val].append(ind) for ind,val in enumerate(users_random)]
else:
users_age = self.users['age'].values
users_age_list = sorted(set(users_age))
if not use_1M:
bins = np.linspace(5, 75, num=15, endpoint=True)
inds = np.digitize(users_age, bins) - 1
self.users_sensitive = np.ascontiguousarray(inds)
else:
reindex = {1:0, 18:1, 25:2, 35:3, 45:4, 50:5, 56:6}
self.num_groups = 7
inds = [reindex.get(n, n) for n in users_age]
[self.groups[val].append(ind) for ind,val in enumerate(inds)]
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
return self.dataset[idx]
def shuffle(self):
if self.dataset.is_cuda:
self.dataset = self.dataset.cpu()
data = self.dataset
np.random.shuffle(data)
data = np.ascontiguousarray(data)
self.dataset = ltensor(data)
if self.prefetch_to_gpu:
self.dataset = self.dataset.cuda().contiguous()
def reddit_check_edges(edges):
print("Printing Bad Edges")
for edge in edges:
if edge[0].split('_')[0] == edge[1].split('_')[1]:
print(edge)
def reddit_mappings(nodes):
users, subreddits = [], []
for ent in nodes:
if ent.split('_')[0] == 'U':
users.append(ent)
else:
subreddits.append(ent)
user_to_idx, sr_to_idx = {},{}
for i, ent in enumerate(users):
user_to_idx[ent] = i
for j, sr in enumerate(subreddits):
sr_to_idx[sr] = j
return user_to_idx, sr_to_idx
def compute_rank(enrgs, target, mask_observed=None):
enrg = enrgs[target]
if mask_observed is not None:
mask_observed[target] = 0
enrgs = enrgs + 100*mask_observed
return (enrgs < enrg).sum() + 1
def create_or_append(d, k, v, v2np=None):
if v2np is None:
if k in d:
d[k].append(v)
else:
d[k] = [v]
else:
if k in d:
d[k].append(v2np(v))
else:
d[k] = [v2np(v)]
def to_multi_gpu(model):
cuda_stat = torch.cuda.is_available()
if cuda_stat:
model = torch.nn.DataParallel(model,\
device_ids=range(torch.cuda.device_count())).cuda()
return model