kmean python实现代码
时间: 2023-11-07 22:05:08 浏览: 92
以下是k-means算法的Python实现代码:
```python
import numpy as np
import matplotlib.pyplot as plt
def kmeans(data, k):
# 随机选择 k 个数据点作为初始聚类中心
centers = data[np.random.choice(len(data), k, replace=False)]
while True:
# 计算每个数据点到 k 个聚类中心的欧几里得距离
distances = np.sqrt(((data - centers[:, np.newaxis])**2).sum(axis=2))
# 根据距离将每个数据点分配到最近的聚类中心
labels = distances.argmin(axis=0)
# 更新聚类中心为每个聚类的均值
new_centers = np.array([data[labels == i].mean(axis=0) for i in range(k)])
# 如果新的聚类中心与旧的聚类中心相同,则算法收敛
if np.all(centers == new_centers):
break
centers = new_centers
return labels, centers
# 测试代码
data = np.random.randn(100, 2)
labels, centers = kmeans(data, 3)
plt.scatter(data[:, 0], data[:, 1], c=labels)
plt.scatter(centers[:, 0], centers[:, 1], marker='+', s=500, linewidth=2)
plt.show()
```
其中,`data` 是待聚类的数据集,`k` 是聚类的个数。函数 `kmeans` 返回每个数据点的聚类标签和每个聚类的聚类中心。在测试代码中,我们生成了一个二维高斯分布的数据集,并将其聚类成 3 个类。最后,我们使用散点图可视化了聚类结果。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)