K-Means Clustering

Hard
machine-learning Google DeepMind

Implement K-Means clustering for 2D points. Given a list of (x, y) tuples, number of clusters k, and initial centroids, run the algorithm for a specified number of iterations and return the final centroids.

Example

points = [(1, 1), (1.5, 2), (3, 4), (5, 7), (3.5, 5), (4.5, 5)]
centroids = [(1, 1), (5, 7)]
k_means(points, 2, centroids, iterations=10)
# => [(1.25, 1.5), (4.0, 5.25)]  (approximately)

Test Cases

Python Editor

Output

Click "Run" to see results...