提供一个三支K-means算法代码python
时间: 2023-10-04 14:09:54 浏览: 81
以下是一个简单的三支K-means算法的Python代码:
```python
import numpy as np
def kmeans(X, K, max_iters):
centroids = X[np.random.choice(X.shape[0], K, replace=False), :]
for i in range(max_iters):
# Calculate the distance between each point and each centroid
distances = np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2))
# Assign each point to its nearest centroid
labels = np.argmin(distances, axis=0)
# Update the centroids based on the points assigned to them
for j in range(K):
centroids[j] = np.mean(X[labels == j], axis=0)
return centroids, labels
# Example usage
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]])
K = 2
max_iters = 10
centroids, labels = kmeans(X, K, max_iters)
print("Final centroids:", centroids)
print("Final labels:", labels)
```
该代码使用了Numpy库来计算距离和均值,以及随机选择初始质心。在每次迭代中,它计算每个点到每个质心的距离,并将每个点分配给最近的质心。然后,它根据分配给它们的点更新每个质心的位置。该算法迭代完成后返回最终质心和标签。
阅读全文