forked from chuckgu/Neural-Machine-Translation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.py
314 lines (254 loc) · 9.6 KB
/
preprocess.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#-*- coding: utf-8 -*-
'''
These preprocessing utils would greatly benefit
from a fast Cython rewrite.
'''
from __future__ import absolute_import
import string, sys
import numpy as np
from six.moves import range
from six.moves import zip
if sys.version_info < (3,):
maketrans = string.maketrans
else:
maketrans = str.maketrans
def base_filter():
f = string.punctuation
f = f.replace("'", '')
f += '\t\n'
return f
def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "):
'''prune: sequence of characters to filter out
'''
if lower:
text = text.lower()
text = text.translate(maketrans(filters, split*len(filters)))
seq = text.split(split)
return [_f for _f in seq if _f]
def one_hot(text, n, filters=base_filter(), lower=True, split=" "):
seq = text_to_word_sequence(text, filters=filters, lower=lower, split=split)
return [(abs(hash(w))%(n-1)+1) for w in seq]
class Tokenizer(object):
def __init__(self, nb_words=None, filters=base_filter(), lower=True, split=" "):
self.word_counts = {}
self.word_docs = {}
self.filters = filters
self.split = split
self.lower = lower
self.nb_words = nb_words
self.document_count = 0
self.maxlen=0
def fit_on_texts(self, texts):
'''
required before using texts_to_sequences or texts_to_matrix
@param texts: can be a list or a generator (for memory-efficiency)
'''
self.document_count = 0
for text in texts:
self.document_count += 1
seq = text_to_word_sequence(text, self.filters, self.lower, self.split)
for w in seq:
if w in self.word_counts:
self.word_counts[w] += 1
else:
self.word_counts[w] = 1
for w in set(seq):
if w in self.word_docs:
self.word_docs[w] += 1
else:
self.word_docs[w] = 1
wcounts = list(self.word_counts.items())
wcounts.sort(key = lambda x: x[1], reverse=True)
sorted_voc = [wc[0] for wc in wcounts]
self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc)+1)))))##amend
self.word_index['<eos>']=0
#self.word_index['UNK']=1
print "max words:"+str(len(self.word_index))
print "max sentences:"+str(self.document_count)
if self.nb_words is None:
self.nb_words=len(self.word_index)
print "nb_words:"+str(self.nb_words)
self.index_docs = {}
for w, c in list(self.word_docs.items()):
self.index_docs[self.word_index[w]] = c
def fit_on_sequences(self, sequences):
'''
required before using sequences_to_matrix
(if fit_on_texts was never called)
'''
self.document_count = len(sequences)
self.index_docs = {}
for seq in sequences:
seq = set(seq)
for i in seq:
if i not in self.index_docs:
self.index_docs[i] = 1
else:
self.index_docs[i] += 1
def texts_to_sequences(self, texts,batch_size=None,maxlen=100):
'''
Transform each text in texts in a sequence of integers.
Only top "nb_words" most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
Returns a list of sequences.
'''
if batch_size is None:
batch_size=self.document_count
print "batch_size:"+str(batch_size)
res = []
for vect in self.texts_to_sequences_generator(texts,maxlen):
res.append(vect)
if len(res) >= batch_size:
break
lengths = [len(s) for s in res]
print('max length of sentence: %i' %max(lengths))
return res
def texts_to_sequences_generator(self, texts,maxlen=100):
'''
Transform each text in texts in a sequence of integers.
Only top "nb_words" most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
Yields individual sequences.
'''
'''
if maxlen is None:
self.maxlen = np.max(lengths)
maxlen=self.maxlen
print('maximum number of words in a sentence: %i' %maxlen)
'''
nb_words = self.nb_words
for text in texts:
seq = text_to_word_sequence(text, self.filters, self.lower, self.split)
vect = []
k=0
for w in seq:
if k>=maxlen:break
i = self.word_index.get(w)
if i is not None:
if nb_words and i >= nb_words:
vect.append(1)
else:
vect.append(i)
else: vect.append(1)
k+=1
#vect.append(0)
yield vect
def texts_to_matrix(self, texts, mode="onehot",batch_size=None,maxlen=None):
'''
modes: binary, count, tfidf, freq
'''
sequences = self.texts_to_sequences(texts,batch_size,maxlen=maxlen)
return self.sequences_to_matrix(sequences, mode=mode)
def sequences_to_matrix(self, sequences, mode="onehot"):
'''
modes: binary, count, tfidf, freq
'''
maxlen=self.maxlen
if not self.nb_words:
if self.word_index:
nb_words = len(self.word_index)
else:
raise Exception("Specify a dimension (nb_words argument), or fit on some text data first")
else:
nb_words = self.nb_words
if mode == "tfidf" and not self.document_count:
raise Exception("Fit the Tokenizer on some data before using tfidf mode")
X = np.zeros((len(sequences),maxlen,nb_words))
for i, seq in enumerate(sequences):
if not seq:
pass
counts = {}
position=np.zeros((nb_words,maxlen))
k=0
for j in seq:
if k>=maxlen:break
if j >= nb_words:
pass
if j not in counts:
counts[j] = 1.
else:
counts[j] += 1
position[j][k]=1.
k+=1
for j, c in list(counts.items()):
if mode == "count":
X[i][j] = c
elif mode == "freq":
X[i][j] = c/len(seq)
elif mode == "binary":
X[i][j] = 1
elif mode == "onehot":
for l,po in enumerate(position[j]):
if po:
X[i][l][j] = 1
elif mode == "tfidf":
tf = np.log(c/len(seq))
df = (1 + np.log(1 + self.index_docs.get(j, 0)/(1 + self.document_count)))
X[i][j] = tf / df
else:
raise Exception("Unknown vectorization mode: " + str(mode))
return X
def sequences_to_text(self, sequences):
vect = []
for n, w in enumerate(sequences):
if w==0:break
i = self.word_index.keys()[self.word_index.values().index(w)]
#print i
if i is not None:vect.append(i)
return vect
def matrix_to_sequences(self, matrix):
seq = np.argmax(matrix, axis = -1)
return seq
def matrix_to_text(self, matrix):
seq=self.matrix_to_sequences(matrix)
text=self.sequences_to_text(seq)
return text
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='post', value=0.):
"""
Pad each sequence to the same length:
the length of the longuest sequence.
If maxlen is provided, any sequence longer
than maxlen is truncated to maxlen. Truncation happens off either the beginning (default) or
the end of the sequence.
Supports post-padding and pre-padding (default).
"""
lengths = [len(s) for s in sequences]
nb_samples = len(sequences)
if maxlen is None:
maxlen = np.max(lengths)
print maxlen
x = (np.ones((nb_samples, maxlen)) * value).astype(dtype)
for idx, s in enumerate(sequences):
if truncating == 'pre':
trunc = s[-maxlen:]
elif truncating == 'post':
trunc = s[:maxlen]
else:
raise ValueError("Truncating type '%s' not understood" % padding)
if padding == 'post':
x[idx, :len(trunc)] = trunc
elif padding == 'pre':
x[idx, -len(trunc):] = trunc
else:
raise ValueError("Padding type '%s' not understood" % padding)
return x
if __name__ == "__main__":
n_batch=9000
text=[]
with open("word.txt") as f:
for line in f:
text.append(line)
input=Tokenizer()
input.fit_on_texts(text)
train_x=input.texts_to_sequences(text)
a=input.sequences_to_text(train_x[58])
'''
text=[]
with open("news-commentary-v9.fr-en.fr") as f:
for line in f:
text.append(line)
output=Tokenizer(500)
output.fit_on_texts(text)
train_y=output.texts_to_sequences(text,n_batch)
train_y=pad_sequences(train_y)
'''