K-means算法的基本思想及代码实现思路
时间: 2024-04-24 14:03:18 浏览: 20
K-means算法是一种常用的聚类算法,其基本思想是将n个数据点划分为k个簇,使得每个数据点都属于离其最近的簇,并且每个簇的中心点尽可能接近该簇内的数据点。该算法的代码实现思路如下:
1. 随机选择k个点作为初始的簇中心点。
2. 根据每个数据点与各簇中心点的距离,将每个数据点分配到距离最近的簇中心点所在的簇中。
3. 重新计算每个簇的中心点。
4. 重复第2步和第3步,直到簇中心点不再发生变化或达到最大迭代次数。
以下是K-means算法的Python代码实现:
```python
import numpy as np
from sklearn.datasets import make_blobs
def kmeans(X, k, max_iter=100):
# 随机初始化k个簇中心点
centers = X[np.random.choice(len(X), k, replace=False)]
for i in range(max_iter):
# 计算每个数据点与各簇中心点的距离
distances = np.sqrt(np.sum((X - centers[:, np.newaxis])**2, axis=2))
# 将每个数据点分配到最近的簇中
labels = np.argmin(distances, axis=0)
# 重新计算每个簇的中心点
new_centers = np.array([X[labels == j].mean(axis=0) for j in range(k)])
# 如果簇中心点不再发生变化,提前结束迭代
if np.allclose(new_centers, centers):
break
centers = new_centers
return labels, centers
# 生成随机数据点
X, y = make_blobs(n_samples=100, centers=3, n_features=2, random_state=42)
# 聚类
labels, centers = kmeans(X, 3)
# 可视化聚类结果
import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.scatter(centers[:, 0], centers[:, 1], marker='*', s=200, c='black')
plt.show()
```
在上述代码中,我们使用`make_blobs`函数生成了100个二维的随机数据点,然后使用自己实现的`kmeans`函数对数据点进行聚类,并将聚类结果可视化出来。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)