首页 > 解决方案 > 获取 nltk k 的惯性意味着使用 cosine_similarity 进行聚类

问题描述

我已将 nltk 用于 k 均值聚类,因为我想更改距离度量。nltk k 意思是不是有类似于sklearn的惯性?似乎无法在他们的文档或在线找到...

下面的代码是人们通常如何使用 sklearn k 均值找到惯性。

inertia = []
for n_clusters in range(2, 26, 1):
  clusterer = KMeans(n_clusters=n_clusters)
  preds = clusterer.fit_predict(features)
  centers = clusterer.cluster_centers_
  inertia.append(clusterer.inertia_)

plt.plot([i for i in range(2,26,1)], inertia, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()

标签: pythonnltkk-means

解决方案


您可以编写自己的函数来获取 nltk 中 Kmeanscluster 的惯性。

根据您发布的问题, 如何使用 nltk (python) 获得 K 均值簇的各个质心。使用相同的虚拟数据,看起来像这样。制作2个集群后.. 在此处输入图像描述

参考文档https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html,惯性是样本到最近的聚类中心的距离平方和。

 feature_matrix = df[['feature1','feature2','feature3']].to_numpy()
 centroid = df['centroid'].to_numpy()

 def nltk_inertia(feature_matrix, centroid):
     sum_ = []
     for i in range(feature_matrix.shape[0]):
         sum_.append(np.sum((feature_matrix[i] - centroid[i])**2))  #here implementing inertia as given in the docs of scikit i.e sum of squared distance..

     return sum(sum_)

 nltk_inertia(feature_matrix, centroid)
 #op 27.495250000000002

 #now using kmeans clustering for feature1, feature2, and feature 3 with same number of cluster 2

scikit_kmeans = KMeans(n_clusters= 2)
scikit_kmeans.fit(vectors)  # vectors = [np.array(f) for f in df.values]  which contain feature1, feature2, feature3
scikit_kmeans.inertia_
#op
27.495250000000006

推荐阅读