FastText.py 16 KB

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