python - 获取 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()
解决方案
您可以编写自己的函数来获取 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
推荐阅读
- javascript - 单选按钮选择并获取值时隐藏/可见复选框
- java - 无法更改低于某个最小值的按钮宽度
- python - 修改 url 参数以从多个网站下载图像
- javascript - Bootstrap,如果在页面加载时选中复选框,则单击复选框时不会取消选中
- jquery - 如何让 React.js 和 Bootstrap 4 模态轮播始终在打开时显示第一张图像
- html - 为什么我的文章在 foreach 循环中不起作用?
- c# - 如何使用 MS Graph Communications API 将调用重定向到队列
- php - PHP 应用程序只需 16 分钟即可连接 Oracle 数据库
- sql - Oracle SQL - 如何动态替换选择返回的值?
- java - 使用 java 进行 SOAP 服务调用时出错