# How do I calculate distance of test data point from centroids in KMeans scikit-learn?

I am using Kmeans clustering on my data After training the model, I want to calculate the distance between Test Data points and CLuster centers.

How do I do it?

My code is like below:

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

model.fit(X_train)

# get centroids
centroids = model.cluster_centers_


But I'm not sure how to use those centroids to calculate the distances for new data point

you can try below approach
centroids is a matrix with all cluster centers

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 provides a predict function for the KMeans object. So something like this should work:

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 assigns data points to clusters is by calculating the Euclidean distance between the data point and the clusters and picking the closest cluster.

• Actually I'm not interested in labels here, I am aware of it. I want to know how can we calculate the distance, so I can manually examine the points at borderline – Sociopath Jan 11 at 11:07
• I mentioned this in my answer. You can use Euclidean distance between the data point and the clusters. – Valentin Calomme Jan 11 at 11:48