@@ -0,0 +1,1242 @@
+import numpy as np%0A%0Aclass KMeans(object):%0A%09def __init__(self, inputs, clusters):%0A%09%09self.inputs = np.array(inputs)%0A%09%09if self.inputs.ndim == 1:%0A%09%09%09self.inputs = self.inputs.reshape(self.inputs.shape%5B0%5D, 1)%0A%0A%09%09self.test_cases = self.inputs.shape%5B0%5D%0A%09%09self.num_clusters = clusters%0A%09%09self.clusters = self.inputs%5Bnp.random.choice(self.test_cases, clusters, replace=False), :%5D%0A%09%09self.cluster_dist = np.array(%5Bnp.zeros((1, self.test_cases)) for i in range(self.num_clusters)%5D)%0A%0A%09def calculate_cluster_distances(self):%0A%09%09for i in range(self.num_clusters):%0A%09%09%09self.cluster_dist%5Bi%5D = np.sum(self.inputs - self.clusters%5Bi%5D, axis=1)%0A%0A%09def assign_data_points(self):%0A%09%09new_clusters = np.zeros(self.clusters.shape)%0A%09%09point_counts = np.zeros((self.num_clusters, 1))%0A%09%09for i in range(self.test_cases):%0A%09%09%09b_cluster = np.where(self.cluster_dist%5B:, :, i%5D == self.cluster_dist%5B:,:,i%5D.min())%5B0%5D%5B0%5D%0A%09%09%09new_clusters%5Bb_cluster%5D += self.inputs%5Bi%5D%0A%09%09%09point_counts%5Bb_cluster%5D += 1%0A%0A%09%09self.clusters%5Bpoint_counts%3E0%5D = new_clusters%5Bpoint_counts%3E0%5D / point_counts%5Bpoint_counts%3E0%5D%0A%0A%09def train(self):%0A%09%09while True:%0A%09%09%09old_clusters = self.clusters.copy()%0A%09%09%09self.calculate_cluster_distances()%0A%09%09%09self.assign_data_points()%0A%09%09%09if np.sum(old_clusters - self.clusters) == 0: break%0A

Add K Means clustering algorithm