Skip to content

Instantly share code, notes, and snippets.

@msaroufim
Last active February 25, 2020 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msaroufim/03908eb8b9e04dc107d5f1e6eb61b561 to your computer and use it in GitHub Desktop.
Save msaroufim/03908eb8b9e04dc107d5f1e6eb61b561 to your computer and use it in GitHub Desktop.
class KMeans:
def __init__(self, k):
self.k = k
self.means = None
def classify(self, input):
return min(range(self.k), key = lambda i: squared_distance(input, self.means[i]))
def train(self, inputs):
self.means = random.sample(inputs, self.k)
assignments = None
while True:
new_assignments = map(self.classify, inputs)
if assignments == new_assignments:
return
assignments = new_assignments
for i in range(self.k):
i_points = [p for p, a in zip(inputs, assignments) if a == i]
if i_points:
self.means[i] = vector_mean(i_points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment