【机器学习—聚类】
# 亲和力传播聚类
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.cluster import AffinityPropagation
# 定义数据集
X, _ = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=4)
# 定义模型
model = AffinityPropagation(damping=0.9)
# 匹配模型
model.fit(X)
# 为每个示例分配一个集群
yhat = model.predict(X)
# 检索唯一群集
clusters = np.unique(yhat)
# 为每个群集的样本创建散点图
plt.figure(figsize=(8,6))
plt.rcParams['font.size']=15
for cluster in clusters:
# 获取此群集的示例的行索引
row_ix = np.where(yhat == cluster)
# 创建这些样本的散布
plt.scatter(X[row_ix, 0], X[row_ix, 1])
plt.title('AffinityPropagation')
# 绘制散点图
plt.show()