Python - 计算 word2vec 向量的层次聚类并将结果绘制为树状图

标签 python numpy machine-learning hierarchical-clustering word2vec

我使用我的领域文本语料库生成了一个 100D word2vec 模型,合并了常用短语,例如 (good bye => good_bye)。然后我提取了 1000 个所需单词的向量。

所以我有一个像这样的 1000 numpy.array:

[[-0.050378,0.855622,1.107467,0.456601,...[100 dimensions],
 [-0.040378,0.755622,1.107467,0.456601,...[100 dimensions],
 ...
 ...[1000 Vectors]
]

单词数组如下:

["hello","hi","bye","good_bye"...1000]

我对我的数据运行了 K-Means,我得到的结果很有意义:

X = np.array(words_vectors)
kmeans = KMeans(n_clusters=20, random_state=0).fit(X)
for idx,l in enumerate(kmeans.labels_):
    print(l,words[idx])

--- Output ---
0 hello
0 hi
1 bye
1 good_bye

0 = 问候 1 = 告别

但是,有些话让我觉得hierarchical clustering 更适合这个任务。我试过使用 AgglomerativeClustering,不幸的是......对于这个 Python nobee,事情变得复杂,我迷路了。

我如何聚类我的向量,以便输出或多或少是一个树状图,就像在 this wiki 页面上找到的那样? enter image description here

最佳答案

我到现在都遇到了同样的问题! 在线搜索后总是找到您的帖子(关键字= word2vec 上的层次聚类)。 我必须给你一个可能有效的解决方案。

sentences = ['hi', 'hello', 'hi hello', 'goodbye', 'bye', 'goodbye bye']
sentences_split = [s.lower().split(' ') for s in sentences]

import gensim
model = gensim.models.Word2Vec(sentences_split, min_count=2)

from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

l = linkage(model.wv.syn0, method='complete', metric='seuclidean')

# calculate full dendrogram
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.ylabel('word')
plt.xlabel('distance')

dendrogram(
    l,
    leaf_rotation=90.,  # rotates the x axis labels
    leaf_font_size=16.,  # font size for the x axis labels
    orientation='left',
    leaf_label_func=lambda v: str(model.wv.index2word[v])
)
plt.show()

关于Python - 计算 word2vec 向量的层次聚类并将结果绘制为树状图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41462711/

相关文章:

python - 将列表映射到 1 和 0

python - keras微调报错 "' Node' object has no attribute 'output_masks"怎么解决?

Tensorflow:如何从训练的模型中预测单个图像?

python - 像 git <tab> 一样自动完成 test.py

python3使用restype定义kernel32.GetModuleHandleA的返回值,但是python输出的值很大

python - 阻止 Pandas Dataframe 'float' 对象没有属性 'split'

python - 查找 xy 数据点图与 numpy 的所有交集?

python - python 中用于存储命名数据的 3 维立方体的最佳数据结构

python - 使用一组子列分配新列

python-3.x - 交叉验证时如何获取AUC-ROC而不是准确率?