FastText.py 16 KB

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