FastText.py 19 KB

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