使用Python代码实现K-means聚类算法 
时间: 2023-03-20 21:01:44 浏览: 96
K-means聚类算法是一种常见的无监督机器学习算法,可用于将数据点分为不同的群组。以下是使用Python代码实现K-means聚类算法的步骤:
1. 导入必要的库
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
```
2. 生成随机数据
```python
X = -2 * np.random.rand(100, 2)
X1 = 1 + 2 * np.random.rand(50, 2)
X[50:100, :] = X1
```
3. 初始化K-means模型
```python
kmeans = KMeans(n_clusters=2)
```
4. 拟合数据
```python
kmeans.fit(X)
```
5. 预测类别
```python
y_pred = kmeans.predict(X)
```
6. 可视化结果
```python
plt.scatter(X[y_pred == 0, 0], X[y_pred == 0, 1], s = 50, c = 'red', label = 'Cluster 1')
plt.scatter(X[y_pred == 1, 0], X[y_pred == 1, 1], s = 50, c = 'blue', label = 'Cluster 2')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 100, c = 'black', label = 'Centroids')
plt.title('K-means Clustering')
plt.legend()
plt.show()
```
以上就是使用Python代码实现K-means聚类算法的步骤。
相关推荐











