如何用代码实现k-means聚类分析
时间: 2023-11-06 16:07:42 浏览: 38
K-means 聚类分析是一种基于距离度量的无监督学习算法,它的主要思想是将数据集分成 k 个簇,每个簇的数据点与该簇质心的距离最小。以下是 Python 中实现 K-means 聚类分析的示例代码:
```python
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# 生成模拟数据
X, y = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
# 使用 K-means 聚类分析
kmeans = KMeans(n_clusters=4)
kmeans.fit(X)
# 绘制聚类结果
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='*', s=200, color='black')
plt.show()
```
在上面的代码中,我们首先生成了一个模拟数据集,然后使用 K-means 聚类分析将数据集分成了 4 个簇,并绘制出了聚类结果。其中,`KMeans` 类是 scikit-learn 库中提供的 K-means 聚类分析的实现,`n_clusters` 参数指定了要分成的簇的数量。最后,我们使用 `scatter` 函数绘制了数据点和质心。