-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
293 lines (169 loc) · 7.29 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
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
import random
import math
import numpy as np
import pandas as pd
import nltk
nltk.data.path.append('.')
with open("data.txt", encoding="utf-8") as f:
data = f.read()
def split_data(data):
sentences = data.split('\n')
sentences = [s.strip() for s in sentences]
sentences = [s for s in sentences if len(s) > 2]
return sentences
def tokenize_sentence(sentences):
tokenized_sentences = []
for sentence in sentences:
sentence = sentence.lower()
tokenized = nltk.word_tokenize(sentence)
tokenized_sentences.append(tokenized)
return tokenized_sentences
def get_tokenized_data(data):
sentences = split_data(data)
tokenized_sentences = tokenize_sentence(sentences)
return tokenized_sentences
tokenized_data = get_tokenized_data(data)
random.seed(87)
random.shuffle(tokenized_data)
train_size = int(len(tokenized_data) * 0.8)
train_data = tokenized_data[0:train_size]
test_data = tokenized_data[train_size:]
def count_words(tokenized_sentences):
word_counts = {}
for sentence in tokenized_sentences:
for token in sentence:
if token not in word_counts.keys():
word_counts[token] = 1
else:
word_counts[token] += 1
return word_counts
def get_words_with_nplus_frequency(tokenized_sentences, count_threshold):
closed_vocab = []
word_counts = count_words(tokenized_sentences)
for word, cnt in word_counts.items():
if cnt >= count_threshold:
closed_vocab.append(word)
return closed_vocab
def replace_oov_words_by_unk(tokenized_sentences, vocabulary, unknown_token="<unk>"):
vocabulary = set(vocabulary)
replaced_tokenized_sentences = []
for sentence in tokenized_sentences:
replaced_sentence = []
for token in sentence:
if token in vocabulary:
replaced_sentence.append(token)
else:
replaced_sentence.append(unknown_token)
replaced_tokenized_sentences.append(replaced_sentence)
return replaced_tokenized_sentences
def preprocess_data(train_data, test_data, count_threshold=2):
vocabulary = get_words_with_nplus_frequency(train_data, count_threshold)
train_data_replaced = replace_oov_words_by_unk(train_data, vocabulary)
test_data_replaced = replace_oov_words_by_unk(test_data, vocabulary)
return train_data_replaced, test_data_replaced, vocabulary
def count_n_grams(data, n, start_token='<s>', end_token='<e>'):
n_grams = {}
for sentence in data:
sentence = [start_token] * n + sentence + [end_token]
sentence = tuple(sentence)
m = len(sentence) if n == 1 else len(sentence)-1
for i in range(m):
n_gram = sentence[i:i+n]
if n_gram in n_grams.keys():
n_grams[n_gram] += 1
else:
n_grams[n_gram] = 1
return n_grams
def estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
previous_n_gram = tuple(previous_n_gram)
previous_n_gram_count = n_gram_counts[previous_n_gram] if previous_n_gram in n_gram_counts else 0
denominator = previous_n_gram_count + k * vocabulary_size
n_plus1_gram = previous_n_gram + (word,)
n_plus1_gram_count = n_plus1_gram_counts[n_plus1_gram] if n_plus1_gram in n_plus1_gram_counts else 0
numerator = n_plus1_gram_count + k
probability = numerator / denominator
return probability
def estimate_probabilities(previous_n_gram, n_gram_counts, n_plus1_gram_counts, vocabulary, k=1.0):
previous_n_gram = tuple(previous_n_gram)
vocabulary = vocabulary + ["<e>", "<unk>"]
vocabulary_size = len(vocabulary)
probabilities = {}
for word in vocabulary:
probability = estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts,
vocabulary_size, k=k)
probabilities[word] = probability
return probabilities
def make_count_matrix(n_plus1_gram_counts, vocabulary):
vocabulary = vocabulary + ["<e>", "<unk>"]
n_grams = []
for n_plus1_gram in n_plus1_gram_counts.keys():
n_gram = n_plus1_gram[0:-1]
n_grams.append(n_gram)
n_grams = list(set(n_grams))
row_index = {n_gram: i for i, n_gram in enumerate(n_grams)}
col_index = {word: j for j, word in enumerate(vocabulary)}
nrow = len(n_grams)
ncol = len(vocabulary)
count_matrix = np.zeros((nrow, ncol))
for n_plus1_gram, count in n_plus1_gram_counts.items():
n_gram = n_plus1_gram[0:-1]
word = n_plus1_gram[-1]
if word not in vocabulary:
continue
i = row_index[n_gram]
j = col_index[word]
count_matrix[i, j] = count
count_matrix = pd.DataFrame(
count_matrix, index=n_grams, columns=vocabulary)
return count_matrix
def make_probability_matrix(n_plus1_gram_counts, vocabulary, k):
count_matrix = make_count_matrix(n_plus1_gram_counts, unique_words)
count_matrix += k
prob_matrix = count_matrix.div(count_matrix.sum(axis=1), axis=0)
return prob_matrix
def calculate_perplexity(sentence, n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
n = len(list(n_gram_counts.keys())[0])
sentence = ["<s>"] * n + sentence + ["<e>"]
sentence = tuple(sentence)
N = len(sentence)
product_pi = 1.0
for t in range(n, N):
n_gram = sentence[t-n:t]
word = sentence[t]
probability = estimate_probability(
word, n_gram, n_gram_counts, n_plus1_gram_counts, len(unique_words), k=1)
product_pi *= 1 / probability
perplexity = product_pi**(1/float(N))
return perplexity
def suggest_a_word(previous_tokens, n_gram_counts, n_plus1_gram_counts, vocabulary, k=1.0, start_with=None):
n = len(list(n_gram_counts.keys())[0])
previous_n_gram = previous_tokens[-n:]
probabilities = estimate_probabilities(previous_n_gram,
n_gram_counts, n_plus1_gram_counts,
vocabulary, k=k)
suggestion = None
max_prob = 0
for word, prob in probabilities.items():
if start_with != None:
if not word.startswith(start_with):
continue
if prob > max_prob:
suggestion = word
max_prob = prob
return suggestion, max_prob
def get_suggestions(previous_tokens, n_gram_counts_list, vocabulary, k=1.0, start_with=None):
model_counts = len(n_gram_counts_list)
suggestions = []
for i in range(model_counts-1):
n_gram_counts = n_gram_counts_list[i]
n_plus1_gram_counts = n_gram_counts_list[i+1]
suggestion = suggest_a_word(previous_tokens, n_gram_counts,
n_plus1_gram_counts, vocabulary,
k=k, start_with=start_with)
suggestions.append(suggestion)
return suggestions
unique_words = [set(token) for token in train_data]
minimum_freq = 2
train_data_processed, test_data_processed, vocabulary = preprocess_data(train_data, test_data,minimum_freq)