意味関係を図で表現する


今までの投稿でWord2Vecというものを紹介した.

分散表現を獲得して,単語の意味情報を数値情報に変換できる技術だ.今回はその実装を行なってみた.コードは下記.

!pip install gensim matplotlib scikit-learn
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from gensim.models import Word2Vec
import numpy as np  # NumPy をインポート

# モデル訓練
sentences = [
    ['language', 'communication', 'meaning', 'semantics', 'syntax', 'grammar'],
    ['brain', 'neuroscience', 'language', 'processing', 'cognition'],
    ['data', 'science', 'machine', 'learning', 'language', 'processing']
]

model = Word2Vec(sentences, vector_size=100, window=3, min_count=1, workers=4)

# 単語ベクトル取得
words = list(model.wv.index_to_key)
vectors = [model.wv[word] for word in words]

# リストからNumPy配列へ変換
vectors_np = np.array(vectors)

# 語彙数を確認(例: 14 語)
n_samples = vectors_np.shape[0]
print("Number of samples:", n_samples)

# TSNE の perplexity をサンプル数より小さい値に設定(例: perplexity=5)
tsne = TSNE(n_components=2, random_state=42, perplexity=5)
reduced_vectors = tsne.fit_transform(vectors_np)

# 可視化
plt.figure(figsize=(8, 6))
plt.scatter(reduced_vectors[:, 0], reduced_vectors[:, 1])

for i, word in enumerate(words):
    plt.annotate(word, (reduced_vectors[i, 0], reduced_vectors[i, 1]))

plt.title('Semantic Relations (t-SNE Visualization)')
plt.show()

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です