Last active
August 29, 2015 14:25
-
-
Save cjmcgraw/800f2a4f03e37a411d33 to your computer and use it in GitHub Desktop.
K-Means implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
class KMeans: | |
def __init__(self, minimum, maximum, dim, k): | |
self._centroids = [[randint(minimum, maximum) for d in range(dim)] for x in range(k] | |
self._points = {i: [] for i in range(k)} | |
def update(self, vector): | |
distance = lambda v: sqrt(sum([(x2-x1) ** 2 for x1, x2 in zip(v[1], vector)])) | |
centroid_index = min(enumerate(self._centroids), key=dist)[0] | |
self._points[centroid_index].append(vector) | |
self._centroids[centroid_index] = [sum(xi) / len(xi) for xi in zip(*self._points[centroid_index])] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment