利用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. 1081 检查密码 (15分)C语言

    本题要求你帮助某网站的用户注册模块写一个密码合法性检查的小功能.该网站要求用户设置的密码必须由不少于6个字符组成,并且只能有英文字母.数字和小数点 .,还必须既有字母也有数字. 输入格式: 输入第一行 ...

  2. java基础之----非空判断

    大家好,第一次写博客,一直想写博客,用于自我总结,也用于帮助新同学成长. 平常我们开发的时候,用到很多非空判断,但是很多同学用到的地方不是很准确,这里,我把自己平时遇到的坑跟大家说说.我废话不多,只想 ...

  3. Mysql备份与恢复(2)---逻辑备份

    数据库及时备份可以帮助我们在数据库出现异常宕机时及时的使用备份数据进行恢复工作,将因为数据库宕机产生的影响降低到最小.上一篇针对使用xtrabackup工具进行物理备份和数据恢复做了一个详细讲解,本篇 ...

  4. Asp.Net Core下的开源任务调度平台ScheduleMaster

    从何说起 2017年初的时候,由于当时项目需要做了一个乞丐版定时调度系统,那时候只在单机上实现了核心的调度功能.做这个玩意之前也调研了社区中开源的解决方案,找了几个实地部署试跑了一下,其实都很不错.但 ...

  5. OpenJ_Bailian 2815 城堡问题(DFS)

    题目传送门OpenJ_Bailian 2815 描述 1 2 3 4 5 6 7 ############################# 1 # | # | # | | # #####---### ...

  6. [Micropython]TPYBoard v202 智能WIFI远控小车

    转载请注明文章来源,更多教程可自助参考docs.tpyboard.com,QQ技术交流群:157816561,公众号:MicroPython玩家汇 前言---------------------- 之 ...

  7. Scrapy的基本使用

    爬取:http://quotes.toscrape.com 单页面 # -*- coding: utf-8 -*- import scrapy class QuoteSpider(scrapy.Spi ...

  8. python文件与输入输出

    注:本文档是学习<Python核心编程(第二版)>时的整理. 1.文件对象 文件对象不仅可以用来访问普通的磁盘文件,也可以访问任何其他类型抽象层面上的"文件".一旦设置 ...

  9. ip 地址库 这个 准么 呢

  10. Python学习,第六课 - 集合

    Python中集合的相关操作 集合是一个无序的,不重复的数据组合 它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 list_1 =set ...