用python 实现K-means聚类 
时间: 2023-03-19 09:22:09 浏览: 39
K-means 聚类是一种无监督学习算法,用于将一组数据点分成 K 个类别。下面是用 Python 实现 K-means 聚类的基本步骤:
1. 导入所需的库
```python
import numpy as np
from sklearn.cluster import KMeans
```
2. 准备数据集
```python
data = np.array([
[1, 2], [1, 4], [1, 0],
[4, 2], [4, 4], [4, 0]
])
```
3. 初始化 KMeans 对象
```python
kmeans = KMeans(n_clusters=2, random_state=0)
```
4. 训练模型
```python
kmeans.fit(data)
```
5. 获取聚类结果
```python
labels = kmeans.labels_
```
6. 获取聚类中心
```python
centroids = kmeans.cluster_centers_
```
7. 可视化聚类结果
```python
import matplotlib.pyplot as plt
plt.scatter(data[:,0], data[:,1], c=labels)
plt.scatter(centroids[:,0], centroids[:,1], marker='x', s=200, linewidths=3, color='r')
plt.show()
```
上述代码将数据集分为 2 个类别,并用红色叉号表示聚类中心。
相关推荐














