This tutorial is about using the Gensim wrapper for the FastText library for training FastText models, loading them and performing similarity operations and vector lookups analogous to Word2Vec.
The main principle behind FastText is that the morphological structure of a word carries important information about the meaning of the word, which is not taken into account by traditional word embeddings, which train a unique word embedding for every individual word. This is especially significant for morphologically rich languages (German, Turkish) in which a single word can have a large number of morphological forms, each of which might occur rarely, thus making it hard to train good word embeddings.
FastText attempts to solve this by treating each word as the aggregation of its subwords. For the sake of simplicity and language-independence, subwords are taken to the character ngrams of the word. The vector for a word is simply taken to be the sum of all vectors of its component char-ngrams.
According to a detailed comparison of Word2Vec and FastText in this notebook, FastText does significantly better on syntactic tasks as compared to the original Word2Vec, especially when the size of the training corpus is small. Word2Vec slightly outperforms FastText on semantic tasks though. The differences grow smaller as the size of training corpus increases.
Training time for FastText is significantly higher than the Gensim version of Word2Vec (15min 42s
vs 6min 42s
on text8, 17 mil tokens, 5 epochs, and a vector size of 100).
FastText can be used to obtain vectors for out-of-vocabulary (oov) words, by summing up vectors for its component char-ngrams, provided at least one of the char-ngrams was present in the training data.
For the following examples, we'll use the Lee Corpus (which you already have if you've installed gensim)
You need to have FastText setup locally to be able to train models. See installation instructions for FastText if you don't have FastText installed.
In [1]:
import gensim, os
from gensim.models.wrappers.fasttext import FastText
# Set FastText home to the path to the FastText executable
ft_home = '/home/jayant/Projects/fastText/fasttext'
# Set file names for train and test data
data_dir = '{}'.format(os.sep).join([gensim.__path__[0], 'test', 'test_data']) + os.sep
lee_train_file = data_dir + 'lee_background.cor'
model = FastText.train(ft_home, lee_train_file)
print(model)
Hyperparameters for training the model follow the same pattern as Word2Vec. FastText supports the folllowing parameters from the original word2vec -
- model: Training architecture. Allowed values: `cbow`, `skipgram` (Default `cbow`)
- size: Size of embeddings to be learnt (Default 100)
- alpha: Initial learning rate (Default 0.025)
- window: Context window size (Default 5)
- min_count: Ignore words with number of occurrences below this (Default 5)
- loss: Training objective. Allowed values: `ns`, `hs`, `softmax` (Default `ns`)
- sample: Threshold for downsampling higher-frequency words (Default 0.001)
- negative: Number of negative words to sample, for `ns` (Default 5)
- iter: Number of epochs (Default 5)
- sorted_vocab: Sort vocab by descending frequency (Default 1)
- threads: Number of threads to use (Default 12)
In addition, FastText has two additional parameters -
- min_n: min length of char ngrams to be used (Default 3)
- max_n: max length of char ngrams to be used for (Default 6)
These control the lengths of character ngrams that each word is broken down into while training and looking up embeddings. If max_n
is set to 0, or to be lesser than min_n
, no character ngrams are used, and the model effectively reduces to Word2Vec.
In [2]:
model = FastText.train(ft_home, lee_train_file, size=50, alpha=0.05, min_count=10)
print(model)
Continuation of training with FastText models is not supported.
Models can be saved and loaded via the load
and save
methods.
In [3]:
model.save('saved_fasttext_model')
loaded_model = FastText.load('saved_fasttext_model')
print(loaded_model)
The save_word2vec_method
causes the vectors for ngrams to be lost. As a result, a model loaded in this way will behave as a regular word2vec model.
In [4]:
print('night' in model.wv.vocab)
print('nights' in model.wv.vocab)
print(model['night'])
print(model['nights'])
The word vector lookup operation only works if atleast one of the component character ngrams is present in the training corpus. For example -
In [5]:
# Raises a KeyError since none of the character ngrams of the word `axe` are present in the training data
model['axe']
The in
operation works slightly differently from the original word2vec. It tests whether a vector for the given word exists or not, not whether the word is present in the word vocabulary. To test whether a word is present in the training word vocabulary -
In [6]:
# Tests if word present in vocab
print("word" in model.wv.vocab)
# Tests if vector present for word
print("word" in model)
Similarity operations work the same way as word2vec. Out-of-vocabulary words can also be used, provided they have atleast one character ngram present in the training data.
In [7]:
print("nights" in model.wv.vocab)
print("night" in model.wv.vocab)
model.similarity("night", "nights")
Out[7]:
Syntactically similar words generally have high similarity in FastText models, since a large number of the component char-ngrams will be the same. As a result, FastText generally does better at syntactic tasks than Word2Vec. A detailed comparison is provided here.
Other similarity operations -
In [8]:
# The example training corpus is a toy corpus, results are not expected to be good, for proof-of-concept only
model.most_similar("nights")
Out[8]:
In [9]:
model.n_similarity(['sushi', 'shop'], ['japanese', 'restaurant'])
Out[9]:
In [10]:
model.doesnt_match("breakfast cereal dinner lunch".split())
Out[10]:
In [11]:
model.most_similar(positive=['baghdad', 'england'], negative=['london'])
Out[11]:
In [13]:
model.accuracy(questions='questions-words.txt')
Out[13]:
In [15]:
# Word Movers distance
sentence_obama = 'Obama speaks to the media in Illinois'.lower().split()
sentence_president = 'The president greets the press in Chicago'.lower().split()
# Remove their stopwords.
from nltk.corpus import stopwords
stopwords = stopwords.words('english')
sentence_obama = [w for w in sentence_obama if w not in stopwords]
sentence_president = [w for w in sentence_president if w not in stopwords]
# Compute WMD.
distance = model.wmdistance(sentence_obama, sentence_president)
distance
Out[15]: