Skip to content

Instantly share code, notes, and snippets.

@Helw150
Last active April 13, 2019 12:32
Show Gist options
  • Save Helw150/169318d7abed7ac519df7b3d39697236 to your computer and use it in GitHub Desktop.
Save Helw150/169318d7abed7ac519df7b3d39697236 to your computer and use it in GitHub Desktop.
Saves a dictionary of vectors into the Gensim KeyedVectors format
from gensim import utils
def save2gensim(fname, word2vec_dict):
vectors = list(word2vec_dict.values())
vector_size = vectors[0].shape[0]
total_vec = len(vectors)
with utils.smart_open(fname, 'wb') as fout:
fout.write(utils.to_utf8("%s %s\n" % (total_vec, vector_size)))
# store in sorted order: most frequent words at the top
for word, vector in word2vec_dict.items():
fout.write(utils.to_utf8("%s %s\n" % (word, ' '.join(repr(val) for val in vector))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment