kmeans聚类算法树状图python实现
时间: 2023-11-04 15:05:23 浏览: 189
Kmeans均值聚类算法原理以及Python如何实现
要使用K-means算法实现聚类树状图,可以按照以下步骤进行:
1. 导入所需的库:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy import dendrogram, linkage
```
2. 准备数据集:
```python
X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
```
3. 使用K-means算法进行聚类:
```python
kmeans = KMeans(n_clusters=2)
means.fit(X)
```
4. 获取聚类标签:
```python
labels = kmeans.labels_
```
5. 使用层次聚类算法生成树状图:
```python
Z = linkage(X, method='single')
dn = dendrogram(Z)
plt.show()
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from scipy.cluster.hierarchy import dendrogram, linkage
X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
labels = kmeans.labels_
Z = linkage(X, method='single')
dn = dendrogram(Z)
plt.show()
```
阅读全文