层次聚类python代码
时间: 2023-07-22 15:06:25 浏览: 167
以下是用Python实现层次聚类的基本代码:
```python
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
# 构造数据
X = np.array([[1,2],[1,4],[1,0],[4,2],[4,4],[4,0]])
labels = ['A', 'B', 'C', 'D', 'E', 'F']
# 层次聚类
Z = linkage(X, method='ward', metric='euclidean')
# 绘制树状图
fig = plt.figure(figsize=(8, 5))
dn = dendrogram(Z, labels=labels)
plt.show()
```
其中,`X`为样本数据,`labels`为每个样本的标签。`linkage`函数用于层次聚类,`method`参数表示聚类方法,`metric`参数表示距离度量方法。`dendrogram`函数用于绘制树状图。运行上述代码,即可得到一个树状图。
相关问题
层次聚类算法python代码
层次聚类算法的Python代码可以使用scipy库中的cluster.hierarchy模块来实现。下面是一个简单的层次聚类算法的Python代码示例:
```python
from scipy.cluster.hierarchy import dendrogram, linkage
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(4711)
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a, b),)
# 层次聚类
Z = linkage(X, 'ward')
# 绘制层次树
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('sample index')
plt.ylabel('distance')
dendrogram(Z, leaf_rotation=90., leaf_font_size=8.)
plt.show()
```
这段代码首先生成了一些随机数据,然后使用`linkage`函数进行层次聚类,最后使用`dendrogram`函数绘制层次树。你可以根据自己的需求修改数据和参数来实现不同的层次聚类算法。
层次聚类分析python代码
层次聚类分析是一种常用的聚类方法,它可以将数据集中的样本分成不同的类别。下面是一个简单的层次聚类分析的Python代码实现:
```python
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(4711)
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a, b),)
# 生成距离矩阵
Z = linkage(X, 'ward')
# 绘制树状图
plt.figure(figsize=(25, 10))
plt.title('Hierarchical Clustering Dendrogram')
plt.xlabel('sample index')
plt.ylabel('distance')
dendrogram(Z, leaf_rotation=90., leaf_font_size=8.)
plt.show()
```
这段代码首先生成了一个随机数据集,然后使用`linkage`函数生成距离矩阵,最后使用`dendrogram`函数绘制树状图。其中,`ward`表示使用Ward方差最小化算法进行聚类。
如果你想对自己的数据进行层次聚类分析,只需要将数据集替换掉上面的随机数据即可。