python AGNES算法 代码
时间: 2023-07-23 11:30:20 浏览: 144
以下是使用Python实现AGNES算法的示例代码:
```python
import numpy as np
def agnes(X, k):
n = X.shape[0]
# 初始化,将每个样本看作一个簇
clusters = [[i] for i in range(n)]
# 计算距离矩阵
dist_matrix = np.zeros((n, n))
for i in range(n):
for j in range(i+1, n):
dist_matrix[i, j] = dist_matrix[j, i] = np.linalg.norm(X[i] - X[j])
while len(clusters) > k:
# 找到距离最近的两个簇
min_dist = np.inf
for i in range(len(clusters)):
for j in range(i+1, len(clusters)):
dist = 0
for m in clusters[i]:
for n in clusters[j]:
dist += dist_matrix[m, n]
dist /= len(clusters[i]) * len(clusters[j])
if dist < min_dist:
min_dist = dist
merge_i, merge_j = i, j
# 合并簇
clusters[merge_i] += clusters[merge_j]
clusters.pop(merge_j)
# 更新距离矩阵
for i in range(len(clusters)):
if i != merge_i:
dist = 0
for m in clusters[i]:
for n in clusters[merge_i]:
dist += dist_matrix[m, n]
dist /= len(clusters[i]) * len(clusters[merge_i])
dist_matrix[i, merge_i] = dist_matrix[merge_i, i] = dist
# 构建聚类结果
labels = np.zeros(n)
for i, cluster in enumerate(clusters):
for j in cluster:
labels[j] = i
return labels
```
其中,X是输入的数据矩阵,k是聚类的簇数。该函数返回一个标签数组,表示每个样本所属的簇。
阅读全文