forked from lucaswiser/USF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.py
235 lines (218 loc) · 9.01 KB
/
reader.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
from collections import deque
import numpy as np
import os
import pickle
import logging
import nltk
import sys
from threading import Thread
logger = logging.getLogger("USF.reader")
logger.setLevel(logging.DEBUG)
neg_train_dir = 'aclImdb/train/neg/'
pos_train_dir = 'aclImdb/train/pos/'
neg_test_dir = 'aclImdb/test/neg/'
pos_test_dir = 'aclImdb/test/pos/'
class TokReader():
def __init__(self, sent_len, batch_size, tok_map, random=True, rounded=True, training=True, limit=None):
assert sent_len % 2 == 0, "Sent len must be an even number"
logger.info("Instantiating TokReader object: %s"%("training" if training else "valid"))
self.sent_len = sent_len
self.batch_size = batch_size
self.tok_map = tok_map
self.random = random
self.rounded = rounded
self.training = training
self.limit = limit
self._load()
def _load(self):
logger.info("Loading reviews")
if self.training:
pos_files = [pos_train_dir + f for f in os.listdir(pos_train_dir)]
neg_files = [neg_train_dir + f for f in os.listdir(neg_train_dir)]
else:
pos_files = [pos_test_dir + f for f in os.listdir(pos_test_dir)]
neg_files = [neg_test_dir + f for f in os.listdir(neg_test_dir)]
data = []
labels = []
lengths = []
for i,f in enumerate(pos_files+neg_files):
with open(f) as _:
sents = _.read().split("<br /><br />")
for s in sents:
index = [self.tok_map.get(t, 1) for t in nltk.tokenize.word_tokenize(s.lower())]
lengths.append(min(len(index), self.sent_len))
fill = self.sent_len - len(index)
if fill > 0:
index.extend([0]*fill)
elif fill < 0:
index = index[:self.sent_len]
parsed_label = int((f.split("_")[-1]).split(".")[0])
data.append(index)
labels.append(parsed_label // 6 if self.rounded else parsed_label)
if self.limit and i > self.limit:
break
self.data = data
self.labels = labels
self.lengths = lengths
def _shuffle(self):
logger.info("Shuffling input data")
inds = list(range(len(self.data)))
if self.random:
np.random.shuffle(inds)
inds = deque(inds)
return inds
def get_sents(self):
inds = self._shuffle()
while len(inds) >= self.batch_size: #A tiny part of the train set won't be produced
x = []
y = []
lengths = []
for i in range(self.batch_size):
sampled_index = inds.popleft()
x.append(self.data[sampled_index])
y.append(self.labels[sampled_index])
lengths.append(self.lengths[sampled_index])
yield np.array(x), np.array(y).reshape((-1,1)), np.array(lengths)
class CharReader():
def __init__(self, sent_len, batch_size, char_map, random=True, rounded=True, training=True, limit=None):
assert sent_len % 2 == 0, "Sent len must be an even number"
logger.info("Instantiating CharReader object: %s"%("training" if training else "valid"))
self.sent_len = sent_len
self.batch_size = batch_size
self.char_map = char_map
self.random = random
self.rounded = rounded
self.training = training
self.limit = limit
self._load()
def _load(self):
logger.info("Loading reviews")
if self.training:
pos_files = [pos_train_dir + f for f in os.listdir(pos_train_dir)]
neg_files = [neg_train_dir + f for f in os.listdir(neg_train_dir)]
else:
pos_files = [pos_test_dir + f for f in os.listdir(pos_test_dir)]
neg_files = [neg_test_dir + f for f in os.listdir(neg_test_dir)]
data = []
labels = []
lengths = []
for i,f in enumerate(pos_files+neg_files):
with open(f) as _:
sents = _.read().split("<br /><br />")
for s in sents:
index = [self.char_map.get(c, 1) for c in s]
lengths.append(min(len(index), self.sent_len))
fill = self.sent_len - len(index)
if fill > 0:
index.extend([0]*fill)
elif fill < 0:
index = index[:self.sent_len]
parsed_label = int((f.split("_")[-1]).split(".")[0])
data.append(index)
labels.append(parsed_label // 6 if self.rounded else parsed_label)
if self.limit and i > self.limit:
break
self.data = data
self.labels = labels
self.lengths = lengths
def _shuffle(self):
logger.info("Shuffling input data")
inds = list(range(len(self.data)))
if self.random:
np.random.shuffle(inds)
inds = deque(inds)
return inds
def get_sents(self):
inds = self._shuffle()
while len(inds) >= self.batch_size: #A tiny part of the train set won't be produced
x = []
y = []
lengths = []
for i in range(self.batch_size):
sampled_index = inds.popleft()
x.append(self.data[sampled_index])
y.append(self.labels[sampled_index])
lengths.append(self.lengths[sampled_index])
yield np.array(x), np.array(y).reshape((-1,1)), np.array(lengths)
class CharTokReader():
def __init__(self, sent_len, word_len, batch_size, char_map, random=True,
rounded=True, training=True, limit=None):
assert sent_len % 2 == 0, "Sent len must be an even number"
assert word_len % 2 == 0, "Word len must be an even number"
logger.info("Instantiating CharReader object: %s"%("training" if training else "valid"))
self.sent_len = sent_len
self.word_len = word_len
self.batch_size = batch_size
self.char_map = char_map
self.random = random
self.rounded = rounded
self.training = training
self.limit = limit
self._load()
def _load(self):
logger.info("Loading reviews")
if self.training:
pos_files = [pos_train_dir + f for f in os.listdir(pos_train_dir)]
neg_files = [neg_train_dir + f for f in os.listdir(neg_train_dir)]
else:
pos_files = [pos_test_dir + f for f in os.listdir(pos_test_dir)]
neg_files = [neg_test_dir + f for f in os.listdir(neg_test_dir)]
data = []
labels = []
lengths = []
wordlengths = []
for i,f in enumerate(pos_files+neg_files):
with open(f) as _:
sents = _.read().split("<br /><br />")
for s in sents:
toks = s.split()
index = [[2] + [self.char_map.get(c, 1) for c in _t] + [3] for _t in toks]
lengths.append(min(len(index), self.sent_len))
temp = []
for i, word in enumerate(index):
temp.append(min(len(word), self.word_len))
wordfill = self.word_len - len(word)
if wordfill > 0:
word.extend([0]*wordfill)
elif wordfill < 0:
split = self.word_len // 2
index[i] = word[:split] + word[-split:]
fill = self.sent_len - len(index)
if fill > 0:
index.extend([[0]*self.word_len]*fill)
temp.extend([0]*fill)
elif fill < 0:
index = index[:self.sent_len]
temp = temp[:self.sent_len]
parsed_label = int((f.split("_")[-1]).split(".")[0])
data.append(index)
labels.append(parsed_label // 6 if self.rounded else parsed_label)
wordlengths.append(temp)
if self.limit and i > self.limit:
break
self.data = data
self.labels = labels
self.lengths = lengths
self.wordlengths = wordlengths
print("Loaded %s reviews"%len(data))
def _shuffle(self):
logger.info("Shuffling input data")
inds = list(range(len(self.data)))
if self.random:
np.random.shuffle(inds)
inds = deque(inds)
return inds
def get_sents(self):
inds = self._shuffle()
while len(inds) >= self.batch_size: #A tiny part of the train set won't be produced
x = []
y = []
lengths = []
wordlengths = []
for i in range(self.batch_size):
sampled_index = inds.popleft()
x.extend(self.data[sampled_index])
y.append(self.labels[sampled_index])
lengths.append(self.lengths[sampled_index])
wordlengths.extend(self.wordlengths[sampled_index])
yield np.array(x), np.array(y).reshape((-1,1)), np.array(lengths), np.array(wordlengths)