I want to divide the training set into n partitions further besides testing set. How can I do that?

Furthermore, I'm creating these groups in the training set. How can I calculate centroid of each partition ?

  • $\begingroup$ Are you trying to implement K-Means and then KNN based on its results? Or are you just looking for a clustering technique with n partitions? $\endgroup$
    – Miss.Alpha
    Oct 13, 2022 at 9:40
  • $\begingroup$ Clustering technique with n partitions . $\endgroup$
    – Vishnu
    Oct 20, 2022 at 5:30

1 Answer 1


If you already know n, you can use cluster module on scikit-learn. Here's a toy example:

# Load libraries
import pandas as pd
from sklearn.datasets import make_blobs 
from sklearn.cluster import KMeans

centers = 3 #here your n should go
# Make simulated feature matrix
features, _ = make_blobs(n_samples = 50,
                             n_features = 2,
                             centers = centers,
                             random_state = 22)

dataframe = pd.DataFrame(features, columns=["feature_1", "feature_2"]) 

# Make k-means clusterer
clusterer = KMeans(3, random_state=0) 

After fitting the model, ou can get the class labels by predict attribute:


And each observation centroid is accessible through cluster_centers_:


You can use scikit-learn documentation on this for more information.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.