I want to do image segmention with k-means clustering, and i want to:
- Calculate distances between all points and the initial centroids.
- Assign all points to their closest centroid.
Here is my code:
def init(ds, k, random_state=42):
np.random.seed(random_state)
centroids = [ds[0]]
for _ in range(1, k):
dist_sq = np.array([min([np.inner(c-x,c-x) for c in centroids]) for x in ds])
probs = dist_sq/dist_sq.sum()
cumulative_probs = probs.cumsum()
r = np.random.rand()
for j, p in enumerate(cumulative_probs):
if r < p:
i = j
break
centroids.append(ds[i])
return np.array(centroids)
k = 4
centroids = init(pixels, k, random_state=42)
print(centroids)
# First centroid
centroids[0]
#Calculate distances between all points and the initial centroids.
# Assign all points to their closest centroid.