-
Notifications
You must be signed in to change notification settings - Fork 4
/
FastText.py
385 lines (334 loc) · 11.4 KB
/
FastText.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import fasttext_pybind as fasttext
import numpy as np
loss_name = fasttext.loss_name
model_name = fasttext.model_name
EOS = "</s>"
BOW = "<"
EOW = ">"
class _FastText():
"""
This class defines the API to inspect models and should not be used to
create objects. It will be returned by functions such as load_model or
train.
In general this API assumes to be given only unicode for Python2 and the
Python3 equvalent called str for any string-like arguments. All unicode
strings are then encoded as UTF-8 and fed to the fastText C++ API.
"""
def __init__(self, model=None):
self.f = fasttext.fasttext()
if model is not None:
self.f.loadModel(model)
def is_quantized(self):
return self.f.isQuant()
def get_dimension(self):
"""Get the dimension (size) of a lookup vector (hidden layer)."""
a = self.f.getArgs()
return a.dim
def get_word_vector(self, word):
"""Get the vector representation of word."""
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getWordVector(b, word)
return np.array(b)
def get_sentence_vector(self, text):
"""
Given a string, get a single vector represenation. This function
assumes to be given a single line of text. We split words on
whitespace (space, newline, tab, vertical tab) and the control
characters carriage return, formfeed and the null character.
"""
if text.find('\n') != -1:
raise ValueError(
"predict processes one line at a time (remove \'\\n\')"
)
text += "\n"
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getSentenceVector(b, text)
return np.array(b)
def get_word_id(self, word):
"""
Given a word, get the word id within the dictionary.
Returns -1 if word is not in the dictionary.
"""
return self.f.getWordId(word)
def get_subword_id(self, subword):
"""
Given a subword, return the index (within input matrix) it hashes to.
"""
return self.f.getSubwordId(subword)
def get_subwords(self, word):
"""
Given a word, get the subwords and their indicies.
"""
pair = self.f.getSubwords(word)
return pair[0], np.array(pair[1])
def get_input_vector(self, ind):
"""
Given an index, get the corresponding vector of the Input Matrix.
"""
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getInputVector(b, ind)
return np.array(b)
def predict(self, text, k=1, threshold=0.0):
"""
Given a string, get a list of labels and a list of
corresponding probabilities. k controls the number
of returned labels. A choice of 5, will return the 5
most probable labels. By default this returns only
the most likely label and probability. threshold filters
the returned labels by a threshold on probability. A
choice of 0.5 will return labels with at least 0.5
probability. k and threshold will be applied together to
determine the returned labels.
This function assumes to be given
a single line of text. We split words on whitespace (space,
newline, tab, vertical tab) and the control characters carriage
return, formfeed and the null character.
If the model is not supervised, this function will throw a ValueError.
If given a list of strings, it will return a list of results as usually
received for a single line of text.
"""
def check(entry):
if entry.find('\n') != -1:
raise ValueError(
"predict processes one line at a time (remove \'\\n\')"
)
entry += "\n"
return entry
if type(text) == list:
text = [check(entry) for entry in text]
all_probs, all_labels = self.f.multilinePredict(text, k, threshold)
return all_labels, np.array(all_probs, copy=False)
else:
text = check(text)
pairs = self.f.predict(text, k, threshold)
probs, labels = zip(*pairs)
return labels, np.array(probs, copy=False)
def get_input_matrix(self):
"""
Get a copy of the full input matrix of a Model. This only
works if the model is not quantized.
"""
if self.f.isQuant():
raise ValueError("Can't get quantized Matrix")
return np.array(self.f.getInputMatrix())
def get_output_matrix(self):
"""
Get a copy of the full output matrix of a Model. This only
works if the model is not quantized.
"""
if self.f.isQuant():
raise ValueError("Can't get quantized Matrix")
return np.array(self.f.getOutputMatrix())
def get_words(self, include_freq=False):
"""
Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords.
"""
pair = self.f.getVocab()
if include_freq:
return (pair[0], np.array(pair[1]))
else:
return pair[0]
def get_labels(self, include_freq=False):
"""
Get the entire list of labels of the dictionary optionally
including the frequency of the individual labels. Unsupervised
models use words as labels, which is why get_labels
will call and return get_words for this type of
model.
"""
a = self.f.getArgs()
if a.model == model_name.supervised:
pair = self.f.getLabels()
if include_freq:
return (pair[0], np.array(pair[1]))
else:
return pair[0]
else:
return self.get_words(include_freq)
def get_line(self, text):
"""
Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default).
"""
def check(entry):
if entry.find('\n') != -1:
raise ValueError(
"get_line processes one line at a time (remove \'\\n\')"
)
entry += "\n"
return entry
if type(text) == list:
text = [check(entry) for entry in text]
return self.f.multilineGetLine(text)
else:
text = check(text)
return self.f.getLine(text)
def save_model(self, path):
"""Save the model to the given path"""
self.f.saveModel(path)
def test(self, path, k=1):
"""Evaluate supervised model using file given by path"""
return self.f.test(path, k)
def quantize(
self,
input=None,
qout=False,
cutoff=0,
retrain=False,
epoch=None,
lr=None,
thread=None,
verbose=None,
dsub=2,
qnorm=False
):
"""
Quantize the model reducing the size of the model and
it's memory footprint.
"""
a = self.f.getArgs()
if not epoch:
epoch = a.epoch
if not lr:
lr = a.lr
if not thread:
thread = a.thread
if not verbose:
verbose = a.verbose
if retrain and not input:
raise ValueError("Need input file path if retraining")
if input is None:
input = ""
self.f.quantize(
input, qout, cutoff, retrain, epoch, lr, thread, verbose, dsub,
qnorm
)
# TODO:
# Not supported:
# - pretrained vectors
def _parse_model_string(string):
if string == "cbow":
return model_name.cbow
if string == "skipgram":
return model_name.skipgram
if string == "supervised":
return model_name.supervised
else:
raise ValueError("Unrecognized model name")
def _parse_loss_string(string):
if string == "ns":
return loss_name.ns
if string == "hs":
return loss_name.hs
if string == "softmax":
return loss_name.softmax
else:
raise ValueError("Unrecognized loss name")
def _build_args(args):
args["model"] = _parse_model_string(args["model"])
args["loss"] = _parse_loss_string(args["loss"])
a = fasttext.args()
for (k, v) in args.items():
setattr(a, k, v)
a.output = "" # User should use save_model
a.pretrainedVectors = "" # Unsupported
a.saveOutput = 0 # Never use this
if a.wordNgrams <= 1 and a.maxn == 0:
a.bucket = 0
return a
def tokenize(text):
"""Given a string of text, tokenize it and return a list of tokens"""
f = fasttext.fasttext()
return f.tokenize(text)
def load_model(path):
"""Load a model given a filepath and return a model object."""
return _FastText(path)
def train_supervised(
input,
lr=0.1,
dim=100,
ws=5,
epoch=5,
minCount=1,
minCountLabel=0,
minn=0,
maxn=0,
neg=5,
wordNgrams=1,
loss="softmax",
bucket=2000000,
thread=12,
lrUpdateRate=100,
t=1e-4,
label="__label__",
verbose=2,
pretrainedVectors="",
):
"""
Train a supervised model and return a model object.
input must be a filepath. The input text does not need to be tokenized
as per the tokenize function, but it must be preprocessed and encoded
as UTF-8. You might want to consult standard preprocessing scripts such
as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
The input file must must contain at least one label per line. For an
example consult the example datasets which are part of the fastText
repository such as the dataset pulled by classification-example.sh.
"""
model = "supervised"
a = _build_args(locals())
ft = _FastText()
fasttext.train(ft.f, a)
return ft
def train_unsupervised(
input,
model="skipgram",
lr=0.05,
dim=100,
ws=5,
epoch=5,
minCount=5,
minCountLabel=0,
minn=3,
maxn=6,
neg=5,
wordNgrams=1,
loss="ns",
bucket=2000000,
thread=12,
lrUpdateRate=100,
t=1e-4,
label="__label__",
verbose=2,
pretrainedVectors="",
):
"""
Train an unsupervised model and return a model object.
input must be a filepath. The input text does not need to be tokenized
as per the tokenize function, but it must be preprocessed and encoded
as UTF-8. You might want to consult standard preprocessing scripts such
as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
The input field must not contain any labels or use the specified label prefix
unless it is ok for those words to be ignored. For an example consult the
dataset pulled by the example script word-vector-example.sh, which is
part of the fastText repository.
"""
a = _build_args(locals())
ft = _FastText()
fasttext.train(ft.f, a)
return ft