import numpy as np
# Custom Manhattan distance function
def custom_distance(p1, p2):
return np.sum(np.abs(p1 - p2))
# Assign clusters based on custom distance function
def assign_clusters(X, centroids):
clusters = []
for x in X:
distances = [custom_distance(x, c) for c in centroids]
clusters.append(np.argmin(distances))
return clusters
# Compute new centroids as mean of assigned points
def compute_centroids(X, labels, k):
centroids = []
for i in range(k):
points = X[np.array(labels) == i]
centroids.append(points.mean(axis=0))
return np.array(centroids)
# Main function to perform custom K-Means clustering
def k_means_custom(X, k, max_iter=100):
centroids = X[np.random.choice(len(X), k, replace=False)]
for _ in range(max_iter):
labels = assign_clusters(X, centroids)
new_centroids = compute_centroids(X, labels, k)
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return labels, centroids
# Example usage
X = np.array([[1, 2], [1, 4], [3, 4], [5, 6], [8, 9]])
labels, centroids = k_means_custom(X, k=2)
print("Labels:", labels)
print("Centroids:", centroids)