-
Notifications
You must be signed in to change notification settings - Fork 0
/
lazy_parser.py
93 lines (75 loc) · 2.89 KB
/
lazy_parser.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
# +
import os
import sys
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
class MultiLabelDataset(Dataset):
def __init__(self, filename):
self.build(filename)
def build(self, filename):
with open(filename) as f:
metadata = f.readline().split()
self.N = int(metadata[0])
self.D = int(metadata[1])
self.L = int(metadata[2])
self.max_L = 0
self.max_D = 0
self.data = list()
for idx in range(self.N):
items = f.readline().split()
labels = [int(x) for x in items[0].split(",")]
self.max_L = max(self.max_L, len(labels))
ids = list()
for fdx in range(1, len(items), 1):
fid, fv = items[fdx].split(":")
ids.append( int(fid) )
self.max_D = max(self.max_D, len(ids))
self.data.append( [torch.from_numpy(np.asarray(x)) for x in [labels, ids]] )
if idx % 100000 == 0:
print(idx)
def pad(self, item, width, value):
result = torch.zeros(width).long()
result.fill_(value)
result[:len(item)] = item
return result
def __len__(self):
return self.N
def __getitem__(self, idx):
labels, data = self.data[idx]
return self.pad(labels, self.max_L, -1), self.pad(data, self.max_D, self.D)
class ValidDataset(Dataset):
def __init__(self, filename):
self.build(filename)
def build(self, filename):
with open(filename) as f:
metadata = f.readline().split()
self.N = int(int(metadata[0]) * 0.025)
#self.N = int(metadata[0])
self.D = int(metadata[1])
self.L = int(metadata[2])
self.max_L = 0
self.max_D = 0
self.data = list()
for idx in range(self.N):
items = f.readline().split()
labels = [int(x) for x in items[0].split(",")]
self.max_L = max(self.max_L, len(labels))
ids = list()
for fdx in range(1, len(items), 1):
fid, fv = items[fdx].split(":")
ids.append( int(fid) )
self.max_D = max(self.max_D, len(ids))
self.data.append( [torch.from_numpy(np.asarray(x)) for x in [labels, ids]] )
if idx % 100000 == 0:
print(idx)
def pad(self, item, width, value):
result = torch.zeros(width).long()
result.fill_(value)
result[:len(item)] = item
return result
def __len__(self):
return self.N
def __getitem__(self, idx):
labels, data = self.data[idx]
return self.pad(labels, self.max_L, -1), self.pad(data, self.max_D, self.D)