Getting a dictionary of cluster_center : cluster_points_list?

Viewed 7

I'm try to use the sklearn.cluster KMeans module in order to experiment on this algorithm. My data is a list of tuples, and each such tuple is a float representing a 2D point (x,y). I want to create from this KMeans object a dictionary that will hold as key the cluster center and as value the list of points that belong to that cluster.

Does anyone know how can I do that?

So far I managed to do what I believe is a dict that holds cluster index as key and indices of the points within that cluster as a list. Here is my code:

import os
import random
from datetime import datetime
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from scipy.spatial import ConvexHull
from kneed import KneeLocator
import matplotlib.pyplot as plt
import numpy as np


def generate_point(mean_x, mean_y, deviation_x, deviation_y):
    return random.gauss(mean_x, deviation_x), random.gauss(mean_y, deviation_y)


def generate_data(number_of_clusters=5, points_per_cluster=10, cluster_mean_x=100, cluster_mean_y=100,
                  cluster_deviation_x=50, cluster_deviation_y=50, point_deviation_x=5, point_deviation_y=5):

    cluster_centers = [generate_point(cluster_mean_x,
                                      cluster_mean_y,
                                      cluster_deviation_x,
                                      cluster_deviation_y)
                       for i in range(number_of_clusters)]

    data = [generate_point(center_x,
                           center_y,
                           point_deviation_x,
                           point_deviation_y)
            for center_x, center_y in cluster_centers
            for i in range(points_per_cluster)]

    plt.clf()
    plt.scatter(*zip(*data))
    plt.savefig('Unclustered Data')

    return data


def cluster_data(data, num_clusters):
    kmeans = KMeans(n_clusters=num_clusters, random_state=0).fit(data)
    plt.clf()
    plt.scatter(*zip(*data), c=kmeans.labels_)
    centroids = kmeans.cluster_centers_
    for cent in centroids:
        plt.scatter(cent[0], cent[1], c='black', marker='x')
    plt.savefig('Clustered data for ' + str(num_clusters) + ' clusters')
    return kmeans, plt

data = generate_data()
km, plot = cluster_data(data, 3)
clusters = get_clusters(km)
0 Answers
Related