如何使用 python 绘制词嵌入的 k 均值聚类的输出?

How to plot the output of k-means clustering of word embedding using python?

我使用 gensims 词嵌入来查找每个词的向量。然后我使用 K-means 来查找词簇。接近 10,000 tokens/words 我想绘制它们。

我想按以下方式绘制结果:

这是我所做的。

tsne = TSNE(perplexity=40, n_components=2, init='pca', n_iter=500)#, random_state=13)


def tsne_plot(data):
    "Creates and TSNE model and plots it"

    data=data.sample(n = 500).reset_index()
    word=data["word"]
    cluster=data["clusters"]
    data=data.drop(["clusters","word"],axis=1)

    X = tsne.fit_transform(data)

    plt.figure(figsize=(48, 48)) 
    for i in range(len(X)):
        plt.scatter(X[:,0][i],X[:,1][i],c=cluster[i])
        plt.annotate(word[i],
                     xy=(X[:,0][i],X[:,1][i]),
                     xytext=(3, 2),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')
    plt.show()

tsne_plot(data)

虽然它在注释 words 但未能用不同的颜色 groups/clusters?

还有其他方法可以用单词 anmes 和颜色不同的簇进行注释吗?

这是通常的做法;带有注释和彩虹色。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
from sklearn.cluster import KMeans
import seaborn as sns
import matplotlib.pyplot as plt


X = np.array([[5,3],
     [10,15],
     [15,12],
     [24,10],
     [30,45],
     [85,70],
     [71,80],
     [60,78],
     [55,52],
     [80,91],])

kmeans = KMeans(n_clusters=2)
kmeans.fit(X)

print(kmeans.cluster_centers_)

print(kmeans.labels_)

#plt.scatter(X[:,0],X[:,1], c=kmeans.labels_, cmap='rainbow')

data = X
labels = kmeans.labels_


#######################################################################


plt.subplots_adjust(bottom = 0.1)
plt.scatter(data[:, 0], data[:, 1], c=kmeans.labels_, cmap='rainbow') 

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='red', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()


#######################################################################

有关所有详细信息,请参阅下面的 link。

https://stackabuse.com/k-means-clustering-with-scikit-learn/

请参阅下面的 link 示例,了解如何使用字符而不是棕褐色数字进行注释。

https://nikkimarinsek.com/blog/7-ways-to-label-a-cluster-plot-python