gpt4 book ai didi

python-3.x - 如何使用 KMEANS 计算每条记录的簇距离?

转载 作者:行者123 更新时间:2023-11-30 08:45:28 24 4
gpt4 key购买 nike

我在具有两个集群的数据集上应用了 Kmeans 算法。我的数据集形状是(506,13)。如何获取每条记录的簇距离?

我尝试使用欧几里得距离作为聚类中心,但我想知道每个记录到两个聚类的距离。

model= KMeans(n_clusters=2)
model.fit(X)
print(model.cluster_centers_)

[3.88774444e-01 1.55826558e+01 8.42089431e+00 7.31707317e-02
5.11847425e-01 6.38800542e+00 6.06322493e+01 4.44127154e+00
4.45528455e+00 3.11926829e+02 1.78092141e+01 3.81042575e+02
1.04174526e+01]
[1.22261690e+01 3.01980663e-14 1.84518248e+01 5.83941606e-02
6.70102190e-01 6.00621168e+00 8.99678832e+01 2.05447007e+00
2.32700730e+01 6.67642336e+02 2.01963504e+01 2.91039051e+02
1.86745255e+01]

**actual results:**
from sklearn.metrics.pairwise import euclidean_distances
dists = euclidean_distances(model.cluster_centers_)
array([[ 0. , 369.34000546],
[369.34000546, 0. ]])

**Expected results:**

rows cluster_1_distance cluster_2_distance
0 0.78 0.89
1 0.53 0.66

最佳答案

使用scipy.spatial.distance中的cdist函数图书馆。

如引用文献中所述,它需要 2 个矩阵,并返回两个矩阵中每对之间的距离。您可以使用 metric 参数来指定所需的距离函数类型。

就您而言,

from scipy.spatial.distance import cdist
dists = cdist(X,model.cluster_centers_,metric='euclidean') #shape of dists : (506,2)

关于python-3.x - 如何使用 KMEANS 计算每条记录的簇距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com