k-means基金聚类算法python
时间: 2023-12-04 14:41:59 浏览: 32
以下是使用Python实现K-means聚类算法的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成数据
np.random.seed(0)
X = np.vstack([np.random.randn(10, 2) + [2, 2], np.random.randn(10, 2) + [0, -2], np.random.randn(10, 2) + [-2, 2]])
# 定义K-means函数
def kmeans(X, k, max_iter=100):
# 随机初始化聚类中心
centers = X[np.random.choice(len(X), k, replace=False)]
for _ in range(max_iter):
# 计算每个样本到聚类中心的距离
distances = np.linalg.norm(X[:, np.newaxis, :] - centers, axis=-1)
# 分配样本到最近的聚类中心
labels = np.argmin(distances, axis=-1)
# 更新聚类中心
new_centers = np.array([X[labels == i].mean(axis=0) for i in range(k)])
# 如果聚类中心不再变化,则停止迭代
if np.allclose(centers, new_centers):
break
centers = new_centers
return centers, labels
# 调用K-means函数进行聚类
centers, labels = kmeans(X, 3)
# 可视化聚类结果
plt.scatter(X[:, 0], X[:, 1], c=labels)
plt.scatter(centers[:, 0], centers[:, 1], marker='*', s=200, c='r')
plt.show()
```
该示例代码生成了一个包含30个样本的数据集,其中有3个聚类。通过调用kmeans函数进行聚类,得到了每个样本所属的聚类标签和聚类中心。最后,使用matplotlib库将聚类结果可视化。