def fit(self, X):
# Initialize centroids randomly
random_indices = np.random.choice(X.shape[0], size=self.n_clusters, replace=False)
self.centroids = X[random_indices]
while True:
# Assign each sample to the nearest centroid
labels = self._assign_labels(X)
# Update centroids
new_centroids = self._update_centroids(X, labels)
# Check if convergence criteria is met
if np.all(self.centroids == new_centroids):
break
self.centroids = new_centroids
def _assign_labels(self, X):
# Compute the distance between each data point and centroids
distances = np.linalg.norm(X[:, np.newaxis] - self.centroids, axis=2)
# Assign each data point to the nearest centroid
labels = np.argmin(distances, axis=1)
return labels
def _update_centroids(self, X, labels):
new_centroids = np.zeros((self.n_clusters, X.shape[1]))
for i in range(self.n_clusters):
cluster_samples = X[labels == i]
if cluster_samples.shape[0] > 0:
new_centroids[i] = np.mean(cluster_samples, axis=0)
return new_centroids
def fit(self, X):
# Initialize centroids randomly
random_indices = np.random.choice(X.shape[0], size=self.n_clusters, replace=False)
self.centroids = X[random_indices]
while True:
# Assign each sample to the nearest centroid
labels = self._assign_labels(X)
# Update centroids
new_centroids = self._update_centroids(X, labels)
# Check if convergence criteria is met
if np.allclose(self.centroids, new_centroids):
break
self.centroids = new_centroids
def _assign_labels(self, X):
# Compute the distance between each data point and centroids
distances = np.linalg.norm(X[:, np.newaxis] - self.centroids, axis=2)
# Assign each data point to the nearest centroid
labels = np.argmin(distances, axis=1)
return labels
def _update_centroids(self, X, labels):
new_centroids = np.zeros((self.n_clusters, X.shape[1]))
for i in range(self.n_clusters):
cluster_samples = X[labels == i]
if cluster_samples.shape[0] > 0:
new_centroids[i] = np.mean(cluster_samples, axis=0)
return new_centroids