我有以下表格的数据框架;
dict_new={'var1':[1,0,1,0,2],'var2':[1,1,0,2,0],'var3':[1,1,1,2,1]}
pd.DataFrame(dict_new,index=['word1','word2','word3','word4','word5'])请注意,实际的数据集相当大,上面的例子是为了简单。然后,我在镰刀学习中执行了K-均值算法,为了简单起见,我取了两个集群质心.
from sklearn.cluster import KMeans
num_clusters = 2
km = KMeans(n_clusters=num_clusters,verbose=1)
km.fit(dfnew.to_numpy())假设新的星系团质心由
centers=km.cluster_centers_
centers
array([[0. , 1.5 , 1.5 ],
[1.33333333, 0.33333333, 1. ]])目标是为每个聚类质心找到两个最接近的词,即为每个聚类中心识别两个最近的词。我使用了来自distance_matrix软件包的scipy,得到了输出作为2 x 5矩阵,对应于两个中心和5个字。请参阅下面的代码。
from scipy.spatial import distance_matrix
distance_matrix(centers,np.asmatrix(dfnew.to_numpy()))
array([[1.22474487, 0.70710678, 1.87082869, 0.70710678, 2.54950976],
[0.74535599, 1.49071198, 0.47140452, 2.3570226 , 0.74535599]])但这里没有索引这个词。因此,我无法识别每个质心最接近的两个词。关于如何检索索引(原始数据框架中定义的索引),我能得到帮助吗?我们很感激你的帮助。
发布于 2020-06-25 21:51:37
考虑到我理解您想要正确地做什么,下面是一个关于如何找到单词的索引的最小工作示例。
首先,让我们生成一个类似的可复制环境
# import packages
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from scipy.spatial.distance import cdist
from scipy.spatial import distance_matrix
# set up the DataFrame
dict_new={'var1':[1,0,1,0,2],'var2':[1,1,0,2,0],'var3':[1,1,1,2,1]}
df = pd.DataFrame(dict_new,index= ['word1','word2','word3','word4','word5'])
# get the cluster centers
kmeans = KMeans(n_clusters=2, random_state=0).fit(np.array(df))
centers = kmeans.cluster_centers_如果您只需要知道最接近的单词
现在,如果您想使用距离矩阵,您可以这样做(而不是):
def closest(df, centers):
# define the distance matrix
mat = distance_matrix(centers, np.asmatrix(df.to_numpy()))
# get an ordered list of the closest word for each cluster centroid
closest_words = [df.index[i] for i in np.argmin(mat, axis=1)]
return closest_words
# example of it working for all centroids
print(closest(df, centers))
# > ['word3', 'word2']如果你需要知道两个最接近的词
现在,如果我们想要两个最接近的词:
def two_closest(df, centers):
# define the distance matrix
mat = distance_matrix(centers, np.asmatrix(df.to_numpy()))
# get an ordered list of lists of the closest two words for each cluster centroid
closest_two_words = [[df.index[i] for i in l] for l in np.argsort(mat, axis=1)[:,0:2]]
return closest_two_words
# example of it working for all centroids
print(two_closest(df, centers))
# > [['word3', 'word5'], ['word2', 'word4']]如果这不是你想做的,或者我的回答不符合你的需要,请告诉我!如果我解决了你的问题,别忘了把这个问题记下来。
https://stackoverflow.com/questions/62584613
复制相似问题