FastText.py 17 KB

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