Skip to content

Instantly share code, notes, and snippets.

@bhaettasch
Created January 10, 2016 18:41
Show Gist options
  • Select an option

  • Save bhaettasch/d7f4e22e79df3c8b6c20 to your computer and use it in GitHub Desktop.

Select an option

Save bhaettasch/d7f4e22e79df3c8b6c20 to your computer and use it in GitHub Desktop.
Use gensim to load a word2vec model pretrained on google news and perform some simple actions with the word vectors.
from gensim.models import Word2Vec
# Load pretrained model (since intermediate data is not included, the model cannot be refined with additional data)
model = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True, norm_only=True)
dog = model['dog']
print(dog.shape)
print(dog[:10])
# Deal with an out of dictionary word: Михаил (Michail)
if 'Михаил' in model:
print(model['Михаил'].shape)
else:
print('{0} is an out of dictionary word'.format('Михаил'))
# Some predefined functions that show content related information for given words
print(model.most_similar(positive=['woman', 'king'], negative=['man']))
print(model.doesnt_match("breakfast cereal dinner lunch".split()))
print(model.similarity('woman', 'man'))
@maifeeulasad

Copy link
Copy Markdown

Download for here : https://s3.amazonaws.com/dl4j-distribution/GoogleNews-vectors-negative300.bin.gz

And use .bin.gz instead of .bin

@vanshika1396

Copy link
Copy Markdown

wordmodelfile=r"GoogleNews-vectors-negative300.bin.gz.gz"
wordmodel= gensim.models.KeyedVectors.load_word2vec_format(wordmodelfile, binary=True)

But i am getting error:
ValueError: invalid literal for int() with base 10: 'version'

Please help me to resolve this error.

@maifeeulasad

Copy link
Copy Markdown

@vanshika1396 have you tried removing the extra .gz from ...ative300.bin.gz.gz ?

@vanshika1396

vanshika1396 commented Feb 28, 2020

Copy link
Copy Markdown

@maifeeulasad have you tried removing the extra .gz from ...ative300.bin.gz.gz ?

...ative300.bin.gz.gz permission is not granted to change the name of the file.What else can be done, suggest?

@maifeeulasad

Copy link
Copy Markdown

@maifeeulasad have you tried removing the extra .gz from ...ative300.bin.gz.gz ?

...ative300.bin.gz.gz permission is not granted to change the name of the file.What else can be done, suggest?

If you are using windows, then open CMD with admin privilege and navigate to that directory.

Now execute command rename GoogleNews-vectors-negative300.bin.gz.gz GoogleNews-vectors-negative300.bin.gz

If you are on linux, there is mv and many more command

@mamad-knight

mamad-knight commented Mar 30, 2020

Copy link
Copy Markdown

wv = gensim.models.KeyedVectors.load_word2vec_format("E:\GoogleNews-vectors-negative300.bin", binary=True)
wv.init_sims(replace=True)

i'm using this. but i want to less RAM. is it possible to load the .bin file part by part? for example in 3 steps? in order to decrease the RAM usage?

@maifeeulasad

Copy link
Copy Markdown

@mamad-knight yes, anything can be done using computer, except getting girlfriend and some abstract ....
Now, I have never done this, so I'm not sure, but

import numpy as np
filepath = "../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin"

embeddings_index = {}
from gensim.models import KeyedVectors
wv_from_bin = KeyedVectors.load_word2vec_format(filepath, binary=True) 
for word, vector in zip(wv_from_bin.vocab, wv_from_bin.vectors):
    coefs = np.asarray(vector, dtype='float32')
    embeddings_index[word] = coefs

Try to split the file and read like this.

I found the code here.

Rest you have to take care, maybe you can knock me, not sure if I can help or not...

@mamad-knight

Copy link
Copy Markdown

Thanks for spending time, but i don't think it work. because the solution is not to load the whole .bin file. as soon as you load it, the RAM usage goes max.

@maifeeulasad

Copy link
Copy Markdown

try colab , not sure if they support such huge files @mamad-knight

@mamad-knight

mamad-knight commented Mar 31, 2020

Copy link
Copy Markdown

Thanks man. i'll try it. @maifeeulasad

@maifeeulasad

Copy link
Copy Markdown

Try passing the url, instead of passing the location of the file..
you may even need to write your own stream receiver too..
good luck, if I'm done, i will share..
and if anyone finishes earlier, please share..
@mamad-knight

@mamad-knight

Copy link
Copy Markdown

Thanks so much for spending time. i'll try it today or tomorrow. @maifeeulasad

@Pratikmehta1729

Copy link
Copy Markdown

Is there any API of this model so I can call it and get a vector for any word and without loading that model at my server? someone please help me with this, I am thinking this because my server can afford 4gb of ram for this model.
Thanks In advance.

@sboronghosh

Copy link
Copy Markdown

Since this example this deprecated, I created a Google Colab demo for the same.

@alexkamil

alexkamil commented Mar 19, 2021

Copy link
Copy Markdown

Reg "the model cannot be refined with additional data" - gensim has an online algorithm which allows to augment existing model (since 2015) https://rutumulkar.com/blog/2015/word2vec/

@senamosisa123

Copy link
Copy Markdown

AttributeError: The vocab attribute was removed from KeyedVector in Gensim 4.0.0.
Use KeyedVector's .key_to_index dict, .index_to_key list, and methods .get_vecattr(key, attr) and .set_vecattr(key, attr, new_val) instead.
See https://github.com/RaRe-Technologies/gensim/wiki/Migrating-from-Gensim-3.x-to-4

@AfricanLeo

Copy link
Copy Markdown

Google Colab demo

Thank you for the Colab demo !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment