-
Notifications
You must be signed in to change notification settings - Fork 0
/
predictor.py
354 lines (278 loc) · 8.57 KB
/
predictor.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import tensorflow as tf
import numpy as np
import collections
class Predictor:
"""
NN to predict word context.
Attributes
----------
vocabulary_size : int
learning_rate : float, optional
Methods
-------
train(X, y)
Train the NN model.
predict(X)
Make prediction from X.
"""
def __init__(self, vocabulary_size, learning_rate=0.1):
self.vocabulary_size = vocabulary_size
self.learning_rate = learning_rate
self.x = tf.placeholder(tf.float32, [None, vocabulary_size])
self.y = tf.placeholder(tf.float32, [None, vocabulary_size])
self.weights = {
'h1': tf.Variable(tf.random_uniform([self.vocabulary_size,
self.vocabulary_size]))
}
def perceptron(x, weights):
layer_1 = tf.matmul(x, weights['h1'])
layer_1 = tf.nn.sigmoid(layer_1)
tmp_sum = tf.reduce_sum(layer_1)
out_layer = tf.divide(layer_1, tmp_sum)
return out_layer
self.pred = perceptron(self.x, self.weights)
self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=self.pred, labels=self.y))
self.optimizer = tf.train.AdamOptimizer(
learning_rate=self.learning_rate).minimize(self.cost)
self.init = tf.global_variables_initializer()
self.sess = tf.Session()
def init_model(self):
"""
Just to execute `self.init`.
"""
self.sess.run(self.init)
def train(self, X, y):
"""
Train the NN model.
Parameters
----------
X, y : array_like
One-hot-encoding vectors of words and their contexts.
Returns
-------
c : float
Cost value.
"""
_, c = self.sess.run([self.optimizer, self.cost],
feed_dict={self.x: X, self.y: y})
return c
def predict(self, X):
"""
Make prediction from `X`. Predict context for OHE of words in `X`.
Parameters
----------
X : array_like
One-hot-encoding vectors of words.
Returns
-------
preds : array_like
Context - the probabilities of each word in vocabulary to be
in the context of words in `X`.
"""
preds = self.sess.run([self.pred], feed_dict={self.x: X})
return preds
def close(self):
"""
Close the `self.sess`.
"""
self.sess.close()
def read_data(filename):
"""
Read text data from file.
Parameters
----------
filename : str
Returns
-------
data : list
List of pieces of texts.
"""
with open(filename, 'r') as data_file:
data = data_file.readlines()
return data
def good_dots(text):
"""
Replace dots with commas in order to split
sentences correctly by dots.
Parameters
----------
text : str
Returns
-------
transformed_text : str
Examples
--------
>>> good_dots('score (+/-SD) was 1.8+/-1.2. Prothrombin times')
'score (+/-SD) was 1,8+/-1,2. Prothrombin times'
"""
#
# TODO: replace with regular expression
#
# >>> import re
# >>> test = 'score (+/-SD) was 1.8+/-1.2. Prothrombin times'
# >>> re.sub('\.\S', ',', test)
# 'score (+/-SD) was 1,+/-1,. Prothrombin times'
#
def is_dot(c):
return c == '.'
def is_right_space(c):
return c == ' '
transformed_text = ''
for index in range(len(text) - 1):
if is_dot(text[index]) and not is_right_space(text[index+1]):
transformed_text += ','
else:
transformed_text += text[index]
transformed_text += text[-1]
# To avoid dot in the end of string.
transformed_text = transformed_text.strip('.')
return transformed_text
def text_preproc(input_text):
"""
Make preprocessing of input text.
Parameters
----------
input_data : str
Returns
-------
sentences_stripped : list
List of sentences. Sentence is a list of words.
"""
sentences = input_text.lower().split('.')
sentences_splitted = list(map(lambda x: x.split(), sentences))
def strip_words(list_input):
return list(map(lambda x: x.strip('<>():,.;!?'), list_input))
sentences_stripped = list(map(lambda x: strip_words(x),
sentences_splitted))
return sentences_stripped
def clean_data(data_input):
"""
Prepare text data for dataset building.
Parameters
----------
data_input : list
List of pieces of texts.
Returns
-------
res_data : list
List of sentences. Sentence is a list of words.
"""
data_good_dots = list(map(lambda x: good_dots(x), data_input))
res_data = list(map(lambda x: text_preproc(x), data_good_dots))
return res_data
def build_vocabulary(texts, vocabulary_size, stopwords_input):
"""
Build vocabulary with size of vocabulary_size.
Use only top-n frequent words.
Parameters
----------
texts : list
List of strings.
vocabulary_size : int
stopwords_input : list
List of words to remove from dictionary.
Returns
-------
res_vocab : dict
Vocabulary of words: {word: id, ...}.
reversed_vocab : dict
Reversed vocabulary: {id: word, ...}.
"""
concat_sent = []
for sentence in texts:
concat_sent.extend(sentence.lower().split())
concat_sent = list(map(lambda x: x.strip('<>():,.;!?'), concat_sent))
count = collections.Counter(concat_sent)
# Remove stop-words from vocabulary.
for word in stopwords_input:
if word in count:
count.pop(word)
# Get top-n words (-1 because of <UNK>)
list_vocab = list(map(lambda x: x[0],
count.most_common(vocabulary_size-1)))
res_vocab = {'UNK': 0}
for word in list_vocab:
res_vocab[word] = len(res_vocab)
reversed_vocab = dict(zip(res_vocab.values(), res_vocab.keys()))
return res_vocab, reversed_vocab
def build_dataset(sentence, vocab, max_dist=3):
"""
Build dataset from words of `sentence`.
Parameters
----------
sentence : list
List of words.
vocab : dict
max_dist : int, optional
Maximum distance between input word and word form context.
Returns
-------
dataset : list
List of tuples: [(word, [context_word_1, ..., context_word_m]), ...].
Examples
--------
>>> build_dataset(['background', 'rivaroxaban', 'is', 'currently',
'used', 'to'])
[('background', ['rivaroxaban', 'is', 'currently']),
('rivaroxaban', ['background', 'is', 'currently', 'used']),
('is', ['background', 'rivaroxaban', 'currently', 'used', 'to']),
('currently', ['background', 'rivaroxaban', 'is', 'used', 'to']),
('used', ['rivaroxaban', 'is', 'currently', 'to']),
('to', ['is', 'currently', 'used'])]
"""
dataset = []
for i in range(len(sentence)):
indexes = list(filter(lambda x: x >= 0 and x < len(sentence),
np.arange(i - max_dist, i + max_dist + 1)))
indexes.remove(i)
tmp = []
for index in indexes:
if sentence[index] in vocab:
tmp.append(sentence[index])
if sentence[i] in vocab and len(tmp) > 0:
dataset.append((sentence[i], tmp))
return dataset
def get_ohe(words, vocab_input):
"""
Compute one-hot-encoding for every word in `words`
and summurize them into `res`.
Parameters
----------
words : list
List of words.
vocab_input : dict
Vocabulary of words: {word: id, ...}
Returns
-------
res : array_like
Summarized one-hot-encoding vectors of every word.
"""
res = np.zeros(len(vocab_input))
for word in words:
# One-hot-encoding of `word`.
tmp_ohe = np.zeros(len(vocab_input))
if word in vocab_input:
tmp_ohe[vocab_input[word]] = 1
else:
tmp_ohe[0] = 1 # In case of <UNK>.
res += tmp_ohe
return res
def normalize_ohe(vector_input):
"""
Normalize one-hot-encoding vector.
Divide input vector by the sum of components.
Parameters
----------
vector_input : array_like
Returns
-------
Normalized vector.
Examples
--------
>>> normalize_ohe([1, 3, 4])
array([ 0.125, 0.375, 0.5 ])
"""
return vector_input / np.sum(vector_input)
if __name__ == '__main__':
assert(0)