gensim logo

gensim
gensim tagline

Get Expert Help From The Gensim Authors

Consulting in Machine Learning & NLP

• Commercial document similarity engine: ScaleText.ai

Corporate trainings in Python Data Science and Deep Learning

models.fasttext – FastText model

models.fasttext – FastText model

Learn word representations via Fasttext: Enriching Word Vectors with Subword Information.

This module allows training word embeddings from a training corpus with the additional ability to obtain word vectors for out-of-vocabulary words.

This module contains a fast native C implementation of Fasttext with Python interfaces. It is not only a wrapper around Facebook’s implementation.

For a tutorial see this noteboook.

Make sure you have a C compiler before installing Gensim, to use the optimized (compiled) Fasttext training routines.

Usage examples

Initialize and train a model:

>>> from gensim.test.utils import common_texts
>>> from gensim.models import FastText
>>>
>>> model = FastText(common_texts, size=4, window=3, min_count=1, iter=10)

Persist a model to disk with:

>>> from gensim.test.utils import get_tmpfile
>>>
>>> fname = get_tmpfile("fasttext.model")
>>>
>>> model.save(fname)
>>> model = FastText.load(fname)  # you can continue training with the loaded model!

Retrieve word-vector for vocab and out-of-vocab word:

>>> existent_word = "computer"
>>> existent_word in model.wv.vocab
True
>>> computer_vec = model.wv[existent_word]  # numpy vector of a word
>>>
>>> oov_word = "graph-out-of-vocab"
>>> oov_word in model.wv.vocab
False
>>> oov_vec = model.wv[oov_word]  # numpy vector for OOV word

You can perform various NLP word tasks with the model, some of them are already built-in:

>>> similarities = model.wv.most_similar(positive=['computer', 'human'], negative=['interface'])
>>> most_similar = similarities[0]
>>>
>>> similarities = model.wv.most_similar_cosmul(positive=['computer', 'human'], negative=['interface'])
>>> most_similar = similarities[0]
>>>
>>> not_matching = model.wv.doesnt_match("human computer interface tree".split())
>>>
>>> sim_score = model.wv.similarity('computer', 'human')

Correlation with human opinion on word similarity:

>>> from gensim.test.utils import datapath
>>>
>>> similarities = model.wv.evaluate_word_pairs(datapath('wordsim353.tsv'))

And on word analogies:

>>> analogies_result = model.wv.accuracy(datapath('questions-words.txt'))
class gensim.models.fasttext.FastText(sentences=None, sg=0, hs=0, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, word_ngrams=1, sample=0.001, seed=1, workers=3, min_alpha=0.0001, negative=5, ns_exponent=0.75, cbow_mean=1, hashfxn=<built-in function hash>, iter=5, null_word=0, min_n=3, max_n=6, sorted_vocab=1, bucket=2000000, trim_rule=None, batch_words=10000, callbacks=())

Bases: gensim.models.base_any2vec.BaseWordEmbeddingsModel

Train, use and evaluate word representations learned using the method described in Enriching Word Vectors with Subword Information, aka FastText.

The model can be stored/loaded via its save() and load() methods, or loaded from a format compatible with the original Fasttext implementation via load_fasttext_format().

Some important internal attributes are the following:

wv

FastTextKeyedVectors – This object essentially contains the mapping between words and embeddings. These are similar to the embeddings computed in the Word2Vec, however here we also include vectors for n-grams. This allows the model to compute embeddings even for unseen words (that do not exist in the vocabulary), as the aggregate of the n-grams included in the word. After training the model, this attribute can be used directly to query those embeddings in various ways. Check the module level docstring from some examples.

vocabulary

FastTextVocab – This object represents the vocabulary of the model. Besides keeping track of all unique words, this object provides extra functionality, such as constructing a huffman tree (frequent words are closer to the root), or discarding extremely rare words.

trainables

FastTextTrainables – This object represents the inner shallow neural network used to train the embeddings. This is very similar to the network of the Word2Vec model, but it also trains weights for the N-Grams (sequences of more than 1 words). The semantics of the network are almost the same as the one used for the Word2Vec model. You can think of it as a NN with a single projection and hidden layer which we train on the corpus. The weights are then used as our embeddings. An important difference however between the two models, is the scoring function used to compute the loss. In the case of FastText, this is modified in word to also account for the internal structure of words, besides their concurrence counts.

Parameters:
  • sentences (iterable of list of str, optional) – Can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See BrownCorpus, Text8Corpus or LineSentence in word2vec module for such examples. If you don’t supply sentences, the model is left uninitialized – use if you plan to initialize it in some other way.
  • min_count (int, optional) – The model ignores all words with total frequency lower than this.
  • size (int, optional) – Dimensionality of the word vectors.
  • window (int, optional) – The maximum distance between the current and predicted word within a sentence.
  • workers (int, optional) – Use these many worker threads to train the model (=faster training with multicore machines).
  • alpha (float, optional) – The initial learning rate.
  • min_alpha (float, optional) – Learning rate will linearly drop to min_alpha as training progresses.
  • sg ({1, 0}, optional) – Training algorithm: skip-gram if sg=1, otherwise CBOW.
  • hs ({1,0}, optional) – If 1, hierarchical softmax will be used for model training. If set to 0, and negative is non-zero, negative sampling will be used.
  • seed (int, optional) – Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + str(seed). Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (workers=1), to eliminate ordering jitter from OS thread scheduling. (In Python 3, reproducibility between interpreter launches also requires use of the PYTHONHASHSEED environment variable to control hash randomization).
  • max_vocab_size (int, optional) – Limits the RAM during vocabulary building; if there are more unique words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM. Set to None for no limit.
  • sample (float, optional) – The threshold for configuring which higher-frequency words are randomly downsampled, useful range is (0, 1e-5).
  • negative (int, optional) – If > 0, negative sampling will be used, the int for negative specifies how many “noise words” should be drawn (usually between 5-20). If set to 0, no negative sampling is used.
  • ns_exponent (float, optional) – The exponent used to shape the negative sampling distribution. A value of 1.0 samples exactly in proportion to the frequencies, 0.0 samples all words equally, while a negative value samples low-frequency words more than high-frequency words. The popular default value of 0.75 was chosen by the original Word2Vec paper. More recently, in https://arxiv.org/abs/1804.04212, Caselles-Dupré, Lesaint, & Royo-Letelier suggest that other values may perform better for recommendation applications.
  • cbow_mean ({1,0}, optional) – If 0, use the sum of the context word vectors. If 1, use the mean, only applies when cbow is used.
  • hashfxn (function, optional) – Hash function to use to randomly initialize weights, for increased training reproducibility.
  • iter (int, optional) – Number of iterations (epochs) over the corpus.
  • trim_rule (function, optional) –

    Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to keep_vocab_item()), or a callable that accepts parameters (word, count, min_count) and returns either gensim.utils.RULE_DISCARD, gensim.utils.RULE_KEEP or gensim.utils.RULE_DEFAULT. The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of themodel.

    The input parameters are of the following types:
    • word (str) - the word we are examining
    • count (int) - the word’s frequency count in the corpus
    • min_count (int) - the minimum count threshold.
  • sorted_vocab ({1,0}, optional) – If 1, sort the vocabulary by descending frequency before assigning word indices.
  • batch_words (int, optional) – Target size (in words) for batches of examples passed to worker threads (and thus cython routines).(Larger batches will be passed if individual texts are longer than 10000 words, but the standard cython code truncates to that maximum.)
  • min_n (int, optional) – Minimum length of char n-grams to be used for training word representations.
  • max_n (int, optional) – Max length of char ngrams to be used for training word representations. Set max_n to be lesser than min_n to avoid char ngrams being used.
  • word_ngrams ({1,0}, optional) – If 1, uses enriches word vectors with subword(n-grams) information. If 0, this is equivalent to Word2Vec.
  • bucket (int, optional) – Character ngrams are hashed into a fixed number of buckets, in order to limit the memory usage of the model. This option specifies the number of buckets used by the model.
  • callbacks – List of callbacks that need to be executed/run at specific stages during training.

Examples

Initialize and train a FastText model:

>>> from gensim.models import FastText
>>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]]
>>>
>>> model = FastText(sentences, min_count=1)
>>> say_vector = model['say']  # get vector for a word
>>> of_vector = model['of']  # get vector for an out-of-vocab word
__getitem__(*args, **kwargs)

Deprecated. Use self.wv.__getitem__() instead.

Refer to the documentation for gensim.models.keyedvectors.KeyedVectors.__getitem__()

accuracy(*args, **kwargs)
bucket
build_vocab(sentences, update=False, progress_per=10000, keep_raw_vocab=False, trim_rule=None, **kwargs)

Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings.

Parameters:
  • sentences (iterable of list of str) – Can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See BrownCorpus, Text8Corpus or LineSentence in word2vec module for such examples.
  • update (bool) – If true, the new words in sentences will be added to model’s vocab.
  • progress_per (int) – Indicates how many words to process before showing/updating the progress.
  • keep_raw_vocab (bool) – If not true, delete the raw vocabulary after the scaling is done and free up RAM.
  • trim_rule (function, optional) –

    Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to keep_vocab_item()), or a callable that accepts parameters (word, count, min_count) and returns either gensim.utils.RULE_DISCARD, gensim.utils.RULE_KEEP or gensim.utils.RULE_DEFAULT. The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of the model.

    The input parameters are of the following types:
    • word (str) - the word we are examining
    • count (int) - the word’s frequency count in the corpus
    • min_count (int) - the minimum count threshold.
  • **kwargs – Additional key word parameters passed to build_vocab().

Examples

Train a model and update vocab for online training

>>> from gensim.models import FastText
>>> sentences_1 = [["cat", "say", "meow"], ["dog", "say", "woof"]]
>>> sentences_2 = [["dude", "say", "wazzup!"]]
>>>
>>> model = FastText(min_count=1)
>>> model.build_vocab(sentences_1)
>>> model.train(sentences_1, total_examples=model.corpus_count, epochs=model.iter)
>>>
>>> model.build_vocab(sentences_2, update=True)
>>> model.train(sentences_2, total_examples=model.corpus_count, epochs=model.iter)
build_vocab_from_freq(word_freq, keep_raw_vocab=False, corpus_count=None, trim_rule=None, update=False)

Build vocabulary from a dictionary of word frequencies.

Parameters:
  • word_freq (dict of (str, int)) – A mapping from a word in the vocabulary to its frequency count.
  • keep_raw_vocab (bool, optional) – If False, delete the raw vocabulary after the scaling is done to free up RAM.
  • corpus_count (int, optional) – Even if no corpus is provided, this argument can set corpus_count explicitly.
  • trim_rule (function, optional) –

    Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to keep_vocab_item()), or a callable that accepts parameters (word, count, min_count) and returns either gensim.utils.RULE_DISCARD, gensim.utils.RULE_KEEP or gensim.utils.RULE_DEFAULT. The rule, if given, is only used to prune vocabulary during current method call and is not stored as part of the model.

    The input parameters are of the following types:
    • word (str) - the word we are examining
    • count (int) - the word’s frequency count in the corpus
    • min_count (int) - the minimum count threshold.
  • update (bool, optional) – If true, the new provided words in word_freq dict will be added to model’s vocab.
clear_sims()

Remove all L2-normalized word vectors from the model, to free up memory.

You can recompute them later again using the init_sims() method.

cum_table
doesnt_match(*args, **kwargs)

Deprecated, use self.wv.doesnt_match() instead.

Refer to the documentation for doesnt_match().

estimate_memory(vocab_size=None, report=None)
evaluate_word_pairs(*args, **kwargs)

Deprecated, use self.wv.evaluate_word_pairs() instead.

Refer to the documentation for evaluate_word_pairs().

hashfxn
init_sims(replace=False)

Precompute L2-normalized vectors.

Parameters:replace (bool) – If True, forget the original vectors and only keep the normalized ones to save RAM.
iter
layer1_size
classmethod load(*args, **kwargs)

Load a previously saved FastText model.

Parameters:fname (str) – Path to the saved file.
Returns:Loaded model.
Return type:FastText

See also

save()
Save FastText model.
load_binary_data(encoding='utf8')

Load data from a binary file created by Facebook’s native FastText.

Parameters:encoding (str, optional) – Specifies the encoding.
classmethod load_fasttext_format(model_file, encoding='utf8')

Load the input-hidden weight matrix from Facebook’s native fasttext .bin and .vec output files.

Notes

Due to limitations in the FastText API, you cannot continue training with a model loaded this way.

Parameters:
  • model_file (str) – Path to the FastText output files. FastText outputs two model files - /path/to/model.vec and /path/to/model.bin Expected value for this example: /path/to/model or /path/to/model.bin, as Gensim requires only .bin file to the load entire fastText model.
  • encoding (str, optional) – Specifies the file encoding.
Returns:

The loaded model.

Return type:

class: ~gensim.models.fasttext.FastText

max_n
min_count
min_n
most_similar(*args, **kwargs)

Deprecated, use self.wv.most_similar() instead.

Refer to the documentation for most_similar().

most_similar_cosmul(*args, **kwargs)

Deprecated, use self.wv.most_similar_cosmul() instead.

Refer to the documentation for most_similar_cosmul().

n_similarity(*args, **kwargs)

Deprecated, use self.wv.n_similarity() instead.

Refer to the documentation for n_similarity().

num_ngram_vectors
sample
save(*args, **kwargs)

Save the Fasttext model. This saved model can be loaded again using load(), which supports incremental training and getting vectors for out-of-vocabulary words.

Parameters:fname (str) – Store the model to this file.

See also

load()
Load FastText model.
similar_by_vector(*args, **kwargs)

Deprecated, use self.wv.similar_by_vector() instead.

Refer to the documentation for similar_by_vector().

similar_by_word(*args, **kwargs)

Deprecated, use self.wv.similar_by_word() instead.

Refer to the documentation for similar_by_word().

similarity(*args, **kwargs)

Deprecated, use self.wv.similarity() instead.

Refer to the documentation for similarity().

struct_unpack(file_handle, fmt)

Read a single object from an open file.

Parameters:
  • file_handle (file_like object) – Handle to an open file
  • fmt (str) – Byte format in which the structure is saved.
Returns:

Unpacked structure.

Return type:

Tuple of (str)

syn0_lockf
syn0_ngrams_lockf
syn0_vocab_lockf
syn1
syn1neg
train(sentences, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0, callbacks=(), **kwargs)

Update the model’s neural weights from a sequence of sentences (can be a once-only generator stream). For FastText, each sentence must be a list of unicode strings.

To support linear learning-rate decay from (initial) alpha to min_alpha, and accurate progress-percentage logging, either total_examples (count of sentences) or total_words (count of raw words in sentences) MUST be provided. If sentences is the same corpus that was provided to build_vocab() earlier, you can simply use total_examples=self.corpus_count.

To avoid common mistakes around the model’s ability to do multiple training passes itself, an explicit epochs argument MUST be provided. In the common and recommended case where train() is only called once, you can set epochs=self.iter.

Parameters:
  • sentences (iterable of iterables) – The sentences iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See BrownCorpus, Text8Corpus or LineSentence in word2vec module for such examples.
  • total_examples (int) – Count of sentences.
  • total_words (int) – Count of raw words in sentences.
  • epochs (int) – Number of iterations (epochs) over the corpus.
  • start_alpha (float, optional) – Initial learning rate. If supplied, replaces the starting alpha from the constructor, for this one call to train(). Use only if making multiple calls to train(), when you want to manage the alpha learning-rate yourself (not recommended).
  • end_alpha (float, optional) – Final learning rate. Drops linearly from start_alpha. If supplied, this replaces the final min_alpha from the constructor, for this one call to train(). Use only if making multiple calls to train(), when you want to manage the alpha learning-rate yourself (not recommended).
  • word_count (int) – Count of words already trained. Set this to 0 for the usual case of training on all words in sentences.
  • queue_factor (int) – Multiplier for size of queue (number of workers * queue_factor).
  • report_delay (float) – Seconds to wait before reporting progress.
  • callbacks – List of callbacks that need to be executed/run at specific stages during training.

Examples

>>> from gensim.models import FastText
>>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]]
>>>
>>> model = FastText(min_count=1)
>>> model.build_vocab(sentences)
>>> model.train(sentences, total_examples=model.corpus_count, epochs=model.iter)
wmdistance(*args, **kwargs)

Deprecated, use self.wv.wmdistance() instead.

Refer to the documentation for wmdistance().

class gensim.models.fasttext.FastTextTrainables(vector_size=100, seed=1, hashfxn=<built-in function hash>, bucket=2000000)

Bases: gensim.models.word2vec.Word2VecTrainables

Represents the inner shallow neural network used to train FastText.

get_vocab_word_vecs(wv)

Calculate vectors for words in vocabulary and stores them in vectors.

init_ngrams_post_load(file_name, wv)

Compute ngrams of all words present in vocabulary, and store vectors for only those ngrams.

Vectors for other ngrams are initialized with a random uniform distribution in FastText. These vectors are discarded here to save space.

init_ngrams_weights(wv, update=False, vocabulary=None)

Compute ngrams of all words present in vocabulary and stores vectors for only those ngrams. Vectors for other ngrams are initialized with a random uniform distribution in FastText.

Parameters:update (bool) – If True, the new vocab words and their new ngrams word vectors are initialized with random uniform distribution and updated/added to the existing vocab word and ngram vectors.
load(fname, mmap=None)

Load an object previously saved using save() from a file.

Parameters:
  • fname (str) – Path to file that contains needed object.
  • mmap (str, optional) – Memory-map option. If the object was saved with large arrays stored separately, you can load these arrays via mmap (shared memory) using mmap=’r’. If the file being loaded is compressed (either ‘.gz’ or ‘.bz2’), then `mmap=None must be set.

See also

save()
Save object to file.
Returns:Object loaded from fname.
Return type:object
Raises:AttributeError – When called on an object instance instead of class (this is a class method).
prepare_weights(hs, negative, wv, update=False, vocabulary=None)
reset_ngrams_weights(wv)

Reset all projection weights to an initial (untrained) state, but keep the existing vocabulary and their ngrams.

reset_weights(hs, negative, wv)

Reset all projection weights to an initial (untrained) state, but keep the existing vocabulary.

save(fname_or_handle, separately=None, sep_limit=10485760, ignore=frozenset([]), pickle_protocol=2)

Save the object to a file.

Parameters:
  • fname_or_handle (str or file-like) – Path to output file or already opened file-like object. If the object is a file handle, no special array handling will be performed, all attributes will be saved to the same file.
  • separately (list of str or None, optional) –

    If None, automatically detect large numpy/scipy.sparse arrays in the object being stored, and store them into separate files. This prevent memory errors for large objects, and also allows memory-mapping the large arrays for efficient loading and sharing the large arrays in RAM between multiple processes.

    If list of str: store these attributes into separate files. The automated size check is not performed in this case.

  • sep_limit (int, optional) – Don’t store arrays smaller than this separately. In bytes.
  • ignore (frozenset of str, optional) – Attributes that shouldn’t be stored at all.
  • pickle_protocol (int, optional) – Protocol number for pickle.

See also

load()
Load object from file.
seeded_vector(seed_string, vector_size)

Get a random vector (but deterministic by seed_string).

update_weights(hs, negative, wv)

Copy all the existing weights, and reset the weights for the newly added vocabulary.

class gensim.models.fasttext.FastTextVocab(max_vocab_size=None, min_count=5, sample=0.001, sorted_vocab=True, null_word=0, ns_exponent=0.75)

Bases: gensim.models.word2vec.Word2VecVocab

Vocabulary used by FastText.

add_null_word(wv)
create_binary_tree(wv)

Create a binary Huffman tree using stored vocabulary word counts. Frequent words will have shorter binary codes. Called internally from build_vocab().

load(fname, mmap=None)

Load an object previously saved using save() from a file.

Parameters:
  • fname (str) – Path to file that contains needed object.
  • mmap (str, optional) – Memory-map option. If the object was saved with large arrays stored separately, you can load these arrays via mmap (shared memory) using mmap=’r’. If the file being loaded is compressed (either ‘.gz’ or ‘.bz2’), then `mmap=None must be set.

See also

save()
Save object to file.
Returns:Object loaded from fname.
Return type:object
Raises:AttributeError – When called on an object instance instead of class (this is a class method).
make_cum_table(wv, domain=2147483647)

Create a cumulative-distribution table using stored vocabulary word counts for drawing random words in the negative-sampling training routines.

To draw a word index, choose a random integer up to the maximum value in the table (cum_table[-1]), then finding that integer’s sorted insertion point (as if by bisect_left or ndarray.searchsorted()). That insertion point is the drawn index, coming up in proportion equal to the increment at that slot.

Called internally from build_vocab().

prepare_vocab(hs, negative, wv, update=False, keep_raw_vocab=False, trim_rule=None, min_count=None, sample=None, dry_run=False)
save(fname_or_handle, separately=None, sep_limit=10485760, ignore=frozenset([]), pickle_protocol=2)

Save the object to a file.

Parameters:
  • fname_or_handle (str or file-like) – Path to output file or already opened file-like object. If the object is a file handle, no special array handling will be performed, all attributes will be saved to the same file.
  • separately (list of str or None, optional) –

    If None, automatically detect large numpy/scipy.sparse arrays in the object being stored, and store them into separate files. This prevent memory errors for large objects, and also allows memory-mapping the large arrays for efficient loading and sharing the large arrays in RAM between multiple processes.

    If list of str: store these attributes into separate files. The automated size check is not performed in this case.

  • sep_limit (int, optional) – Don’t store arrays smaller than this separately. In bytes.
  • ignore (frozenset of str, optional) – Attributes that shouldn’t be stored at all.
  • pickle_protocol (int, optional) – Protocol number for pickle.

See also

load()
Load object from file.
scan_vocab(sentences, progress_per=10000, trim_rule=None)

Do an initial scan of all words appearing in sentences.

sort_vocab(wv)

Sort the vocabulary so the most frequent words have the lowest indexes.