2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

How to load word vector ( pretrained fasttext ) : fasttextで事前学習したvectorを読み込む方法

Last updated at Posted at 2019-10-12

概要

  • 埋め込み層への適用
  • [追記]「ValueError: invalid literal for int() with base 10: ','」のようなエラーが出た場合の対処法

環境

  • Ubuntu 18.04.3 LTS
  • python 3.7.3
  • pytorch 1.3.0
  • gensim ( pip install gensimでok )

方法

FastTextのサイト(link)からwiki-news-300d-1M.vec.zipをダウンロードして解凍。(他にvector fileがあるならそれでもよし。)
*以下のような内容([word] [分散表現, .....])

engage -0.0935 0.0512 0.1021 ........
Mayor -0.0162 0.1117 -0.2773 ........

python上でgensimを使って読み込み(かなり遅い)、次回以降高速に処理するためにbinファイルとしてsave

>>> import gensim
>>> m = gensim.models.KeyedVectors.load_word2vec_format('wiki-news-300d-1M.vec')
>>> m.save_word2vec_format('wiki-news-300d-1M.bin', binary=True)  

確認

>>> m = gensim.models.KeyedVectors.load_word2vec_format('wiki-news-300d-1M.bin', binary=True)  
>>> m['oh']  
array([-6.550e-02,  8.530e-02, -1.158e-01, -6.580e-02, -5.300e-03, .... ])  

埋め込み層への適用

上記の配列をFloatTensorに変換し、weightとしてEmbedding層にloadさせる.(変換方法は省略)
具体例はここを参照。下記のような内容が書かれている。

>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
>> embedding = nn.Embedding.from_pretrained(weight)
>> input = torch.LongTensor([1])
>> embedding(input)

[追記]ValueError: invalid literal for int() with base 10: ','」のようなエラーが出た場合の対処法

vectorファイルは、最初の行に単語の数と次元を明記する必要があります。

999994 300

以下のように対処してください

python -m gensim.scripts.glove2word2vec --input wiki-news-300d-1M.vec --output wiki-news-300d-1M.vec
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?