- Introduced by
- Joulin, A.; Bojanowski, P.; Grave, E.; Mikolov, T. (Facebook AI Research)
- Year
- 2016
- Type
- Subword embedding model and linear text classifier
What does it do?
FastText is a word embedding and text classification method introduced by Facebook AI Research (Joulin, Bojanowski, Grave and Mikolov; papers published in 2017).
It represents each word as the sum of vectors for its character n-grams, so it can build a representation for words not seen during training, and it pairs this with a linear classifier designed to train quickly on large text collections.
The intuition behind the method
Word2Vec-style methods assign one vector to each whole word and cannot produce a vector for a word absent from training. FastText instead splits each word into overlapping character n-grams and learns a vector for each fragment; the whole word is also kept as a unit. For 'where' with n=3, the fragments include '<wh', 'whe', 'her', 'ere' and 're>', and the word's embedding is the sum of those fragment vectors. Related forms such as 'run', 'running' and 'runner' share fragments, so what is learned for one helps the others, and an unseen word still receives a vector if its fragments were learned from other words. For classification, the model averages the word embeddings of a document into one vector and passes it through a linear softmax layer. Because averaging discards word order, the approach trades structural detail for speed.
History
FastText grew out of two papers by Facebook AI Research authors. Bojanowski, Grave, Joulin and Mikolov (2017, Transactions of the ACL, 'Enriching Word Vectors with Subword Information') extended the skipgram model so that each word is represented as the sum of its character n-gram vectors. Joulin, Grave, Bojanowski and Mikolov (2017, EACL, 'Bag of Tricks for Efficient Text Classification') showed that averaging word embeddings and passing them through a linear classifier could be competitive with deep text classifiers at much lower cost. The subword-embedding contribution belongs to the TACL paper rather than the EACL paper. The authors released an open-source library and pre-trained vectors, which made the method widely used as a baseline.
When to use it
Choose FastText when you need word vectors or a fast classifier for a language with rich morphology, or for text with many rare, misspelled or novel word forms, and when training speed or hardware is limited. It is a reasonable fit for document classification with a moderate-to-large labelled corpus and many categories, for example sentiment, language identification, topic labelling or multi-label tagging. As a rough guide rather than an established threshold, corpora of tens of thousands of examples or more are a common setting for it. Do not choose it when word meaning depends on context, as in word-sense disambiguation or coreference, or when word order is essential to the label; a contextual Transformer model such as BERT is the usual alternative in those cases. Input should be tokenised text. For very small datasets, a bag-of-words baseline such as tf-idf with logistic regression should be compared first, since FastText does not reliably outperform it there. Compare against this baseline on your own data in any case.
Limitations and considerations
- Word representations are context-free: a word receives the same vector regardless of its meaning in a given sentence, unlike contextual models such as BERT or GPT.
- The mean-pooling document representation loses word order and syntactic structure, which can hurt performance on tasks that depend on composition.
- The number of distinct character n-grams grows with corpus size and with the n-gram range, which increases memory use. Implementations limit this by hashing n-grams into a fixed number of buckets, at the cost of collisions between unrelated fragments.
- On very small datasets, roughly a few hundred documents or fewer as a rough guide rather than an established threshold, a simple tf-idf plus logistic regression baseline may match or outperform FastText.
- The model is less suited to tasks that need fine-grained contextual disambiguation, such as named entity recognition or coreference resolution.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Builds vectors for out-of-vocabulary words by composing subword vectors, which suits morphologically rich languages such as Finnish, Turkish and Arabic, where many word forms are rare.
- Training is fast on large corpora because the model is shallow and the cost per token is small; speed is a central design goal of the cited papers.
- The averaged-embedding linear classifier is reported in the cited work to be competitive with deep convolutional text classifiers at much lower computational cost.
- Pre-trained vectors have been released for many languages, so embeddings can be used without local training.
- The classifier has one weight vector per class over the embedding dimensions, so per-class weights can be inspected directly.
Applications
- Word vectors for morphologically complex languages, where whole-word vocabularies are impractical.
- Fast text classification for sentiment analysis, topic detection, intent recognition and language identification.
- Initial embeddings for downstream NLP pipelines when computing resources are limited.
- Baseline for comparing more complex classifiers on text classification tasks.
- Multi-label categorisation with large label sets, such as product tagging.
How it works
How it works
Each word w is split into all character n-grams whose lengths fall within a chosen range; the typical setting for word vectors is 3 to 6 characters. The set G_w also includes the whole word as its own unit. G_w is the set of sub-units whose vectors are combined to form the representation of w.
Formula
\mathcal{G}_w = \{g : g \in \text{character n-grams of } w\} \cup \{w\}The vector for w is the sum of the learned vectors z_g for every unit g in G_w, as the formula shows. Because fragments are shared across words, morphologically related words tend to receive similar vectors, and a word unseen in training still gets a vector whenever its fragments were learned from other words.
Formula
\mathbf{v}_w = \sum_{g \in \mathcal{G}_w} \mathbf{z}_gEmbeddings are trained with the skipgram objective and negative sampling. The score for a target word and a context word is the dot product of the word vector and the context vector, passed through a logistic sigmoid. The objective raises this score for observed context words and lowers it for sampled negative words. Gradients from each update flow back into the fragment vectors, so the subword vectors are trained jointly.
Formula
\sum_{t=1}^{T} \sum_{c \in C_t} \left[ \log \sigma(\mathbf{v}_w^\top \mathbf{u}_{c}) + \sum_{n \in \mathcal{N}_{t,c}} \log \sigma(-\mathbf{v}_w^\top \mathbf{u}_{n}) \right]For classification, a document of N tokens is represented by the mean of its word vectors. This gives a fixed-size vector whatever the document length, but it treats the document as an unordered collection of words, so word order is not captured.
Formula
\hat{\mathbf{x}} = \frac{1}{N} \sum_{n=1}^{N} \mathbf{v}_{w_n}The document vector is passed through a linear layer and a softmax, which gives a probability for each class as the formula shows. The formula is the full softmax over all classes. For large label sets, the FastText classifier can use a hierarchical softmax instead, which reduces the cost of this output layer without changing the form of the model.
Formula
\hat{y} = \text{softmax}(\mathbf{W} \hat{\mathbf{x}} + \mathbf{b})Common pitfalls
- Expecting different vectors for the senses of a polysemous word such as 'bank': the model assigns the same vector in every sentence, so sense distinctions must come from elsewhere.
- Keeping default n-gram range and embedding dimension without tuning on a validation set, although the best range depends on the morphology of the language.
- Applying pre-trained multilingual vectors to a language whose script or morphology is poorly represented in the training data.
- Reporting accuracy alone on imbalanced classes, where a majority-class predictor can look strong; macro-averaged F1 or per-class precision and recall are more informative.
- Setting the hash bucket count too low for a large n-gram vocabulary, so that unrelated fragments share vectors and their information blurs together.
Frequently asked questions
How does FastText differ from Word2Vec?
Word2Vec assigns one vector per whole-word token and cannot represent words absent from training. FastText decomposes every word into character n-grams and sums their vectors, so it produces an embedding for any word, including misspellings and neologisms, by composing fragment representations. This makes FastText substantially more robust on morphologically rich languages and noisy text.
Should I use FastText or BERT for my NLP task?
FastText is preferable when training speed, low memory, and out-of-vocabulary robustness are priorities, or when GPU resources are unavailable. BERT and Transformer-based models are preferable when the task requires contextual word-sense disambiguation, when fine-grained linguistic structure matters, or when a pre-trained model can be fine-tuned on a moderately sized labelled dataset and inference latency is acceptable.
What n-gram range should I use?
The embedding model uses character n-grams, and the typical length range for word vectors is 3 to 6. The classifier has its own feature settings: word n-grams, such as adjacent word pairs, can be added as features, and some implementations can also enable character n-gram features for the classifier. For agglutinative languages with long affixes, the maximum character length may need to be larger than the default, so treat the minimum and maximum lengths as hyperparameters and tune them on a held-out validation set.
Can FastText handle multiple languages in one model?
Within limits. Because the embedding model works on character n-grams, a model trained on text in several languages that share a script can share subword vectors across them. Pre-trained multilingual vectors trained on Wikipedia are publicly available for many languages and can support cross-lingual transfer, but the quality for each language depends on how well it is represented in its training data.
Related methods
Sources
Joulin, A., Grave, E., Bojanowski, P. & Mikolov, T. (2017). Bag of Tricks for Efficient Text Classification. In Proceedings of EACL 2017, Short Papers, pp. 427–431. ACL.
Open DOI referenceBojanowski, P., Grave, E., Joulin, A. & Mikolov, T. (2017). Enriching Word Vectors with Subword Information. Transactions of the Association for Computational Linguistics, 5, 135–146.
Open DOI referenceGoldberg, Y. (2017). Neural Network Methods for Natural Language Processing. Morgan & Claypool Publishers.
ISBN: 978-1-62705-298-6