kmeans群集中节点与质心之间的距离?

时间:2019-01-17 16:21:10

标签: python-3.x scikit-learn k-means euclidean-distance

任何用于提取kmeans群集中节点与形心之间距离的选项。

我已经在文本嵌入数据集上完成了Kmeans聚类,并且我想知道每个聚类中哪些节点与质心的距离较远,因此我可以检查各个节点的功能是否有所不同

谢谢!

3 个答案:

答案 0 :(得分:3)

KMeans.transform()返回每个样本到聚类中心的距离的数组。

import numpy as np

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import seaborn as sns

# Generate some random clusters
X, y = make_blobs()
kmeans = KMeans(n_clusters=3).fit(X)

# plot the cluster centers and samples 
sns.scatterplot(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], 
                marker='+', 
                color='black', 
                s=200);
sns.scatterplot(X[:,0], X[:,1], hue=y, 
                palette=sns.color_palette("Set1", n_colors=3));

enter image description here

transform X并取每一行的总和(axis=1)来确定距离中心最远的样本。

# squared distance to cluster center
X_dist = kmeans.transform(X)**2

# do something useful...
import pandas as pd
df = pd.DataFrame(X_dist.sum(axis=1).round(2), columns=['sqdist'])
df['label'] = y

df.head()
    sqdist  label
0   211.12  0
1   257.58  0
2   347.08  1
3   209.69  0
4   244.54  0

目视检查-同一图,只是这次突出显示了每个聚类中心的最远点:

# for each cluster, find the furthest point
max_indices = []
for label in np.unique(kmeans.labels_):
    X_label_indices = np.where(y==label)[0]
    max_label_idx = X_label_indices[np.argmax(X_dist[y==label].sum(axis=1))]
    max_indices.append(max_label_idx)

# replot, but highlight the furthest point
sns.scatterplot(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], 
                marker='+', 
                color='black', 
                s=200);
sns.scatterplot(X[:,0], X[:,1], hue=y, 
                palette=sns.color_palette("Set1", n_colors=3));
# highlight the furthest point in black
sns.scatterplot(X[max_indices, 0], X[max_indices, 1], color='black');

enter image description here

答案 1 :(得分:1)

如果您使用的是Python和sklearn。

从这里: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans

您可以获得labels_cluster_centers_

现在,您确定距离函数,该距离函数采用每个节点及其簇中心的向量。用labels_过滤并计算每个标签内每个点的距离。

答案 2 :(得分:0)

Kevin在上面有一个很好的答案,但我觉得它不能回答所提出的问题(也许我读错了)。如果要查看每个单独的聚类中心,并获得该聚类中距中心最远的点,则需要使用聚类标签来获取每个点到该聚类质心的距离。上面的代码只是在每个群集中找到距所有其他群集中心最远的点(在图中可以看到,这些点始终位于群集的另一侧,远离其他2个群集)。为了查看各个群集,您将需要以下内容:

center_dists = np.array([X_dist[i][x] for i,x in enumerate(y)])

这将为您提供每个点与其簇的质心的距离。然后,通过运行几乎与Kevin相同的代码,它将为您提供每个集群中最远的地方。

max_indices = []
for label in np.unique(kmeans.labels_):
    X_label_indices = np.where(y==label)[0]
    max_label_idx = X_label_indices[np.argmax(center_dist[y==label])]
    max_indices.append(max_label_idx)
相关问题