利用AP算法进行聚类:

首先导入需要的包:

from sklearn.cluster import AffinityPropagation
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs

生成一组数据:

centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5, random_state=0)

以上代码包括3个类簇的中心点以及300个以这3个点为中心的样本点。

接下来要利用AP算法对这300个点进行聚类。

af = AffinityPropagation(preference=-50).fit(X) # preference采用负的欧氏距离
cluster_centers_indices = af.cluster_centers_indices_
labels = af.labels_ # 样本标签
n_clusters_ = len(cluster_centers_indices) # 类簇数

打印各种评价指标分数:

print('估计的类簇数: %d' % n_clusters_)
print('Homogeneity: %0.3f' % metrics.homogeneity_score(labels_true, labels))
print('Completeness: %0.3f' %metrics.completeness_score(labels_true, labels))
print('V-measure: %0.3f' %metrics.v_measure_score(labels_true, labels))
print('Adjusted Rand Index:%0.3f' %metrics.adjusted_rand_score(labels_true, labels))
print('Adjusted Mutual Information:%0.3f'%metrics.adjusted_mutual_info_score(labels_true, labels))
print('Silhouette Coefficient:%0.3f' %metrics.silhouette_score(X, labels, metric='sqeuclidean')) # sqeuclidean欧式距离平方

可视化聚类结果:

导入画图需要的包:

import matplotlib.pyplot as plt
from itertools import cycle
plt.close('all')
plt.figure(1)
plt.clf() # 清除当前图的所有信息
colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
close()方法介绍【可忽略】
close方法简介:

matplotlib.pyplot.close(*args)   --- Close a figure window.
close() by itself closes the current figure close(fig) closes the Figure instance fig close(num) closes the figure number num close(name) where name is a string, closes figure with that label close('all') closes all the figure windows
for k, col in zip(range(n_clusters_),colors):
class_members = labels == k;
print('k:',k)
print('labels:',labels)
print('cls_member--------',class_members)
  cluster_center = X[cluster_centers_indices[k]]
  print('cluster_center:', cluster_center)
# 画样本点
  plt.plot(X[class_members, 0], X[class_members, 1], col + '.')
  # 画中心点
  plt.plot(cluster_center[0], cluster_center[1], 'o',
markeredgecolor='k', markersize=28)
  
# 划线
  for x in X[class_members]:
   plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) plt.title('Estimated number of clusters:%d' %n_clusters_)
plt.show()# 显示图
运行结果:

完整代码:
print(__doc__)

from sklearn.cluster import AffinityPropagation
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs # #################################################
# generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5, random_state=0) # #######################################################
# Compute Affinity Propagation
af = AffinityPropagation(preference=-50).fit(X) # preference采用负的欧氏距离
cluster_centers_indices = af.cluster_centers_indices_
labels = af.labels_ # 样本标签 n_clusters_ = len(cluster_centers_indices) # 类簇数 print('估计的类簇数: %d' % n_clusters_)
print('Homogeneity: %0.3f' % metrics.homogeneity_score(labels_true, labels))
print('Completeness: %0.3f' %metrics.completeness_score(labels_true, labels))
print('V-measure: %0.3f' %metrics.v_measure_score(labels_true, labels))
print('Adjusted Rand Index:%0.3f' %metrics.adjusted_rand_score(labels_true, labels))
print('Adjusted Mutual Information:%0.3f'%metrics.adjusted_mutual_info_score(labels_true, labels))
print('Silhouette Coefficient:%0.3f' %metrics.silhouette_score(X, labels, metric='sqeuclidean')) # sqeuclidean欧式距离平方 # ##########################################################
# Plot result
import matplotlib.pyplot as plt
from itertools import cycle plt.close('all')
plt.figure(1)
plt.clf()
colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
for k, col in zip(range(n_clusters_),colors):
class_members = labels == k;
print('k:',k)
print('labels:',labels)
print('cls_member--------',class_members) cluster_center = X[cluster_centers_indices[k]]
print('cluster_center:', cluster_center)
plt.plot(X[class_members, 0], X[class_members, 1], col + '.')
plt.plot(cluster_center[0], cluster_center[1], 'o',
markeredgecolor='k', markersize=28) # 划线
for x in X[class_members]:
plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) plt.title('Estimated number of clusters:%d' %n_clusters_)
plt.show()

Affinity Propagation Demo1学习的更多相关文章

  1. Affinity Propagation Demo2学习【可视化股票市场结构】

    这个例子利用几个无监督的技术从历史报价的变动中提取股票市场结构. 使用报价的日变化数据进行试验. Learning a graph structure 首先使用sparse inverse(相反) c ...

  2. AP(affinity propagation)研究

    待补充…… AP算法,即Affinity propagation,是Brendan J. Frey* 和Delbert Dueck于2007年在science上提出的一种算法(文章链接,维基百科) 现 ...

  3. Affinity Propagation Algorithm

    The principle of Affinity Propagation Algorithm is discribed at above. It is widly applied in many f ...

  4. Affinity Propagation

    1. 调用方法: AffinityPropagation(damping=0.5, max_iter=200, convergence_iter=15, copy=True, preference=N ...

  5. AP聚类算法(Affinity propagation Clustering Algorithm )

    AP聚类算法是基于数据点间的"信息传递"的一种聚类算法.与k-均值算法或k中心点算法不同,AP算法不需要在运行算法之前确定聚类的个数.AP算法寻找的"examplars& ...

  6. knn/kmeans/kmeans++/Mini Batch K-means/Affinity Propagation/Mean Shift/层次聚类/DBSCAN 区别

    可以看出来除了KNN以外其他算法都是聚类算法 1.knn/kmeans/kmeans++区别 先给大家贴个简洁明了的图,好几个地方都看到过,我也不知道到底谁是原作者啦,如果侵权麻烦联系我咯~~~~ k ...

  7. [Python] 机器学习库资料汇总

    声明:以下内容转载自平行宇宙. Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: ...

  8. 【转帖】Python在大数据分析及机器学习中的兵器谱

    Flask:Python系的轻量级Web框架. 1. 网页爬虫工具集 Scrapy 推荐大牛pluskid早年的一篇文章:<Scrapy 轻松定制网络爬虫> Beautiful Soup ...

  9. python数据挖掘领域工具包

    原文:http://qxde01.blog.163.com/blog/static/67335744201368101922991/ Python在科学计算领域,有两个重要的扩展模块:Numpy和Sc ...

随机推荐

  1. win设置C、D、E等盘符图标为自定义的图片

    1.选择一张jpg图片,在下面网站工具上,转为ico的图片(最好转64x64的清晰些). http://www.faviconico.org/favicon 2.在D盘下新建文本文件.txt,写入以下 ...

  2. Android/Unity大乱斗-完整双方集成交互指南

    这是一个很长很长的story!-芝麻粒儿创作 开篇 源码地址:GitHub 本文目的,将Unity集成到Android端,学完本文后你可以做到 Android任意布局加载Unity 3D场景 任意操作 ...

  3. 正则表达式grep命令

    grep命令 作用:文本搜索工具,根据用户指定的“模式”对目标文本逐行进行匹配检查:打印匹配到的行. 模式::由正则表达式字符及文本字符所编写的过滤条件 语法:grep [OPTIONS] PATTE ...

  4. Python爬虫入门教程 33-100 电影评论数据抓取 scrapy

    1. 海王评论数据爬取前分析 海王上映了,然后口碑炸了,对咱来说,多了一个可爬可分析的电影,美哉~ 摘录一个评论 零点场刚看完,温导的电影一直很不错,无论是速7,电锯惊魂还是招魂都很棒.打斗和音效方面 ...

  5. 原生JS在网页上复制的所有文字后面自动加上一段版权声明

    不少技术博客有这样的处理,当我们复制代码的时候,会自动加上一段本信息版权为XXXX,这是怎么实现的呢? 其实实现的方式很简单,可以在我的网站页面上绑定一个copy事件,当你复制文章内容的时候,自动在剪 ...

  6. 【转】KAFKA分布式消息系统

    Kafka[1]是linkedin用于日志处理的分布式消息队列,linkedin的日志数据容量大,但对可靠性要求不高,其日志数据主要包括用户行为(登录.浏览.点击.分享.喜欢)以及系统运行日志(CPU ...

  7. 玩转Django2.0---Django笔记建站基础四(视图)

    第四章 视图 4.1 探究视图 一.视图说明 视图(View)是Django的MTV架构模式的V部分,主要负责处理用户请求和生成相应的相应部分,然后在页面或其它类型文档中显示.也可以理解为视图是MVC ...

  8. octave在win上和linux上配置syms

    octave是类似matlab的一个科学计算工具集.需要用到积分.微分.求导的时候,需要连接python3的sympy. windows上先安装好python3,然后pip安装Sympy.具体过程: ...

  9. Excel.Application class

    https://docs.microsoft.com/en-us/javascript/api/excel/excel.application?view=office-js Represents th ...

  10. Add Scaffold