Python gensim ライブラリ完全ガイド

Python の gensim は、文書シミラリティ計算やトピックモデリングなど、自然言語処理に特化したライブラリです。
1. gensim ライブラリの概要
- LDA (トピックモデル)やDoc2Vec / Word2Vecなどを使用した分析に適す
- 大規模テキストを効率的に処理
- 各種の文書ベクトル化、類似度計算を支援
インストール方法
pip install gensim
2. 主な機能と使用例
(1) 単純な文章をトークナイズ
from gensim.utils import simple_preprocess doc = "Gensim is a great Python library for topic modeling." print(simple_preprocess(doc))
(2) Dictionary の作成
from gensim.corpora import Dictionary docs = [["gensim", "is", "great"], ["topic", "modeling", "library"]] dictionary = Dictionary(docs) print(dictionary.token2id)
(3) Bag-of-Words 表現
corpus = [dictionary.doc2bow(text) for text in docs] print(corpus)
(4) TF-IDF の計算
from gensim.models import TfidfModel tfidf = TfidfModel(corpus) tfidf_corpus = tfidf[corpus] print(list(tfidf_corpus))
(5) LSI モデルの作成
from gensim.models import LsiModel lsi = LsiModel(tfidf_corpus, id2word=dictionary, num_topics=2) print(lsi.print_topics())
(6) LDA モデルの作成
from gensim.models import LdaModel lda = LdaModel(corpus, num_topics=2, id2word=dictionary) print(lda.print_topics())
(7) Word2Vec の訓練
from gensim.models import Word2Vec model = Word2Vec(docs, vector_size=50, window=2, min_count=1, workers=1) print(model.wv["gensim"])
(8) Doc2Vec の使用
from gensim.models.doc2vec import Doc2Vec, TaggedDocument tagged_data = [TaggedDocument(words=d, tags=[str(i)]) for i, d in enumerate(docs)] model = Doc2Vec(tagged_data, vector_size=20, window=2, min_count=1, workers=1) print(model.dv["0"])
(9) 類似語の検索
print(model.wv.most_similar("gensim"))
(10) モデルの保存と読み込み
model.save("word2vec.model") model = Word2Vec.load("word2vec.model")
3. gensim の主要モジュール
| 機能 | 説明 |
|---|---|
simple_preprocess |
文章を単語に分解 |
Dictionary |
単語とIDの対応関係の生成 |
TfidfModel |
TF-IDFの計算 |
LdaModel |
LDA によるトピック分析 |
Word2Vec |
言語の分散表現を形成 |
まとめ
gensim は、文書分析とトピックモデリングを手軽に行うための最適なライブラリです。文書の類似性評価やテーマ分析に役立てるので、文章理解を効率化したい方に最適です 🚀