2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MacでWord2Vecを使うまでの流れ(覚え書き)

Last updated at Posted at 2024-12-07

Macで仮想環境を使ってWord2Vecを使うのに少しつまづいたので覚え書き
誰かのお役に立てますように

前提条件

・Homebrewがインストールされていること
・pipenvとmecabがインストールされていること

データセットのダウンロード

まずは,Wikipediaよりデータセットをダウンロードする

最新版である「jawiki-latest-pages-articles.xml.bz」をダウンロードして展開する

Pythonの仮想環境構築

wikiextractorがPython3.10より後だと正規表現のルールが厳格になったためバージョンを指定して環境を構築する

pipenv install --python 3.10 wikiextractor gensim ptpython

記事ごとに文章を抽出する

pipenv run python -m wikiextractor.WikiExtractor jawiki-latest-pages-articles.xml

しばらく時間がかかる



完了したら出力結果を結合する

cat text/*/* > jawiki-latest-pages-articles.txt

mecabを使って分ち書きを行う

 mecab -Owakati jawiki-latest-pages-articles.txt -o jawiki-latest-pages-articles.text8 -b 200000

これもしばらく時間がかかる



gensimを使って単語を学習させる

train.py
import logging
from gensim.models import word2vec


def main():
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    sentences = word2vec.Text8Corpus("jawiki-latest-pages-articles.text8")
    model = word2vec.Word2Vec(sentences, vector_size=200, min_count=20, window=15)
    model.save("jawiki-latest-pages-articles.model")


if __name__ == "__main__":
    main()
pipenv run python train.py

これもまた時間がかかる

Word2Vecを使う

まず仮想環境のシェルに入る

pipenv shell

Ptpythonを使ってWord2Vecを使う

ptpython
>>> from gensim.models import word2vec
>>> model = word2vec.Word2Vec.load("jawiki-latest-pages-articles.model")
>>> model.wv.most_similar(positive=["","アメリカ"], negative=["日本"], topn=1)
[('ドル', 0.7449465990066528)]

参考文献

ラムダ技術部. “【数値化】言葉の足し算をするAIで遊んでみた.” YouTube, 2020年11月7日,

2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?