import numpy as np
class KMeans:
def __init__(self, cluster):
self.cluster = cluster
self.centroids = None
def fit(self, trainx):
# Randomly initialize centroids using K random data points
np.random.shuffle(trainx)
self.centroids = trainx[:self.cluster]
while True:
# Assign each data point to its nearest centroid
clusters = [[] for _ in range(self.cluster)]
for x in trainx:
distances = np.linalg.norm(x - self.centroids, axis=1)
nearest_centroid = np.argmin(distances)
clusters[nearest_centroid].append(x)
# Update centroids based on the average of assigned data points
new_centroids = []
for cluster in clusters:
new_centroids.append(np.mean(cluster, axis=0))
new_centroids = np.array(new_centroids)
# Check convergence
if np.allclose(self.centroids, new_centroids):
break
self.centroids = new_centroids
def predict(self, testx):
clusters = [[] for _ in range(self.cluster)]
for x in testx:
distances = np.linalg.norm(x - self.centroids, axis=1)
nearest_centroid = np.argmin(distances)
clusters[nearest_centroid].append(x)
return clusters
# Example usage
# Simplified datasets for demonstration purpose
trainx = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
testx = np.array([[2, 3], [6, 9], [0, 0], [10, 12]])
kmeans = KMeans(cluster=2)
kmeans.fit(trainx)
clusters = kmeans.predict(testx)
for i, cluster in enumerate(clusters):
print("Cluster", i)
print(cluster)
print("------")