层次聚类 Python 实现——从原理到代码实现

112 篇文章 ¥59.90 ¥99.00
本文介绍了层次聚类算法的原理,重点讲述了凝聚型层次聚类,并提供了使用Python实现的详细步骤,包括载入数据、计算距离矩阵、构建聚类树和簇划分,通过Iris数据集展示了层次聚类的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

层次聚类 Python 实现——从原理到代码实现

层次聚类(hierarchical clustering)是一种将数据点逐步分组的聚类算法。与其他聚类算法不同的是,它不需要预先设置聚类数目,而是通过聚类树来展示数据点间的相似程度,并自下而上构建出聚类结果。本篇文章将从原理入手,介绍了层次聚类算法,并使用 Python 实现。

层次聚类算法简介

层次聚类算法主要分为两种:凝聚型(Agglomerative Clustering)和分裂型(Divisive Clustering)。本篇文章主要介绍凝聚型层次聚类算法。

凝聚型层次聚类算法的基本思想是将所有的数据点都看作一个簇,然后逐渐合并簇,直到所有数据点都被合并成为一个簇。具体而言,在该算法中,我们首先将每个数据点视为一个独立的簇,之后在每次聚合中选择距离最近的两个簇,合并成一个新的簇,并更新距离矩阵。直至最终得到包含所有数据点的簇集合。

层次聚类算法实现

接下来,我们将使用 Python 实现凝聚型层次聚类算法,并以 Iris 数据集为例进行演示。

载入数据

首先,我们载入所需的库,并读入 Iris 数据集。

import pandas as pd
from sklearn
### Python 实现层次聚类算法 以下是基于 `scipy` 和 `sklearn` 库的两种方式来实现层次聚类代码示例。 #### 方法一:使用 SciPy 的 `hierarchy` 模块 SciPy 提供了一个强大的模块用于执行层次聚类分析。以下是一个完整的例子: ```python import numpy as np from scipy.cluster.hierarchy import dendrogram, linkage, fcluster import matplotlib.pyplot as plt # 创建一些随机数据作为输入 np.random.seed(42) data = np.random.rand(10, 2) # 使用 linkage 函数计算层次聚类的距离矩阵 Z = linkage(data, 'ward') # 可选方法有 'single', 'complete', 'average', 'weighted' 等 # 绘制树状图 (dendrogram) plt.figure(figsize=(8, 5)) dendrogram(Z) plt.title('Hierarchical Clustering Dendrogram') plt.xlabel('Sample Index') plt.ylabel('Distance') plt.show() # 获取指定数量的聚类标签 num_clusters = 3 clusters = fcluster(Z, num_clusters, criterion='maxclust') print(f"Cluster labels: {clusters}") ``` 此代码展示了如何通过 SciPy 计算并可视化层次聚类的结果[^1]。 --- #### 方法二:使用 Scikit-Learn 的 AgglomerativeClustering 类 Scikit-learn 是另一个常用的机器学习库,提供了更简洁的方式来应用层次聚类。 ```python from sklearn.cluster import AgglomerativeClustering import numpy as np import matplotlib.pyplot as plt # 数据准备 np.random.seed(42) X = np.random.rand(10, 2) # 初始化模型 model = AgglomerativeClustering(n_clusters=3, affinity='euclidean', linkage='ward') # 执行聚类 labels = model.fit_predict(X) # 结果展示 unique_labels = np.unique(labels) colors = ['red', 'blue', 'green'] for label in unique_labels: cluster_points = X[labels == label] plt.scatter(cluster_points[:, 0], cluster_points[:, 1], color=colors[label]) plt.title('Agglomerative Clustering Result') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.show() ``` 这段代码利用 scikit-learn 中的 `AgglomerativeClustering` 来完成层次聚类,并绘制散点图显示不同类别[^3]。 --- #### 自定义实现层次聚类的核心逻辑 如果想深入了解底层原理而不依赖第三方库,则可以手动编写如下核心部分: ```python class Node: def __init__(self, vec): self.vec = vec self.left = None self.right = None self.distance = 0 self.count = 1 def hierarchical_clustering(points, distance_threshold=None): nodes = [Node(point) for point in points] while len(nodes) > 1: min_distance = float('inf') closest_pair = (-1, -1) # 寻找最近的一对节点 for i in range(len(nodes)): for j in range(i + 1, len(nodes)): dist = ((nodes[i].vec - nodes[j].vec)**2).sum() ** 0.5 if dist < min_distance: min_distance = dist closest_pair = (i, j) ni, nj = closest_pair new_node = Node((nodes[ni].vec * nodes[ni].count + nodes[nj].vec * nodes[nj].count) / (nodes[ni].count + nodes[nj].count)) new_node.left = nodes[ni] new_node.right = nodes[nj] new_node.distance = min_distance new_node.count = nodes[ni].count + nodes[nj].count del nodes[max(ni, nj)] del nodes[min(ni, nj)] nodes.append(new_node) if distance_threshold and min_distance >= distance_threshold: break return nodes[0] points = np.array([[0.4005, 0.5306], [0.2148, 0.3854], [0.2652, 0.1875], [0.0789, 0.4139]]) root = hierarchical_clustering(points) print(root.vec) ``` 该函数实现了基本的自底向上聚合过程,其中每一步都会寻找最接近的两个簇并将它们合并[^4]。 --- ### 总结 以上三种方法分别适用于不同的场景需求——从简单调用现有工具包到深入理解内部机制的手动构建。对于实际项目开发而言,推荐优先考虑成熟的开源解决方案如 SciPy 或 Scikit-learn,因为它们经过广泛测试且性能优越。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值