如何计算测试数据点与 KMeans scikit-learn 中质心的距离?

数据挖掘 Python scikit-学习 k-均值
2022-02-13 03:19:31

我在我的数据上使用 Kmeans 聚类训练模型后,我想计算测试数据点和聚类中心之间的距离。

我该怎么做?

My code is like below:


model = KMeans(clusters=2, random_state=42)

model.fit(X_train)

# get centroids
centroids = model.cluster_centers_

但我不确定如何使用这些质心来计算新数据点的距离

2个回答

您可以尝试以下方法
,centroids 是一个包含所有聚类中心的矩阵

centroids=[[20,40,60,80],[60,120,180,240],[100,200,300,400]]

TestData_vector=[130,170,250,300] #you new test data as a vector

import numpy as np
from sklearn.metrics.pairwise import euclidean_distances
euc_res=euclidean_distances(np.array(centroids), np.array([TestData_vector]))

# normalize the result  
normlaized_res= (1/euc_res)/((1/euc_res).sum())
#convert to list and sort it 
normlaized_res_list=normlaized_res.tolist()
sorted_res=sorted(normlaized_res,reverse=True)
#get the nearset cluster 
nearest_cluster=[]
for i in sorted_res[:10] :
    nearest_cluster.append(normlaized_res_list.index(i))

Sklearn 为 KMeans 对象提供了一个预测函数。所以这样的事情应该有效:

model = KMeans(clusters=2, random_state=42)

model.fit(X_train)

# get centroids
centroids = model.cluster_centers_

test_data_point = pass

model.predict([test_data_point])

KMeans 将数据点分配给集群是通过计算数据点和集群之间的欧几里德距离并选择最近的集群。