1、 凝聚层次聚类算法实现(非聚类库函数调用),要求算法输入:随机生成聚类的>=20个对象;算法输出:分类结果,聚类过程中得到的最短距离值以及距离矩阵。考虑三种不同距离计算方法进行聚类。
时间: 2023-06-29 16:14:52 浏览: 113
以下是非聚类库函数调用的凝聚层次聚类算法的Python实现。实现了三种不同距离计算方法:欧几里得距离、曼哈顿距离和切比雪夫距离。
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(42)
data = np.random.rand(20, 2)
# 计算距离矩阵
def distance_matrix(data, metric='euclidean'):
n = data.shape[0]
distance_mat = np.zeros((n, n))
for i in range(n):
for j in range(i+1, n):
if metric == 'euclidean':
distance_mat[i, j] = np.linalg.norm(data[i, :] - data[j, :])
elif metric == 'manhattan':
distance_mat[i, j] = np.sum(np.abs(data[i, :] - data[j, :]))
elif metric == 'chebyshev':
distance_mat[i, j] = np.max(np.abs(data[i, :] - data[j, :]))
else:
raise ValueError('Invalid metric')
distance_mat += distance_mat.T
return distance_mat
# 凝聚层次聚类算法
def agglomerative_clustering(data, method='single', metric='euclidean'):
n = data.shape[0]
labels = np.arange(n)
distance_mat = distance_matrix(data, metric=metric)
min_distance = np.min(distance_mat[np.nonzero(distance_mat)])
clusters = [i for i in range(n)]
history = [(i,) for i in range(n)]
while len(clusters) > 1:
i, j = np.unravel_index(np.argmin(distance_mat), distance_mat.shape)
if method == 'single':
new_distance = np.min(distance_mat[i, labels == labels[j]])
elif method == 'complete':
new_distance = np.max(distance_mat[i, labels == labels[j]])
elif method == 'average':
new_distance = np.mean(distance_mat[i, labels == labels[j]])
else:
raise ValueError('Invalid method')
history.append((clusters[i], clusters[j]))
clusters[i] = tuple(sorted((clusters[i], clusters[j])))
clusters.pop(j)
labels[labels == labels[j]] = labels[i]
distance_mat = np.delete(distance_mat, j, axis=0)
distance_mat = np.delete(distance_mat, j, axis=1)
distance_mat[i, :] = np.minimum(distance_mat[i, :], distance_mat[j, :])
distance_mat[:, i] = distance_mat[i, :]
distance_mat[i, i] = 0
min_distance = min(min_distance, new_distance)
return clusters[0], min_distance, history
# 聚类并可视化结果
methods = ['single', 'complete', 'average']
metrics = ['euclidean', 'manhattan', 'chebyshev']
fig, axs = plt.subplots(3, 3, figsize=(12, 12))
for i, metric in enumerate(metrics):
for j, method in enumerate(methods):
clusters, min_distance, history = agglomerative_clustering(data, method=method, metric=metric)
axs[i, j].scatter(data[:, 0], data[:, 1], c=clusters)
axs[i, j].set_title(f'{method} ({metric})')
axs[i, j].set_xticks([])
axs[i, j].set_yticks([])
axs[i, j].text(0.05, 0.9, f'min_distance: {min_distance:.3f}\nclusters: {len(set(clusters))}', transform=axs[i, j].transAxes, fontsize=12, verticalalignment='top')
plt.show()
```
在上面的代码中,我们首先生成了20个随机的2维数据点,然后分别使用欧几里得距离、曼哈顿距离和切比雪夫距离计算了距离矩阵,并使用了三种不同的凝聚层次聚类方法(单链接、全链接和平均链接)进行了聚类。最后,我们将聚类结果可视化,并输出了最短距离值和聚类数目。
需要注意的是,由于凝聚层次聚类算法的时间复杂度较高,对于更大的数据集,可能需要进行优化。
阅读全文