我使用Python中的gensim包加载预先训练好的Google word2vec数据集。然后,我想使用k-means在我的单词向量上找到有意义的聚类,并找到每个聚类的代表性单词。我正在考虑使用其对应的向量最接近群集质心的单词来表示该群集,但不知道这是否是一个好主意,因为我的实验没有给我带来好结果。
我的示例代码如下所示:
import gensim
import numpy as np
import pandas as pd
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import pairwise_distances_argmin_min
model = gensim.models.KeyedVectors.load_word2vec_format('/home/Desktop/GoogleNews-vectors-negative300.bin', binary=True)
K=3
words = ["ship", "car", "truck", "bus", "vehicle", "bike", "tractor", "boat",
"apple", "banana", "fruit", "pear", "orange", "pineapple", "watermelon",
"dog", "pig", "animal", "cat", "monkey", "snake", "tiger", "rat", "duck", "rabbit", "fox"]
NumOfWords = len(words)
# construct the n-dimentional array for input data, each row is a word vector
x = np.zeros((NumOfWords, model.vector_size))
for i in range(0, NumOfWords):
x[i,]=model[words[i]]
# train the k-means model
classifier = MiniBatchKMeans(n_clusters=K, random_state=1, max_iter=100)
classifier.fit(x)
# check whether the words are clustered correctly
print(classifier.predict(x))
# find the index and the distance of the closest points from x to each class centroid
close = pairwise_distances_argmin_min(classifier.cluster_centers_, x, metric='euclidean')
index_closest_points = close[0]
distance_closest_points = close[1]
for i in range(0, K):
print("The closest word to the centroid of class {0} is {1}, the distance is {2}".format(i, words[index_closest_points[i]], distance_closest_points[i]))
输出如下:
[2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0]
The closest word to the centroid of class 0 is rabbit, the distance is 1.578625818679259
The closest word to the centroid of class 1 is fruit, the distance is 1.8351978219013796
The closest word to the centroid of class 2 is car, the distance is 1.6586030662247868
在代码中我有3类词:车辆,水果和动物。从输出中我们可以看出k-means正确地聚集了所有3个类别的单词,但是使用质心方法得出的代表性单词并不是很好,因为对于0类我想看到" animal"但是它给了兔子#34;而对于2级我想看到" vehicle"但它返回" car"。
我们将非常感谢您为每个群集找到合适的代表性词语的任何帮助或建议。
答案 0 :(得分:3)
听起来你希望能够找到群集中单词的通用术语 - 一种 hypernym - 具有自动化过程,并且希望质心是那个词。
不幸的是,我没有看到任何声称word2vec结束这样安排的话。单词往往接近可以为其填充的其他单词 - 但实际上没有任何保证共享类型的单词比其他类型的单词更接近彼此,或者下位词往往是等距的他们的下位,等等。 (当然,鉴于word2vec在类比求解方面的成功,上位词往往会在各个类的模糊相似方向上偏离它们的下位词。也就是说,或许含糊'volkswagen' + ('animal' - 'dog') ~ 'car'
- 尽管我没检查过。)
有时候有一个有趣的观察结果可能是相关的:对于具有更多弥散意义的词的词向量 - 例如多重感觉 - 往往比其他词向量具有更低的幅度,原始形式对于具有更多单义含义的单词。通常最相似的计算忽略了幅度,只是比较原始方向,但搜索更通用的术语可能希望偏向较低幅度的矢量。但这也只是猜测我没有检查过。
你可以查看自动上位词/下位词发现的工作,并且word2vec矢量可能是这种发现过程的一个促成因素 - 要么以正常方式训练,要么用一些新的皱纹来试图强制所需的排列。 (但是,开箱即用的gensim通常不支持这种专业化。)
通常会有一些文章改进word2vec训练过程,以使矢量更好地用于特定目的。 Facebook Research最近发表的一篇似乎相关的论文是“Poincaré Embeddings for Learning Hierarchical Representations” - 它报告了更好的层次结构建模,特别是对WordNet的名词hypernym图的测试。