1
0

FastText.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the MIT license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. from __future__ import absolute_import
  7. from __future__ import division
  8. from __future__ import print_function
  9. from __future__ import unicode_literals
  10. import fasttext_pybind as fasttext
  11. import numpy as np
  12. import multiprocessing
  13. import sys
  14. from itertools import chain
  15. loss_name = fasttext.loss_name
  16. model_name = fasttext.model_name
  17. EOS = "</s>"
  18. BOW = "<"
  19. EOW = ">"
  20. displayed_errors = {}
  21. class _Meter(object):
  22. def __init__(self, fasttext_model, meter):
  23. self.f = fasttext_model
  24. self.m = meter
  25. def score_vs_true(self, label):
  26. """Return scores and the gold of each sample for a specific label"""
  27. label_id = self.f.get_label_id(label)
  28. pair_list = self.m.scoreVsTrue(label_id)
  29. if pair_list:
  30. y_scores, y_true = zip(*pair_list)
  31. else:
  32. y_scores, y_true = ([], ())
  33. return np.array(y_scores, copy=False), np.array(y_true, copy=False)
  34. def precision_recall_curve(self, label=None):
  35. """Return precision/recall curve"""
  36. if label:
  37. label_id = self.f.get_label_id(label)
  38. pair_list = self.m.precisionRecallCurveLabel(label_id)
  39. else:
  40. pair_list = self.m.precisionRecallCurve()
  41. if pair_list:
  42. precision, recall = zip(*pair_list)
  43. else:
  44. precision, recall = ([], ())
  45. return np.array(precision, copy=False), np.array(recall, copy=False)
  46. def precision_at_recall(self, recall, label=None):
  47. """Return precision for a given recall"""
  48. if label:
  49. label_id = self.f.get_label_id(label)
  50. precision = self.m.precisionAtRecallLabel(label_id, recall)
  51. else:
  52. precision = self.m.precisionAtRecall(recall)
  53. return precision
  54. def recall_at_precision(self, precision, label=None):
  55. """Return recall for a given precision"""
  56. if label:
  57. label_id = self.f.get_label_id(label)
  58. recall = self.m.recallAtPrecisionLabel(label_id, precision)
  59. else:
  60. recall = self.m.recallAtPrecision(precision)
  61. return recall
  62. class _FastText(object):
  63. """
  64. This class defines the API to inspect models and should not be used to
  65. create objects. It will be returned by functions such as load_model or
  66. train.
  67. In general this API assumes to be given only unicode for Python2 and the
  68. Python3 equvalent called str for any string-like arguments. All unicode
  69. strings are then encoded as UTF-8 and fed to the fastText C++ API.
  70. """
  71. def __init__(self, model_path=None, args=None):
  72. self.f = fasttext.fasttext()
  73. if model_path is not None:
  74. self.f.loadModel(model_path)
  75. self._words = None
  76. self._labels = None
  77. self.set_args(args)
  78. def set_args(self, args=None):
  79. if args:
  80. arg_names = ['lr', 'dim', 'ws', 'epoch', 'minCount',
  81. 'minCountLabel', 'minn', 'maxn', 'neg', 'wordNgrams',
  82. 'loss', 'bucket', 'thread', 'lrUpdateRate', 't',
  83. 'label', 'verbose', 'pretrainedVectors']
  84. for arg_name in arg_names:
  85. setattr(self, arg_name, getattr(args, arg_name))
  86. def is_quantized(self):
  87. return self.f.isQuant()
  88. def get_dimension(self):
  89. """Get the dimension (size) of a lookup vector (hidden layer)."""
  90. a = self.f.getArgs()
  91. return a.dim
  92. def get_word_vector(self, word):
  93. """Get the vector representation of word."""
  94. dim = self.get_dimension()
  95. b = fasttext.Vector(dim)
  96. self.f.getWordVector(b, word)
  97. return np.array(b)
  98. def get_sentence_vector(self, text):
  99. """
  100. Given a string, get a single vector represenation. This function
  101. assumes to be given a single line of text. We split words on
  102. whitespace (space, newline, tab, vertical tab) and the control
  103. characters carriage return, formfeed and the null character.
  104. """
  105. if text.find('\n') != -1:
  106. raise ValueError(
  107. "predict processes one line at a time (remove \'\\n\')"
  108. )
  109. text += "\n"
  110. dim = self.get_dimension()
  111. b = fasttext.Vector(dim)
  112. self.f.getSentenceVector(b, text)
  113. return np.array(b)
  114. def get_nearest_neighbors(self, word, k=10, on_unicode_error='strict'):
  115. return self.f.getNN(word, k, on_unicode_error)
  116. def get_analogies(self, wordA, wordB, wordC, k=10,
  117. on_unicode_error='strict'):
  118. return self.f.getAnalogies(wordA, wordB, wordC, k, on_unicode_error)
  119. def get_word_id(self, word):
  120. """
  121. Given a word, get the word id within the dictionary.
  122. Returns -1 if word is not in the dictionary.
  123. """
  124. return self.f.getWordId(word)
  125. def get_label_id(self, label):
  126. """
  127. Given a label, get the label id within the dictionary.
  128. Returns -1 if label is not in the dictionary.
  129. """
  130. return self.f.getLabelId(label)
  131. def get_subword_id(self, subword):
  132. """
  133. Given a subword, return the index (within input matrix) it hashes to.
  134. """
  135. return self.f.getSubwordId(subword)
  136. def get_subwords(self, word, on_unicode_error='strict'):
  137. """
  138. Given a word, get the subwords and their indicies.
  139. """
  140. pair = self.f.getSubwords(word, on_unicode_error)
  141. return pair[0], np.array(pair[1])
  142. def get_input_vector(self, ind):
  143. """
  144. Given an index, get the corresponding vector of the Input Matrix.
  145. """
  146. dim = self.get_dimension()
  147. b = fasttext.Vector(dim)
  148. self.f.getInputVector(b, ind)
  149. return np.array(b)
  150. def predict(self, text, k=1, threshold=0.0, on_unicode_error='strict'):
  151. """
  152. Given a string, get a list of labels and a list of
  153. corresponding probabilities. k controls the number
  154. of returned labels. A choice of 5, will return the 5
  155. most probable labels. By default this returns only
  156. the most likely label and probability. threshold filters
  157. the returned labels by a threshold on probability. A
  158. choice of 0.5 will return labels with at least 0.5
  159. probability. k and threshold will be applied together to
  160. determine the returned labels.
  161. This function assumes to be given
  162. a single line of text. We split words on whitespace (space,
  163. newline, tab, vertical tab) and the control characters carriage
  164. return, formfeed and the null character.
  165. If the model is not supervised, this function will throw a ValueError.
  166. If given a list of strings, it will return a list of results as usually
  167. received for a single line of text.
  168. """
  169. def check(entry):
  170. if entry.find('\n') != -1:
  171. raise ValueError(
  172. "predict processes one line at a time (remove \'\\n\')"
  173. )
  174. entry += "\n"
  175. return entry
  176. if type(text) == list:
  177. text = [check(entry) for entry in text]
  178. all_labels, all_probs = self.f.multilinePredict(
  179. text, k, threshold, on_unicode_error)
  180. return all_labels, all_probs
  181. else:
  182. text = check(text)
  183. predictions = self.f.predict(text, k, threshold, on_unicode_error)
  184. if predictions:
  185. probs, labels = zip(*predictions)
  186. else:
  187. probs, labels = ([], ())
  188. return labels, np.array(probs, copy=False)
  189. def get_input_matrix(self):
  190. """
  191. Get a reference to the full input matrix of a Model. This only
  192. works if the model is not quantized.
  193. """
  194. if self.f.isQuant():
  195. raise ValueError("Can't get quantized Matrix")
  196. return np.array(self.f.getInputMatrix())
  197. def get_output_matrix(self):
  198. """
  199. Get a reference to the full output matrix of a Model. This only
  200. works if the model is not quantized.
  201. """
  202. if self.f.isQuant():
  203. raise ValueError("Can't get quantized Matrix")
  204. return np.array(self.f.getOutputMatrix())
  205. def get_words(self, include_freq=False, on_unicode_error='strict'):
  206. """
  207. Get the entire list of words of the dictionary optionally
  208. including the frequency of the individual words. This
  209. does not include any subwords. For that please consult
  210. the function get_subwords.
  211. """
  212. pair = self.f.getVocab(on_unicode_error)
  213. if include_freq:
  214. return (pair[0], np.array(pair[1]))
  215. else:
  216. return pair[0]
  217. def get_labels(self, include_freq=False, on_unicode_error='strict'):
  218. """
  219. Get the entire list of labels of the dictionary optionally
  220. including the frequency of the individual labels. Unsupervised
  221. models use words as labels, which is why get_labels
  222. will call and return get_words for this type of
  223. model.
  224. """
  225. a = self.f.getArgs()
  226. if a.model == model_name.supervised:
  227. pair = self.f.getLabels(on_unicode_error)
  228. if include_freq:
  229. return (pair[0], np.array(pair[1]))
  230. else:
  231. return pair[0]
  232. else:
  233. return self.get_words(include_freq)
  234. def get_line(self, text, on_unicode_error='strict'):
  235. """
  236. Split a line of text into words and labels. Labels must start with
  237. the prefix used to create the model (__label__ by default).
  238. """
  239. def check(entry):
  240. if entry.find('\n') != -1:
  241. raise ValueError(
  242. "get_line processes one line at a time (remove \'\\n\')"
  243. )
  244. entry += "\n"
  245. return entry
  246. if type(text) == list:
  247. text = [check(entry) for entry in text]
  248. return self.f.multilineGetLine(text, on_unicode_error)
  249. else:
  250. text = check(text)
  251. return self.f.getLine(text, on_unicode_error)
  252. def save_model(self, path):
  253. """Save the model to the given path"""
  254. self.f.saveModel(path)
  255. def test(self, path, k=1, threshold=0.0):
  256. """Evaluate supervised model using file given by path"""
  257. return self.f.test(path, k, threshold)
  258. def test_label(self, path, k=1, threshold=0.0):
  259. """
  260. Return the precision and recall score for each label.
  261. The returned value is a dictionary, where the key is the label.
  262. For example:
  263. f.test_label(...)
  264. {'__label__italian-cuisine' : {'precision' : 0.7, 'recall' : 0.74}}
  265. """
  266. return self.f.testLabel(path, k, threshold)
  267. def get_meter(self, path, k=-1):
  268. meter = _Meter(self, self.f.getMeter(path, k))
  269. return meter
  270. def quantize(
  271. self,
  272. input=None,
  273. qout=False,
  274. cutoff=0,
  275. retrain=False,
  276. epoch=None,
  277. lr=None,
  278. thread=None,
  279. verbose=None,
  280. dsub=2,
  281. qnorm=False
  282. ):
  283. """
  284. Quantize the model reducing the size of the model and
  285. it's memory footprint.
  286. """
  287. a = self.f.getArgs()
  288. if not epoch:
  289. epoch = a.epoch
  290. if not lr:
  291. lr = a.lr
  292. if not thread:
  293. thread = a.thread
  294. if not verbose:
  295. verbose = a.verbose
  296. if retrain and not input:
  297. raise ValueError("Need input file path if retraining")
  298. if input is None:
  299. input = ""
  300. self.f.quantize(
  301. input, qout, cutoff, retrain, epoch, lr, thread, verbose, dsub,
  302. qnorm
  303. )
  304. def set_matrices(self, input_matrix, output_matrix):
  305. """
  306. Set input and output matrices. This function assumes you know what you
  307. are doing.
  308. """
  309. self.f.setMatrices(input_matrix.astype(np.float32),
  310. output_matrix.astype(np.float32))
  311. @property
  312. def words(self):
  313. if self._words is None:
  314. self._words = self.get_words()
  315. return self._words
  316. @property
  317. def labels(self):
  318. if self._labels is None:
  319. self._labels = self.get_labels()
  320. return self._labels
  321. def __getitem__(self, word):
  322. return self.get_word_vector(word)
  323. def __contains__(self, word):
  324. return word in self.words
  325. def _parse_model_string(string):
  326. if string == "cbow":
  327. return model_name.cbow
  328. if string == "skipgram":
  329. return model_name.skipgram
  330. if string == "supervised":
  331. return model_name.supervised
  332. else:
  333. raise ValueError("Unrecognized model name")
  334. def _parse_loss_string(string):
  335. if string == "ns":
  336. return loss_name.ns
  337. if string == "hs":
  338. return loss_name.hs
  339. if string == "softmax":
  340. return loss_name.softmax
  341. if string == "ova":
  342. return loss_name.ova
  343. else:
  344. raise ValueError("Unrecognized loss name")
  345. def _build_args(args, manually_set_args):
  346. args["model"] = _parse_model_string(args["model"])
  347. args["loss"] = _parse_loss_string(args["loss"])
  348. if type(args["autotuneModelSize"]) == int:
  349. args["autotuneModelSize"] = str(args["autotuneModelSize"])
  350. a = fasttext.args()
  351. for (k, v) in args.items():
  352. setattr(a, k, v)
  353. if k in manually_set_args:
  354. a.setManual(k)
  355. a.output = "" # User should use save_model
  356. a.saveOutput = 0 # Never use this
  357. if a.wordNgrams <= 1 and a.maxn == 0:
  358. a.bucket = 0
  359. return a
  360. def tokenize(text):
  361. """Given a string of text, tokenize it and return a list of tokens"""
  362. f = fasttext.fasttext()
  363. return f.tokenize(text)
  364. def load_model(path):
  365. """Load a model given a filepath and return a model object."""
  366. return _FastText(model_path=path)
  367. unsupervised_default = {
  368. 'model': "skipgram",
  369. 'lr': 0.05,
  370. 'dim': 100,
  371. 'ws': 5,
  372. 'epoch': 5,
  373. 'minCount': 5,
  374. 'minCountLabel': 0,
  375. 'minn': 3,
  376. 'maxn': 6,
  377. 'neg': 5,
  378. 'wordNgrams': 1,
  379. 'loss': "ns",
  380. 'bucket': 2000000,
  381. 'thread': multiprocessing.cpu_count() - 1,
  382. 'lrUpdateRate': 100,
  383. 't': 1e-4,
  384. 'label': "__label__",
  385. 'verbose': 2,
  386. 'pretrainedVectors': "",
  387. 'seed': 0,
  388. 'autotuneValidationFile': "",
  389. 'autotuneMetric': "f1",
  390. 'autotunePredictions': 1,
  391. 'autotuneDuration': 60 * 5, # 5 minutes
  392. 'autotuneModelSize': ""
  393. }
  394. def read_args(arg_list, arg_dict, arg_names, default_values):
  395. param_map = {
  396. 'min_count': 'minCount',
  397. 'word_ngrams': 'wordNgrams',
  398. 'lr_update_rate': 'lrUpdateRate',
  399. 'label_prefix': 'label',
  400. 'pretrained_vectors': 'pretrainedVectors'
  401. }
  402. ret = {}
  403. manually_set_args = set()
  404. for (arg_name, arg_value) in chain(zip(arg_names, arg_list), arg_dict.items()):
  405. if arg_name in param_map:
  406. arg_name = param_map[arg_name]
  407. if arg_name not in arg_names:
  408. raise TypeError("unexpected keyword argument '%s'" % arg_name)
  409. if arg_name in ret:
  410. raise TypeError("multiple values for argument '%s'" % arg_name)
  411. ret[arg_name] = arg_value
  412. manually_set_args.add(arg_name)
  413. for (arg_name, arg_value) in default_values.items():
  414. if arg_name not in ret:
  415. ret[arg_name] = arg_value
  416. return (ret, manually_set_args)
  417. def train_supervised(*kargs, **kwargs):
  418. """
  419. Train a supervised model and return a model object.
  420. input must be a filepath. The input text does not need to be tokenized
  421. as per the tokenize function, but it must be preprocessed and encoded
  422. as UTF-8. You might want to consult standard preprocessing scripts such
  423. as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
  424. The input file must must contain at least one label per line. For an
  425. example consult the example datasets which are part of the fastText
  426. repository such as the dataset pulled by classification-example.sh.
  427. """
  428. supervised_default = unsupervised_default.copy()
  429. supervised_default.update({
  430. 'lr': 0.1,
  431. 'minCount': 1,
  432. 'minn': 0,
  433. 'maxn': 0,
  434. 'loss': "softmax",
  435. 'model': "supervised"
  436. })
  437. arg_names = ['input', 'lr', 'dim', 'ws', 'epoch', 'minCount',
  438. 'minCountLabel', 'minn', 'maxn', 'neg', 'wordNgrams', 'loss', 'bucket',
  439. 'thread', 'lrUpdateRate', 't', 'label', 'verbose', 'pretrainedVectors',
  440. 'seed', 'autotuneValidationFile', 'autotuneMetric',
  441. 'autotunePredictions', 'autotuneDuration', 'autotuneModelSize']
  442. args, manually_set_args = read_args(kargs, kwargs, arg_names,
  443. supervised_default)
  444. a = _build_args(args, manually_set_args)
  445. ft = _FastText(args=a)
  446. fasttext.train(ft.f, a)
  447. ft.set_args(ft.f.getArgs())
  448. return ft
  449. def train_unsupervised(*kargs, **kwargs):
  450. """
  451. Train an unsupervised model and return a model object.
  452. input must be a filepath. The input text does not need to be tokenized
  453. as per the tokenize function, but it must be preprocessed and encoded
  454. as UTF-8. You might want to consult standard preprocessing scripts such
  455. as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
  456. The input field must not contain any labels or use the specified label prefix
  457. unless it is ok for those words to be ignored. For an example consult the
  458. dataset pulled by the example script word-vector-example.sh, which is
  459. part of the fastText repository.
  460. """
  461. arg_names = ['input', 'model', 'lr', 'dim', 'ws', 'epoch', 'minCount',
  462. 'minCountLabel', 'minn', 'maxn', 'neg', 'wordNgrams', 'loss', 'bucket',
  463. 'thread', 'lrUpdateRate', 't', 'label', 'verbose', 'pretrainedVectors']
  464. args, manually_set_args = read_args(kargs, kwargs, arg_names,
  465. unsupervised_default)
  466. a = _build_args(args, manually_set_args)
  467. ft = _FastText(args=a)
  468. fasttext.train(ft.f, a)
  469. ft.set_args(ft.f.getArgs())
  470. return ft
  471. def cbow(*kargs, **kwargs):
  472. raise Exception("`cbow` is not supported any more. Please use `train_unsupervised` with model=`cbow`. For more information please refer to https://fasttext.cc/blog/2019/06/25/blog-post.html#2-you-were-using-the-unofficial-fasttext-module")
  473. def skipgram(*kargs, **kwargs):
  474. raise Exception("`skipgram` is not supported any more. Please use `train_unsupervised` with model=`skipgram`. For more information please refer to https://fasttext.cc/blog/2019/06/25/blog-post.html#2-you-were-using-the-unofficial-fasttext-module")
  475. def supervised(*kargs, **kwargs):
  476. raise Exception("`supervised` is not supported any more. Please use `train_supervised`. For more information please refer to https://fasttext.cc/blog/2019/06/25/blog-post.html#2-you-were-using-the-unofficial-fasttext-module")