K-Means Clustering
medium· Machine Learningruns: 0Implement K-Means clustering. Initialize k centroids, assign each point to its nearest centroid, recompute centroids as the mean of their members, and repeat until the centroids stop moving.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 715
import numpy as np
class KMeans:
def __init__(self, k: int = 3, max_iters: int = 100):
self.k = k
self.max_iters = max_iters
def fit(self, X):
rng = np.random.default_rng(0)
idx = rng.choice(len(X), self.k, replace=False)
self.centroids = X[idx]
for _ in range(self.max_iters):
labels = self._assign(X)
new = np.array([X[labels == c].mean(axis=0) for c in range(self.k)])
if np.allclose(new, self.centroids):
break
self.centroids = new
return labels
def _assign(self, X):
dists = np.linalg.norm(X[:, None] - self.centroids, axis=2)
return np.argmin(dists, axis=1)
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.