用python实现一个聚类(angens )算法实例
时间: 2023-07-12 10:13:57 浏览: 110
聚类算法的实现
好的,以下是使用Python实现Agnes聚类算法的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
class Agnes:
def __init__(self, n_clusters=2):
self.n_clusters = n_clusters
def fit(self, X):
n_samples = X.shape[0]
self.labels_ = np.zeros(n_samples, dtype=np.int)
# 计算距离矩阵
distances = np.zeros((n_samples, n_samples))
for i in range(n_samples):
for j in range(i+1, n_samples):
distances[i,j] = np.sqrt(np.sum((X[i]-X[j])**2))
distances[j,i] = distances[i,j]
# 初始化聚类簇
clusters = []
for i in range(n_samples):
clusters.append([i])
# 合并聚类簇
while len(clusters) > self.n_clusters:
min_distance = np.inf
for i in range(len(clusters)):
for j in range(i+1, len(clusters)):
for k in range(len(clusters[i])):
for l in range(len(clusters[j])):
distance = distances[clusters[i][k], clusters[j][l]]
if distance < min_distance:
min_distance = distance
merge_clusters = (i, j)
clusters[merge_clusters[0]] += clusters[merge_clusters[1]]
del clusters[merge_clusters[1]]
# 计算聚类标签
for i, cluster in enumerate(clusters):
for j in cluster:
self.labels_[j] = i
return self.labels_
```
接下来,我们可以使用该算法对样本进行聚类,并可视化结果:
```python
from sklearn.datasets import make_blobs
# 生成样本数据
X, y = make_blobs(n_samples=100, centers=3, cluster_std=1.0, random_state=42)
# 使用Agnes算法进行聚类
agnes = Agnes(n_clusters=3)
labels = agnes.fit(X)
# 可视化聚类结果
plt.scatter(X[:,0], X[:,1], c=labels)
plt.show()
```
运行以上代码,即可得到聚类结果的可视化图像。
阅读全文