实现三支K- Means算法
时间: 2023-12-01 16:51:27 浏览: 31
以下是三支K-Means算法的实现:
算法一:
```python
import numpy as np
def kmeans1(X, K, max_iters=100):
# 随机初始化K个聚类中心
centers = X[np.random.choice(range(len(X)), K, replace=False)]
for i in range(max_iters):
# 计算每个样本距离哪个聚类中心更近
distances = np.sqrt(((X - centers[:, np.newaxis])**2).sum(axis=2))
clusters = np.argmin(distances, axis=0)
# 计算每个聚类的平均值作为新的聚类中心
new_centers = np.array([X[clusters == k].mean(axis=0) for k in range(K)])
# 如果聚类中心不再变化,则结束迭代
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers, clusters
```
算法二:
```python
import numpy as np
def kmeans2(X, K, max_iters=100):
# 随机初始化K个聚类中心
centers = X[np.random.choice(range(len(X)), K, replace=False)]
for i in range(max_iters):
# 计算每个样本距离哪个聚类中心更近
distances = np.sqrt(((X - centers[:, np.newaxis])**2).sum(axis=2))
clusters = np.argmin(distances, axis=0)
# 计算每个聚类的中位数作为新的聚类中心
new_centers = np.array([np.median(X[clusters == k], axis=0) for k in range(K)])
# 如果聚类中心不再变化,则结束迭代
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers, clusters
```
算法三:
```python
import numpy as np
def kmeans3(X, K, max_iters=100):
# 随机初始化K个聚类中心
centers = X[np.random.choice(range(len(X)), K, replace=False)]
for i in range(max_iters):
# 计算每个样本距离哪个聚类中心更近
distances = np.sqrt(((X - centers[:, np.newaxis])**2).sum(axis=2))
clusters = np.argmin(distances, axis=0)
# 计算每个聚类的加权平均值作为新的聚类中心
weights = np.array([X[clusters == k].sum(axis=0) for k in range(K)])
counts = np.array([(clusters == k).sum() for k in range(K)])
new_centers = weights / counts[:, np.newaxis]
# 如果聚类中心不再变化,则结束迭代
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers, clusters
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)