kmeans代码实现聚类
时间: 2023-08-25 15:07:50 浏览: 36
以下为Python实现的K-Means聚类算法代码:
```python
import numpy as np
def kmeans(X, k, max_iterations=100):
# 随机选取k个中心点
centroids = X[np.random.choice(range(len(X)), k, replace=False)]
for i in range(max_iterations):
# 计算每个样本到中心点的距离
distances = np.sqrt(((X - centroids[:, np.newaxis])**2).sum(axis=2))
# 分配每个样本到最近的中心点
labels = np.argmin(distances, axis=0)
# 更新中心点
new_centroids = np.array([X[labels == j].mean(axis=0) for j in range(k)])
# 如果中心点不再变化,则停止迭代
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return labels, centroids
```
其中,X为输入数据,k为聚类数,max_iterations为最大迭代次数。函数返回每个样本所属的类别和最终的中心点。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)