写一个python的k-means算法
时间: 2024-05-10 17:19:56 浏览: 78
基于Python实现一个k-means算法和混合高斯模型【100011012】
好的,我可以回答这个问题。K-means 是一种常见的聚类算法,可以用 Python 实现。以下是一个简单的 K-means 示例:
```python
import numpy as np
def k_means(X, k, max_iters):
"""
X: ndarray, shape=(m, n),
m is the number of examples, n is the number of features
k: int, the number of clusters
max_iters: int, the maximum number of iterations
"""
m, n = X.shape
centroids = X[np.random.choice(m, k, replace=False), :]
for _ in range(max_iters):
# assignment step: assign each example to the cluster with the nearest centroid
distances = np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2))
labels = distances.argmin(axis=0)
# update step: move the centroids to the mean of the examples assigned to them
for j in range(k):
centroids[j] = X[labels == j].mean(axis=0)
return centroids, labels
```
以上代码是一个简单的 K-means 算法实现。其中,`X` 是数据集,`k` 是簇的数量,`max_iters` 是最大迭代次数。函数的输出是聚类后的簇中心和标签。
阅读全文