层次聚类python代码
时间: 2023-07-22 14:30:48 浏览: 66
下面是一个使用scikit-learn库进行层次聚类的Python代码示例:
```python
from sklearn.cluster import AgglomerativeClustering
import numpy as np
# 创建样本数据
X = np.array([[5, 3],
[10, 15],
[15, 12],
[24, 10],
[30, 30],
[85, 70],
[71, 80],
[60, 78],
[70, 55],
[80, 91],])
# 进行层次聚类
clustering = AgglomerativeClustering(n_clusters=2).fit(X)
# 打印每个样本所属的簇
print(clustering.labels_)
```
上面的代码创建了一个包含10个样本的数据集,并使用`AgglomerativeClustering`类进行层次聚类。聚类的数量被设置为2个,因此最终生成2个簇。聚类结果存储在`clustering.labels_`中,打印输出即可看到每个样本所属的簇。
相关问题
层次聚类算法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方差最小化算法进行聚类。
如果你想对自己的数据进行层次聚类分析,只需要将数据集替换掉上面的随机数据即可。