Last active
February 25, 2020 22:09
-
-
Save msaroufim/03908eb8b9e04dc107d5f1e6eb61b561 to your computer and use it in GitHub Desktop.
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
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