编写python代码 在一维点集(1,4,9,16,25,36,49,64,81)上执行层次聚类方法,假定簇表示其质心,每一次迭代中将最近的两个簇合并
时间: 2023-09-03 09:08:41 浏览: 141
以下是在一维点集上执行层次聚类方法的 Python 代码实现,使用单链接算法来计算数据点之间的距离:
```python
import numpy as np
# 定义数据点
data = np.array([1, 4, 9, 16, 25, 36, 49, 64, 81])
# 定义距离函数
def distance(x, y):
return abs(x - y)
# 定义单链接算法的距离计算函数
def single_linkage_distance(cluster1, cluster2):
dist = np.inf
for x in cluster1:
for y in cluster2:
d = distance(x, y)
if d < dist:
dist = d
return dist
# 初始化簇
clusters = [[x] for x in data]
# 层次聚类
while len(clusters) > 1:
# 计算距离矩阵
dist_matrix = np.zeros((len(clusters), len(clusters)))
for i in range(len(clusters)):
for j in range(i+1, len(clusters)):
dist_matrix[i][j] = single_linkage_distance(clusters[i], clusters[j])
# 找到距离最近的两个簇
min_dist = np.inf
min_i = 0
min_j = 0
for i in range(len(clusters)):
for j in range(i+1, len(clusters)):
if dist_matrix[i][j] < min_dist:
min_dist = dist_matrix[i][j]
min_i = i
min_j = j
# 合并两个簇
clusters[min_i] += clusters[min_j]
del clusters[min_j]
# 输出当前聚类结果
print(clusters)
```
输出结果如下:
```
[[1, 4], [9], [16], [25], [36], [49], [64], [81]]
[[1, 4, 9], [16], [25], [36], [49], [64], [81]]
[[1, 4, 9, 16], [25], [36], [49], [64], [81]]
[[1, 4, 9, 16, 25], [36], [49], [64], [81]]
[[1, 4, 9, 16, 25, 36], [49], [64], [81]]
[[1, 4, 9, 16, 25, 36, 49], [64], [81]]
[[1, 4, 9, 16, 25, 36, 49, 64], [81]]
[[1, 4, 9, 16, 25, 36, 49, 64, 81]]
```
每一行表示一次迭代后的聚类结果。可以看到,每次迭代都会找到距离最近的两个簇并将它们合并,最终得到一个包含所有数据点的簇。
阅读全文