Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug Fix 1779 #1787

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 7 additions & 31 deletions gensim/models/wrappers/fasttext.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Jayant Jain <jayantjain1992@gmail.com>
# Copyright (C) 2017 Radim Rehurek <me@radimrehurek.com>
# Copyright (C) 2017 Radim Rehurek <radim@rare-technologies.com>
# Copyright (C) 2017 Carl Saroufim <carl_saroufim@hotmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html


Expand Down Expand Up @@ -390,10 +390,7 @@ def struct_unpack(self, file_handle, fmt):

def init_ngrams(self):
"""
Computes 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. These
vectors are discarded here to save space.

Computes ngrams of all words present in vocabulary and stores vectors for those ngrams.
"""
self.wv.ngrams = {}
all_ngrams = []
Expand All @@ -403,32 +400,11 @@ def init_ngrams(self):
all_ngrams += compute_ngrams(w, self.wv.min_n, self.wv.max_n)
self.wv.syn0[vocab.index] += np.array(self.wv.syn0_ngrams[vocab.index])

all_ngrams = set(all_ngrams)
self.num_ngram_vectors = len(all_ngrams)
ngram_indices = []
for i, ngram in enumerate(all_ngrams):
ngram_hash = ft_hash(ngram)
ngram_indices.append(len(self.wv.vocab) + ngram_hash % self.bucket)
self.wv.ngrams[ngram] = i
self.wv.syn0_ngrams = self.wv.syn0_ngrams.take(ngram_indices, axis=0)

ngram_weights = self.wv.syn0_ngrams

logger.info(
"loading weights for %s words for fastText model from %s",
len(self.wv.vocab), self.file_name
)
self.wv.syn0_ngrams = self.wv.syn0_ngrams[len(self.wv.vocab):]

for w, vocab in self.wv.vocab.items():
word_ngrams = compute_ngrams(w, self.wv.min_n, self.wv.max_n)
for word_ngram in word_ngrams:
self.wv.syn0[vocab.index] += np.array(ngram_weights[self.wv.ngrams[word_ngram]])

self.wv.syn0[vocab.index] /= (len(word_ngrams) + 1)
logger.info(
"loaded %s weight matrix for fastText model from %s",
self.wv.syn0.shape, self.file_name
)
all_ngrams = set(all_ngrams)
for ngram in all_ngrams:
self.wv.ngrams[ngram] = ft_hash(ngram) % self.bucket


def compute_ngrams(word, min_n, max_n):
Expand Down