FastText.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 reference to 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 reference to 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. def set_matrices(self, input_matrix, output_matrix):
  255. """
  256. Set input and output matrices. This function assumes you know what you
  257. are doing.
  258. """
  259. self.f.setMatrices(input_matrix.astype(np.float32),
  260. output_matrix.astype(np.float32))
  261. @property
  262. def words(self):
  263. if self._words is None:
  264. self._words = self.get_words()
  265. return self._words
  266. @property
  267. def labels(self):
  268. if self._labels is None:
  269. self._labels = self.get_labels()
  270. return self._labels
  271. def __getitem__(self, word):
  272. return self.get_word_vector(word)
  273. def __contains__(self, word):
  274. return word in self.words
  275. def _parse_model_string(string):
  276. if string == "cbow":
  277. return model_name.cbow
  278. if string == "skipgram":
  279. return model_name.skipgram
  280. if string == "supervised":
  281. return model_name.supervised
  282. else:
  283. raise ValueError("Unrecognized model name")
  284. def _parse_loss_string(string):
  285. if string == "ns":
  286. return loss_name.ns
  287. if string == "hs":
  288. return loss_name.hs
  289. if string == "softmax":
  290. return loss_name.softmax
  291. if string == "ova":
  292. return loss_name.ova
  293. else:
  294. raise ValueError("Unrecognized loss name")
  295. def _build_args(args, manually_set_args):
  296. args["model"] = _parse_model_string(args["model"])
  297. args["loss"] = _parse_loss_string(args["loss"])
  298. if type(args["autotuneModelSize"]) == int:
  299. args["autotuneModelSize"] = str(args["autotuneModelSize"])
  300. a = fasttext.args()
  301. for (k, v) in args.items():
  302. setattr(a, k, v)
  303. if k in manually_set_args:
  304. a.setManual(k)
  305. a.output = "" # User should use save_model
  306. a.saveOutput = 0 # Never use this
  307. if a.wordNgrams <= 1 and a.maxn == 0:
  308. a.bucket = 0
  309. return a
  310. def tokenize(text):
  311. """Given a string of text, tokenize it and return a list of tokens"""
  312. f = fasttext.fasttext()
  313. return f.tokenize(text)
  314. def load_model(path):
  315. """Load a model given a filepath and return a model object."""
  316. eprint("Warning : `load_model` does not return WordVectorModel or SupervisedModel any more, but a `FastText` object which is very similar.")
  317. return _FastText(model_path=path)
  318. unsupervised_default = {
  319. 'model': "skipgram",
  320. 'lr': 0.05,
  321. 'dim': 100,
  322. 'ws': 5,
  323. 'epoch': 5,
  324. 'minCount': 5,
  325. 'minCountLabel': 0,
  326. 'minn': 3,
  327. 'maxn': 6,
  328. 'neg': 5,
  329. 'wordNgrams': 1,
  330. 'loss': "ns",
  331. 'bucket': 2000000,
  332. 'thread': multiprocessing.cpu_count() - 1,
  333. 'lrUpdateRate': 100,
  334. 't': 1e-4,
  335. 'label': "__label__",
  336. 'verbose': 2,
  337. 'pretrainedVectors': "",
  338. 'seed': 0,
  339. 'autotuneValidationFile': "",
  340. 'autotuneMetric': "f1",
  341. 'autotunePredictions': 1,
  342. 'autotuneDuration': 60 * 5, # 5 minutes
  343. 'autotuneModelSize': ""
  344. }
  345. def read_args(arg_list, arg_dict, arg_names, default_values):
  346. param_map = {
  347. 'min_count': 'minCount',
  348. 'word_ngrams': 'wordNgrams',
  349. 'lr_update_rate': 'lrUpdateRate',
  350. 'label_prefix': 'label',
  351. 'pretrained_vectors': 'pretrainedVectors'
  352. }
  353. ret = {}
  354. manually_set_args = set()
  355. for (arg_name, arg_value) in chain(zip(arg_names, arg_list), arg_dict.items()):
  356. if arg_name in param_map:
  357. arg_name = param_map[arg_name]
  358. if arg_name not in arg_names:
  359. raise TypeError("unexpected keyword argument '%s'" % arg_name)
  360. if arg_name in ret:
  361. raise TypeError("multiple values for argument '%s'" % arg_name)
  362. ret[arg_name] = arg_value
  363. manually_set_args.add(arg_name)
  364. for (arg_name, arg_value) in default_values.items():
  365. if arg_name not in ret:
  366. ret[arg_name] = arg_value
  367. return (ret, manually_set_args)
  368. def train_supervised(*kargs, **kwargs):
  369. """
  370. Train a supervised model and return a model object.
  371. input must be a filepath. The input text does not need to be tokenized
  372. as per the tokenize function, but it must be preprocessed and encoded
  373. as UTF-8. You might want to consult standard preprocessing scripts such
  374. as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
  375. The input file must must contain at least one label per line. For an
  376. example consult the example datasets which are part of the fastText
  377. repository such as the dataset pulled by classification-example.sh.
  378. """
  379. supervised_default = unsupervised_default.copy()
  380. supervised_default.update({
  381. 'lr': 0.1,
  382. 'minCount': 1,
  383. 'minn': 0,
  384. 'maxn': 0,
  385. 'loss': "softmax",
  386. 'model': "supervised"
  387. })
  388. arg_names = ['input', 'lr', 'dim', 'ws', 'epoch', 'minCount',
  389. 'minCountLabel', 'minn', 'maxn', 'neg', 'wordNgrams', 'loss', 'bucket',
  390. 'thread', 'lrUpdateRate', 't', 'label', 'verbose', 'pretrainedVectors',
  391. 'seed', 'autotuneValidationFile', 'autotuneMetric',
  392. 'autotunePredictions', 'autotuneDuration', 'autotuneModelSize']
  393. args, manually_set_args = read_args(kargs, kwargs, arg_names,
  394. supervised_default)
  395. a = _build_args(args, manually_set_args)
  396. ft = _FastText(args=a)
  397. fasttext.train(ft.f, a)
  398. ft.set_args(ft.f.getArgs())
  399. return ft
  400. def train_unsupervised(*kargs, **kwargs):
  401. """
  402. Train an unsupervised model and return a model object.
  403. input must be a filepath. The input text does not need to be tokenized
  404. as per the tokenize function, but it must be preprocessed and encoded
  405. as UTF-8. You might want to consult standard preprocessing scripts such
  406. as tokenizer.perl mentioned here: http://www.statmt.org/wmt07/baseline.html
  407. The input field must not contain any labels or use the specified label prefix
  408. unless it is ok for those words to be ignored. For an example consult the
  409. dataset pulled by the example script word-vector-example.sh, which is
  410. part of the fastText repository.
  411. """
  412. arg_names = ['input', 'model', 'lr', 'dim', 'ws', 'epoch', 'minCount',
  413. 'minCountLabel', 'minn', 'maxn', 'neg', 'wordNgrams', 'loss', 'bucket',
  414. 'thread', 'lrUpdateRate', 't', 'label', 'verbose', 'pretrainedVectors']
  415. args, manually_set_args = read_args(kargs, kwargs, arg_names,
  416. unsupervised_default)
  417. a = _build_args(args, manually_set_args)
  418. ft = _FastText(args=a)
  419. fasttext.train(ft.f, a)
  420. ft.set_args(ft.f.getArgs())
  421. return ft
  422. def cbow(*kargs, **kwargs):
  423. 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")
  424. def skipgram(*kargs, **kwargs):
  425. 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")
  426. def supervised(*kargs, **kwargs):
  427. 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")