← Lesson
Unsupervised Learning
Joeven
Run
Reset
Python loads on first run
import math points = [ (0.0, 0.1), (0.2, 0.0), (0.1, 0.2), (0.15, 0.15), # blob A (5.0, 5.1), (5.2, 4.9), (4.8, 5.0), (5.1, 5.2), # blob B ] def dist(a, b): return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) def mean(group): n = len(group) return (sum(p[0] for p in group) / n, sum(p[1] for p in group) / n) centroids = [points[0], points[-1]] # one seed from each blob for step in range(1, 6): buckets = [[] for _ in centroids] assign = [] for p in points: j = min(range(len(centroids)), key=lambda i: dist(p, centroids[i])) buckets[j].append(p) assign.append(j) centroids = [mean(b) if b else c for b, c in zip(buckets, centroids)] print("step", step, "assign", assign) print(" centroids", [(round(c[0], 2), round(c[1], 2)) for c in centroids])
Run to execute this in your browser. Nothing is sent to a server.