spaCy icon indicating copy to clipboard operation
spaCy copied to clipboard

Using custom word vectors in spaCy

Open viksit opened this issue 11 years ago • 16 comments

Hi @honnibal - what would be the best way to load custom word-embeddings into spacy?

Thanks!

viksit avatar Sep 10 '15 07:09 viksit

Hi,

This is much easier in the next version, which should be out this week --- I'm just finishing testing it. For now:

  • By default spaCy loads a data/vocab/vec.bin file, where the "data" directory is within the spacy.en module directory
  • Create the vec.bin file from a bz2 file using spacy.vocab.write_binary_vectors
  • Either replace spaCy's vec.bin file, or call nlp.vocab.load_rep_vectors at run-time, with the path to the binary file.

The above is a bit inconvenient at first, but the binary file format is much smaller and faster to load, and the vectors files are fairly big. Note that GloVe distributes in gzip format, not bzip.

Out of interest: are you using the GloVe vectors, or something you trained on your own data? If your own data, did you use Gensim? I'd like to make this much easier, so I'd appreciate suggestions for what work-flow you'd like to see.

Load new vectors at run-time, optionally converting them

    import spacy.vocab

    def set_spacy_vectors(nlp, binary_loc, bz2_loc=None):
        if bz2_loc is not None:
            spacy.vocab.write_binary_vectors(bz2_loc, binary_loc)
        write_binary_vectors(bz2_input_loc, binary_loc)

        nlp.vocab.load_rep_vectors(binary_loc)

Replace the vec.bin, so your vectors will be loaded by default


    from spacy.vocab import write_binary_vectors
    import spacy.en

    from os import path

    def main(bz2_loc):
        bin_loc = path.join(path.dirname(spacy.en.__file__), 'data', 'vocab', 'vec.bin')
        write_binary_vectors(bz2_loc, bin_loc)

if __name__ == '__main__':
    plac.call(main)

honnibal avatar Sep 10 '15 09:09 honnibal

Perfect, thank you - there was a thread about this on the gensim github issues incidentally and the approach suggested there is similar :)

Agree that gloVe vectors are becoming the standard - but my worry is that data load is going to take even longer. I've been thinking about a service that you load purely for vecs that runs locally - any thoughts?

Out of interest: are you using the GloVe vectors, or something you trained on your own data? If your own data, did you use Gensim? I'd like to make this much easier, so I'd appreciate suggestions for what work-flow you'd like to see.

I'm using vectors that I train myself. I've used gensim before, and also glove/google news. Glove has better performance in general from what I've seen, vs google news.

Ultimately, I've built my own network to train since I'm trying out a bunch of different kind of embeddings. I haven't yet figured how to load them into something else - so if I can convert them into the same format as glove, then I should be set.

viksit avatar Sep 10 '15 18:09 viksit

Yeah, the loading time is a problem. I think it should be possible to load asynchronously. That'd help a lot. On reflection the large GloVe vectors are also too big to be the default --- I don't want to ask people to download 2gb unless that's what they need. The download script should be a lot more sophisticated, and offer finer-grained options. This will come.

On Thursday, September 10, 2015, Viksit Gaur [email protected] wrote:

Perfect, thank you - there was a thread about this on the gensim github issues incidentally and the approach suggested there is similar :)

Agree that glove vectors are becoming the standard - but my worry is that data load is going to take even longer. I've been thinking about a service that you load purely for vecs - any thoughts?

— Reply to this email directly or view it on GitHub https://github.com/honnibal/spaCy/issues/95#issuecomment-139334813.

honnibal avatar Sep 10 '15 19:09 honnibal

But the GloVe vectors are really good, especially if you want to move to a bit more production battle testing. The biggest pre-trained dataset on the GloVe website is much bigger than 2GB actually! Ideally you can ran a separate service/server that acts as a in-memory lookup table for the vectors so you can start it once and link your program to it. Even if this is just an interface so you can implement it yourself however you see if. Preveiously I actually did a bit of experimenting with Redis for this. It's not great if you want to do nearest lookup...but that's not always required actually. Most of the time we just want the cosine distance between two words and that's fast! Good thing is as well that we can leverage it over to AWS and have it re-used by multiple processing nodes using the same lookup table.

RXminuS avatar Sep 17 '15 20:09 RXminuS

Additional documentation in progress here: http://spacy.io/tutorials/load-new-word-vectors/

The biggest data is 2gb there, as far as I can see? I'm counting this as the compressed size --- the raw text size is irrelevant.

Why do you need the larger vocabulary, by the way? I would expect that you'd see <1% of tokens outside the top 1m word vocabulary items, because of Zipf's law.

So I would guess that you'd be best off loading the frequent words into memory, and keeping the others in an mmap if you do need them. I'd anticipate you only need to load a few per session.

One of the best uses of the additional vocabulary is spelling correction. It'd be nice to load this into spaCy by default, as an orth-to-orth mapping. This way we wouldn't need a separate vector for the misspelled words.

honnibal avatar Sep 24 '15 09:09 honnibal

@honnibal As per https://spacy.io/tutorials/load-new-word-vectors, did you mean that any text file that contains the format you specify in that blog post, and bz2'd up, should work with

nlp.vocab.load_vectors("file.txt.bz2")

as long as this file is copied to the site-packages/spacy/data/en-1.0.9/vocab/ directory?

I just tried this with the following steps,

  • Take the glove file
  • Bz2 compress it
  • Copy to that directory
  • Run nlp = English() and nlp.vocab.load_vectors("filename")
  • 0 dimensions loaded

Any insights?

viksit avatar Mar 11 '16 20:03 viksit

Almost, you missed the step Replacing vec.bin in the tutorial. Please read it again. The tutorial says that the function spacy.vocab.write_binary_vectors takes a text file with a certain layout (one line per vector, space-delimited token + list of floats) and generates a spaCy-compatible binary, memory-efficient vector file. This vector can then be loaded with nlp.vocab.load_vectors.

Luckily we just created GloVe vectors (not officially announced yet). To use them please upgrade to latest spaCy version 0.100.6 and run:

$ sputnik --name spacy install en_glove_cc_300_1m_vectors

This downloads and installs following GloVe vectors: Common Crawl (840B tokens, 2.2M vocab, cased, 300d vectors, 2.03 GB download) from https://github.com/stanfordnlp/GloVe#download-pre-trained-word-vectors. The only change we did was pruning the vocab to 1M entries.

You can then load them in spaCy using:

spacy.load('en', vectors='en_glove_cc_300_1m_vectors')

henningpeters avatar Mar 12 '16 09:03 henningpeters

I'm not sure that I follow the steps to load glove vector.

import spacy
from spacy.en import English

spacy.load('en', vectors='en_glove_cc_300_1m_vectors')
nlp = English()

This doesn't seem to replace the vectors.

Sorry for the basic question

xumx avatar Mar 29 '16 20:03 xumx

@xumx you are creating two English instances (one with glove vectors, one without) and only use the latter one. What you might have missed is that spacy.load('en') is an alternative to English(), hence please use just:

nlp = spacy.load('en', vectors='en_glove_cc_300_1m_vectors')

henningpeters avatar Mar 30 '16 09:03 henningpeters

@honnibal To avoid the issues in https://github.com/spacy-io/spaCy/issues/485, I was able to download / install via sputnik the language and glove vectors using the following:

sputnik --name spacy --repository-url http://index.spacy.io install en sputnik --name spacy --repository-url http://index.spacy.io install en_glove_cc_300_1m_vectors

Then, I should be able to do this

nlp = spacy.load('en', vectors='en_glove_cc_300_1m_vectors')

But I get this exception:

>>> nlp = spacy.load('en', vectors='en_glove_cc_300_1m_vectors')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/spacy/__init__.py", line 16, in load
    vectors_package = get_package_by_name(vectors, via=via)
  File "/usr/local/lib/python2.7/dist-packages/spacy/util.py", line 41, in get_package_by_name
    lang = get_lang_class(name)
  File "/usr/local/lib/python2.7/dist-packages/spacy/util.py", line 28, in get_lang_class
    raise RuntimeError('Language not supported: %s' % lang)
RuntimeError: Language not supported: en_glove_cc_300_1m_vectors

Since the sputnik install worked I didn't think I would need to manipulate the vec.bin file directly. Any ideas what might be going wrong for me?

gitwhistle avatar Aug 29 '16 17:08 gitwhistle

Hmm. Maybe I packaged this wrong? Not sure. Will look into this.

honnibal avatar Aug 29 '16 17:08 honnibal

@honnibal any luck? seems to be an issue here.

viksit avatar Aug 30 '16 20:08 viksit

The LANGUAGES dict in that module appears to be empty, or not set properly in set_lang_class

On 30 August 2016 at 16:44, Viksit Gaur [email protected] wrote:

@honnibal https://github.com/honnibal any luck? seems to be an issue here.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/spacy-io/spaCy/issues/95#issuecomment-243574436, or mute the thread https://github.com/notifications/unsubscribe-auth/AAHOs7lOccokn-aNrllDEGNJgUEJJRSVks5qlJYUgaJpZM4F6zpf .

fmailhot avatar Aug 30 '16 21:08 fmailhot

Seems to me that the server stuff has been a red herring here, and this was broken by a code change in 1.1.0.

Until the next release, we can hack around it by simply adding something --- anything --- to the LANGUAGES dict with that key. Like so:

import spacy

spacy.set_lang_class('en_glove_cc_300_1m_vectors', 'vectors')

honnibal avatar Sep 14 '16 01:09 honnibal

@honnibal What alternative word vectors are available? I have used the following default vectors

nlp = spacy.load('en', vectors='en_glove_cc_300_1m_vectors')

but I would like to test out a 50d or 100d word vector. I know that I could download a word vector from GloVe but I was wondering where I could see other word vectors that come with spacy

jcomfort4 avatar Mar 16 '17 15:03 jcomfort4

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar May 09 '18 02:05 lock[bot]