-
Notifications
You must be signed in to change notification settings - Fork 8
/
tokenizer.py
210 lines (176 loc) · 8.04 KB
/
tokenizer.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
import collections
from keras.preprocessing.sequence import pad_sequences
import pickle
import numpy as np
# 0 is reserved
# make UNK token something
# make vocab size a requirement on creation
class Tokenizer(object):
def __init__(self):
self.word_count = collections.Counter()
self.w2i = {}
self.i2w = {}
self.oov_index = None
self.vocab_size = None
self.vectors = {}
def save(self, path):
pickle.dump(self, open(path, 'wb'))
def load(self, path):
return pickle.load(open(path, 'rb'))
def train(self, texts, vocab_size):
if len(self.word_count) != 0:
raise Exception("To update existing tokenizer with new vocabulary, run update() or update_from_file()")
# takes a list of strings that are space delimited into tokens
for sent in texts:
for w in sent.split():
self.word_count[w] += 1
self.vocab_size = vocab_size
# Easily changed but vocab size is essentially defining your max index
# 0 is reserved and UNK is reserved so you will get vocab_size-2 to get
# indices from 0-(vocab_size-1) i.e. vocab_size = 50, we get indices 0-49
for count, w in enumerate(self.word_count.most_common(self.vocab_size-2)):
self.w2i[w[0]] = count+1
self.i2w[count+1] = w[0]
self.oov_index = min([self.vocab_size-1, len(self.word_count)+1])
self.vocab_size = self.oov_index+1
self.w2i['<UNK>'] = self.oov_index
self.w2i['<NULL>'] = 0
self.i2w[0] = '<NULL>'
self.i2w[self.oov_index] = '<UNK>'
def train_from_file(self, path, vocab_size):
if len(self.word_count) != 0:
raise Exception("To update existing tokenizer with new vocabulary, run update() or update_from_file()")
# This is for our file representation of "fid, text\n"
self.vocab_size = vocab_size
for line in open(path):##questions
tmp = [x.strip() for x in line.split(',')]
# takes a list of strings that are space delimited into tokens
fid = tmp[0]
sent = tmp[1]
for w in sent.split():
self.word_count[w] += 1
# Easily changed but vocab size is essentially defining your max index
# 0 is reserved and UNK is reserved so you will get vocab_size-2 to get
# indices from 0-(vocab_size-1) i.e. vocab_size = 50, we get indices 0-49
for count, w in enumerate(self.word_count.most_common(self.vocab_size-2)):
self.w2i[w[0]] = count+1
self.i2w[count+1] = w[0]
self.oov_index = min([self.vocab_size-1, len(self.word_count)+1])
self.vocab_size = self.oov_index+1
self.w2i['<UNK>'] = self.oov_index
self.w2i['<NULL>'] = 0
self.i2w[0] = '<NULL>'
self.i2w[self.oov_index] = '<UNK>'
def update(self, texts):
# takes a list of strings that are space delimited into tokens
for sent in texts:
for w in sent.split():
self.word_count[w] += 1
# reset w2i and i2w for new vocab
self.w2i = {}
self.i2w = {}
# Easily changed but vocab size is essentially defining your max index
# 0 is reserved and UNK is reserved so you will get vocab_size-2 to get
# indices from 0-(vocab_size-1) i.e. vocab_size = 50, we get indices 0-49
for count, w in enumerate(self.word_count.most_common(self.vocab_size-2)):
self.w2i[w[0]] = count+1
self.i2w[count+1] = w[0]
self.oov_index = min([self.vocab_size-1, len(self.word_count)+1])
self.vocab_size = self.oov_index+1
self.w2i['<UNK>'] = self.oov_index
self.w2i['<NULL>'] = 0
self.i2w[0] = '<NULL>'
self.i2w[self.oov_index] = '<UNK>'
def update_from_file(self, path):
# takes a list of strings that are space delimited into tokens
for line in open(path):
tmp = [x.strip() for x in line.split(',')]
# takes a list of strings that are space delimited into tokens
fid = tmp[0]
sent = tmp[1]
for w in sent.split():
self.word_count[w] += 1
# reset w2i and i2w for new vocab
self.w2i = {}
self.i2w = {}
# Easily changed but vocab size is essentially defining your max index
# 0 is reserved and UNK is reserved so you will get vocab_size-2 to get
# indices from 0-(vocab_size-1) i.e. vocab_size = 50, we get indices 0-49
for count, w in enumerate(self.word_count.most_common(self.vocab_size-2)):
self.w2i[w[0]] = count+1
self.i2w[count+1] = w[0]
self.oov_index = min([self.vocab_size-1, len(self.word_count)+1])
self.vocab_size = self.oov_index+1
self.w2i['<UNK>'] = self.oov_index
self.w2i['<NULL>'] = 0
self.i2w[0] = '<NULL>'
self.i2w[self.oov_index] = '<UNK>'
def set_vocab_size(self, vocab_size):
self.vocab_size = vocab_size
# reset w2i and i2w for new vocab
self.w2i = {}
self.i2w = {}
# Easily changed but vocab size is essentially defining your max index
# 0 is reserved and UNK is reserved so you will get vocab_size-2 to get
# indices from 0-(vocab_size-1) i.e. vocab_size = 50, we get indices 0-49
for count, w in enumerate(self.word_count.most_common(self.vocab_size-2)):
self.w2i[w[0]] = count+1
self.i2w[count+1] = w[0]
self.oov_index = min([self.vocab_size-1, len(self.word_count)+1])
self.w2i['<UNK>'] = self.oov_index
self.w2i['<NULL>'] = 0
self.i2w[0] = '<NULL>'
self.i2w[self.oov_index] = '<UNK>'
def texts_to_sequences(self, texts, maxlen=None, padding='post', truncating='post', value=0):
if len(self.word_count) == 0:
raise Exception("Tokenizer has not been trained, no words in vocabulary.")
# takes a list of strings that are space delimited into tokens
# all_seq = list()
# for sent in texts:
# seq = []
# for w in sent.split():
# try:
# seq.append(self.w2i[w])
# except:
# seq.append(self.oov_index)
# if maxlen is not None:
# if len(seq) == maxlen:
# break
# all_seq.append(seq)
all_seq = list()
seq = []
for w in texts.split():
try:
seq.append(self.w2i[w])
except:
seq.append(self.oov_index)
if maxlen is not None:
if len(seq) == maxlen:
break
all_seq.append((seq))
return pad_sequences(all_seq, maxlen=maxlen, padding=padding, truncating=truncating, value=value)
def texts_to_sequences_from_file(self, path, maxlen=50, padding='post', truncating='post', value=0):
if len(self.word_count) == 0:
raise Exception("Tokenizer has not been trained, no words in vocabulary.")
all_seq = {}
for line in open(path):
tmp = [x.strip() for x in line.split(',')]
# takes a list of strings that are space delimited into tokens
fid = int(tmp[0])
sent = tmp[1]
# takes a list of strings that are space delimited into tokens
seq = []
for w in sent.split():
try:
seq.append(self.w2i[w])
except:
seq.append(self.oov_index)
if maxlen is not None:
if len(seq) == maxlen:
break
all_seq[fid] = seq
return {key: newval for key, newval in zip(all_seq.keys(), pad_sequences(all_seq.values(), maxlen=maxlen, padding=padding, truncating=truncating, value=value))}
def seq_to_text(self, seq):
return [self.i2w[x] for x in seq]
def forw2v(self, seq):
return [self.i2w[x] for x in seq if self.i2w[x] not in ['<NULL>', '<s>', '</s>']]