注: このコードは Python 3.6.1 (Gensim 2.3.0) で書かれています
Gensim を使用した Python の実装と word2vec のアプリケーション
原著論文: Mikolov, T.、Chen, K.、Corrado, G.、および Dean, J. (2013)。ベクトル空間での単語表現の効率的な推定。 arXiv プレプリント arXiv:1301.3781.
import re import numpy as np from gensim.models import Word2Vec from nltk.corpus import gutenberg from multiprocessing import Pool from scipy import spatial
sentences = list(gutenberg.sents('shakespeare-hamlet.txt')) # import the corpus and convert into a list print('Type of corpus: ', type(sentences)) print('Length of corpus: ', len(sentences))
コーパスの種類: クラス 'リスト'
コーパスの長さ: 3106
print(sentences[0]) # title, author, and year print(sentences[1]) print(sentences[10])
['[', 'ザ'、'悲劇'、'オブ'、'ハムレット'、'バイ'、'ウィリアム'、'シェイクスピア'、'1599'、']']
['アクタス'、'プリムス'、'.']
['フラン', '.']
データの前処理
for i in range(len(sentences)): sentences[i] = [word.lower() for word in sentences[i] if re.match('^[a-zA-Z] ', word)] print(sentences[0]) # title, author, and year print(sentences[1]) print(sentences[10])
['ザ'、'悲劇'、'オブ'、'ハムレット'、'バイ'、'ウィリアム'、'シェイクスピア']
['アクタス'、'プリムス']
['フラン']
model = Word2Vec(sentences = sentences, size = 100, sg = 1, window = 3, min_count = 1, iter = 10, workers = Pool()._processes) model.init_sims(replace = True)
model.save('word2vec_model') model = Word2Vec.load('word2vec_model')
model.most_similar('hamlet')
[('ホレイショ', 0.9978846311569214),
('クイーン', 0.9971947073936462),
('レアテス', 0.9971820116043091),
('キング', 0.9968599081039429),
('母', 0.9966716170310974),
('どこ', 0.9966292381286621),
('ディア', 0.9965540170669556),
('オフィーリア', 0.9964221715927124),
(「とても」、0.9963752627372742)、
(「ああ」、0.9963476657867432)]
v1 = model['king'] v2 = model['queen'] # define a function that computes cosine similarity between two words def cosine_similarity(v1, v2): return 1 - spatial.distance.cosine(v1, v2) cosine_similarity(v1, v2)
0.99437165260314941
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3