使用Scikit-learn包的AffinityPropagation
【摘要】 下面是一个使用 scikit-learn 中 AffinityPropagation 进行聚类的完整示例。AffinityPropagation 的特点是:不需要预先指定簇的数量,算法会自动选择聚类中心,且聚类中心是原始样本点。import numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import Affini...
下面是一个使用 scikit-learn 中 AffinityPropagation 进行聚类的完整示例。AffinityPropagation 的特点是:不需要预先指定簇的数量,算法会自动选择聚类中心,且聚类中心是原始样本点。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AffinityPropagation
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
# 1. 生成示例数据
X, y_true = make_blobs(
n_samples=300,
centers=3,
cluster_std=0.7,
random_state=42
)
# 2. 构建 AffinityPropagation 模型
af = AffinityPropagation(
damping=0.9, # 阻尼系数,通常 0.5~1,越大越稳定但收敛越慢
preference=-50, # 偏好参数,越大簇越多,越小簇越少;None 时使用相似度中位数
affinity='euclidean', # 相似度度量,也可用 'precomputed'
max_iter=500,
convergence_iter=30,
random_state=42
)
# 3. 聚类
y_pred = af.fit_predict(X)
# 4. 查看结果
n_clusters = len(af.cluster_centers_indices_)
print(f"估计簇数量: {n_clusters}")
print(f"聚类中心索引: {af.cluster_centers_indices_}")
print(f"聚类中心坐标:\n{af.cluster_centers_}")
print(f"迭代次数: {af.n_iter_}")
if 1 < n_clusters < len(X):
print(f"轮廓系数: {silhouette_score(X, y_pred):.3f}")
# 5. 可视化
plt.figure(figsize=(8, 6))
plt.scatter(
X[:, 0], X[:, 1],
c=y_pred,
cmap='viridis',
s=30,
alpha=0.7
)
# 标出聚类中心
plt.scatter(
af.cluster_centers_[:, 0],
af.cluster_centers_[:, 1],
c='red',
marker='x',
s=120,
linewidths=2,
label='聚类中心'
)
plt.title('Affinity Propagation Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()
关键参数说明
| 参数 | 说明 |
|---|---|
damping |
阻尼系数,默认 0.5,常用 0.9。越大越不容易振荡,但收敛慢。 |
preference |
偏好参数。值越大,产生的簇越多;值越小,产生的簇越少。默认 None,表示使用相似度中位数。 |
affinity |
相似度计算方式。'euclidean' 表示使用负欧氏距离;'precomputed' 表示传入相似度矩阵。 |
max_iter |
最大迭代次数。 |
convergence_iter |
连续多少次迭代结果不变则认为收敛。 |
random_state |
随机种子,用于结果可复现。 |
常用属性
af.labels_ # 每个样本的簇标签
af.cluster_centers_ # 聚类中心坐标,实际是原始样本点
af.cluster_centers_indices_ # 聚类中心在原始数据中的索引
af.affinity_matrix_ # 相似度矩阵
af.n_iter_ # 实际迭代次数
使用预计算相似度矩阵
如果已经有一个相似度矩阵,可以这样使用:
from sklearn.metrics.pairwise import euclidean_distances
# 相似度矩阵,越大表示越相似;这里用负平方欧氏距离
S = -euclidean_distances(X, squared=True)
af = AffinityPropagation(
affinity='precomputed',
preference=-50,
random_state=42
)
labels = af.fit_predict(S)
注意事项
AffinityPropagation不需要指定n_clusters,但结果对preference和damping比较敏感。- 算法时间和内存复杂度较高,适合中小规模数据集。
- 如果特征量纲差异较大,建议先用
StandardScaler标准化。 - 聚类中心是实际样本点,而不是像 KMeans 那样计算出的均值点。
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)