forked from ddbourgin/numpy-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.py
255 lines (203 loc) · 7.83 KB
/
tests.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
import sys
import nltk
sys.path.append("..")
import numpy as np
from preprocessing.nlp import tokenize_words
from ngram import AdditiveNGram, MLENGram
class MLEGold:
def __init__(
self, N, K=1, unk=True, filter_stopwords=True, filter_punctuation=True
):
self.N = N
self.K = K
self.unk = unk
self.filter_stopwords = filter_stopwords
self.filter_punctuation = filter_punctuation
self.hyperparameters = {
"N": N,
"K": K,
"unk": unk,
"filter_stopwords": filter_stopwords,
"filter_punctuation": filter_punctuation,
}
super().__init__()
def train(self, corpus_fp, vocab=None, encoding=None):
N = self.N
H = self.hyperparameters
models, counts = {}, {}
grams = {n: [] for n in range(1, N + 1)}
gg = {n: [] for n in range(1, N + 1)}
filter_punc, filter_stop = H["filter_punctuation"], H["filter_stopwords"]
n_words = 0
tokens = set([])
with open(corpus_fp, "r", encoding=encoding) as text:
for line in text:
words = tokenize_words(line, filter_punc, filter_stop)
if vocab is not None:
words = vocab.filter(words, H["unk"])
if len(words) == 0:
continue
n_words += len(words)
tokens.update(words)
# calculate n, n-1, ... 1-grams
for n in range(1, N + 1):
grams[n].append(
nltk.ngrams(
words,
n,
pad_left=True,
pad_right=True,
left_pad_symbol="<bol>",
right_pad_symbol="<eol>",
)
)
gg[n].extend(
list(
nltk.ngrams(
words,
n,
pad_left=True,
pad_right=True,
left_pad_symbol="<bol>",
right_pad_symbol="<eol>",
)
)
)
for n in range(1, N + 1):
counts[n] = nltk.FreqDist(gg[n])
models[n] = nltk.lm.MLE(order=n)
models[n].fit(grams[n], tokens)
self.counts = counts
self.n_words = n_words
self._models = models
self.n_tokens = len(vocab) if vocab is not None else len(tokens)
def log_prob(self, words, N):
assert N in self.counts, "You do not have counts for {}-grams".format(N)
if N > len(words):
err = "Not enough words for a gram-size of {}: {}".format(N, len(words))
raise ValueError(err)
total_prob = 0
for ngram in nltk.ngrams(words, N):
total_prob += self._log_ngram_prob(ngram)
return total_prob
def _log_ngram_prob(self, ngram):
N = len(ngram)
return self._models[N].logscore(ngram[-1], ngram[:-1])
class AdditiveGold:
def __init__(
self, N, K=1, unk=True, filter_stopwords=True, filter_punctuation=True
):
self.N = N
self.K = K
self.unk = unk
self.filter_stopwords = filter_stopwords
self.filter_punctuation = filter_punctuation
self.hyperparameters = {
"N": N,
"K": K,
"unk": unk,
"filter_stopwords": filter_stopwords,
"filter_punctuation": filter_punctuation,
}
super().__init__()
def train(self, corpus_fp, vocab=None, encoding=None):
N = self.N
H = self.hyperparameters
models, counts = {}, {}
grams = {n: [] for n in range(1, N + 1)}
gg = {n: [] for n in range(1, N + 1)}
filter_punc, filter_stop = H["filter_punctuation"], H["filter_stopwords"]
n_words = 0
tokens = set()
with open(corpus_fp, "r", encoding=encoding) as text:
for line in text:
words = tokenize_words(line, filter_punc, filter_stop)
if vocab is not None:
words = vocab.filter(words, H["unk"])
if len(words) == 0:
continue
n_words += len(words)
tokens.update(words)
# calculate n, n-1, ... 1-grams
for n in range(1, N + 1):
grams[n].append(
nltk.ngrams(
words,
n,
pad_left=True,
pad_right=True,
left_pad_symbol="<bol>",
right_pad_symbol="<eol>",
)
)
gg[n].extend(
list(
nltk.ngrams(
words,
n,
pad_left=True,
pad_right=True,
left_pad_symbol="<bol>",
right_pad_symbol="<eol>",
)
)
)
for n in range(1, N + 1):
counts[n] = nltk.FreqDist(gg[n])
models[n] = nltk.lm.Lidstone(order=n, gamma=self.K)
models[n].fit(grams[n], tokens)
self.counts = counts
self._models = models
self.n_words = n_words
self.n_tokens = len(vocab) if vocab is not None else len(tokens)
def log_prob(self, words, N):
assert N in self.counts, "You do not have counts for {}-grams".format(N)
if N > len(words):
err = "Not enough words for a gram-size of {}: {}".format(N, len(words))
raise ValueError(err)
total_prob = 0
for ngram in nltk.ngrams(words, N):
total_prob += self._log_ngram_prob(ngram)
return total_prob
def _log_ngram_prob(self, ngram):
N = len(ngram)
return self._models[N].logscore(ngram[-1], ngram[:-1])
def test_mle():
N = np.random.randint(2, 5)
gold = MLEGold(N, unk=True, filter_stopwords=False, filter_punctuation=False)
mine = MLENGram(N, unk=True, filter_stopwords=False, filter_punctuation=False)
gold.train("russell.txt", encoding="utf-8-sig")
mine.train("russell.txt", encoding="utf-8-sig")
for k in mine.counts[N].keys():
if k[0] == k[1] and k[0] in ("<bol>", "<eol>"):
continue
err_str = "{}, mine: {}, gold: {}"
assert mine.counts[N][k] == gold.counts[N][k], err_str.format(
k, mine.counts[N][k], gold.counts[N][k]
)
M = mine.log_prob(k, N)
G = gold.log_prob(k, N) / np.log2(np.e) # convert to log base e
np.testing.assert_allclose(M, G)
print("PASSED")
def test_additive():
K = np.random.rand()
N = np.random.randint(2, 5)
gold = AdditiveGold(
N, K, unk=True, filter_stopwords=False, filter_punctuation=False
)
mine = AdditiveNGram(
N, K, unk=True, filter_stopwords=False, filter_punctuation=False
)
gold.train("russell.txt", encoding="utf-8-sig")
mine.train("russell.txt", encoding="utf-8-sig")
for k in mine.counts[N].keys():
if k[0] == k[1] and k[0] in ("<bol>", "<eol>"):
continue
err_str = "{}, mine: {}, gold: {}"
assert mine.counts[N][k] == gold.counts[N][k], err_str.format(
k, mine.counts[N][k], gold.counts[N][k]
)
M = mine.log_prob(k, N)
G = gold.log_prob(k, N) / np.log2(np.e) # convert to log base e
np.testing.assert_allclose(M, G)
print("PASSED")