kmeans python 算法代码
时间: 2023-07-23 19:06:09 浏览: 92
kmeans,python算法
3星 · 编辑精心推荐
import numpy as np
def kmeans(X, K, max_iters=100):
# Initialize centroids randomly
centroids = X[np.random.choice(range(len(X)), K, replace=False)]
for _ in range(max_iters):
# Assign each data point to the nearest centroid
distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=-1)
labels = np.argmin(distances, axis=-1)
# Update centroids
new_centroids = np.array([X[labels == k].mean(axis=0) for k in range(K)])
# Check for convergence
if np.allclose(centroids, new_centroids):
break
centroids = new_centroids
return centroids, labels
# Example usage
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
K = 2
centroids, labels = kmeans(X, K)
print("Centroids:")
print(centroids)
print("Labels:")
print(labels)
阅读全文