Affinity Propagation Demo1学习
利用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学习的更多相关文章
- Affinity Propagation Demo2学习【可视化股票市场结构】
这个例子利用几个无监督的技术从历史报价的变动中提取股票市场结构. 使用报价的日变化数据进行试验. Learning a graph structure 首先使用sparse inverse(相反) c ...
- AP(affinity propagation)研究
待补充…… AP算法,即Affinity propagation,是Brendan J. Frey* 和Delbert Dueck于2007年在science上提出的一种算法(文章链接,维基百科) 现 ...
- Affinity Propagation Algorithm
The principle of Affinity Propagation Algorithm is discribed at above. It is widly applied in many f ...
- Affinity Propagation
1. 调用方法: AffinityPropagation(damping=0.5, max_iter=200, convergence_iter=15, copy=True, preference=N ...
- AP聚类算法(Affinity propagation Clustering Algorithm )
AP聚类算法是基于数据点间的"信息传递"的一种聚类算法.与k-均值算法或k中心点算法不同,AP算法不需要在运行算法之前确定聚类的个数.AP算法寻找的"examplars& ...
- knn/kmeans/kmeans++/Mini Batch K-means/Affinity Propagation/Mean Shift/层次聚类/DBSCAN 区别
可以看出来除了KNN以外其他算法都是聚类算法 1.knn/kmeans/kmeans++区别 先给大家贴个简洁明了的图,好几个地方都看到过,我也不知道到底谁是原作者啦,如果侵权麻烦联系我咯~~~~ k ...
- [Python] 机器学习库资料汇总
声明:以下内容转载自平行宇宙. Python在科学计算领域,有两个重要的扩展模块:Numpy和Scipy.其中Numpy是一个用python实现的科学计算包.包括: 一个强大的N维数组对象Array: ...
- 【转帖】Python在大数据分析及机器学习中的兵器谱
Flask:Python系的轻量级Web框架. 1. 网页爬虫工具集 Scrapy 推荐大牛pluskid早年的一篇文章:<Scrapy 轻松定制网络爬虫> Beautiful Soup ...
- python数据挖掘领域工具包
原文:http://qxde01.blog.163.com/blog/static/67335744201368101922991/ Python在科学计算领域,有两个重要的扩展模块:Numpy和Sc ...
随机推荐
- ASP.NET Core Web程序托管到Windows 服务
前言 在 .NET Core 3.1和WorkerServices构建Windows服务 我们也看到了,如何将workerservices构建成服务,那么本篇文章我们再来看看如何将web应用程序托管到 ...
- codevs 3981 动态最大子段和(线段树)
题目传送门:codevs 3981 动态最大子段和 题目描述 Description 题目还是简单一点好... 有n个数,a[1]到a[n]. 接下来q次查询,每次动态指定两个数l,r,求a[l]到a ...
- java架构之路(多线程)大厂方式手写单例模式
上期回顾: 上次博客我们说了我们的volatile关键字,我们知道volatile可以保证我们变量被修改马上刷回主存,并且可以有效的防止指令重排序,思想就是加了我们的内存屏障,再后面的多线程博客里还有 ...
- rest实践3
1.从mongodb的数据实体Document中获取其中一个字段的值,即例如:doc.getString("pid"),直接显示value. 2.当从网络上的网址url的图片直接弄 ...
- django count(*) 慢查询优化
分页显示是web开发常见需求,随着表数据增加,200万以上时,翻页越到后面越慢,这个时候慢查询成为一个痛点,关于count(*)慢的原因,简单说会进行全表扫描,再排序,导致查询变慢.这里介绍postg ...
- Java入门 - 语言基础 - 08.运算符
原文地址:http://www.work100.net/training/java-operator.html 更多教程:光束云 - 免费课程 运算符 序号 文内章节 视频 1 概述 2 算术运算符 ...
- typescript 第一弹
typescript官网: http://typescriptlang.org typescript 在线运行环境: http://www.typescriptlang.org/play/index. ...
- HGE引擎改进——2014/2/18 和 2014/2/27
2014/2/18 更新 hgehelper库:增加hgeSkeleton类,该类用于播放骨骼动画 增加工具骨骼动画编辑器(AnimationEd),该工具用于骨骼动画的编辑 2014/2/27 更新 ...
- [转]在C#中调用C语言函数(静态调用Native DLL,Windows & Microsoft.Net平台)
原文:https://blog.csdn.net/yapingxin/article/details/7288325 对于不太了解.Net的人,如果想要了解.Net,我必须给他介绍P/Invoke.P ...
- Java容器解析系列(16) android内存优化之SparseArray
HashMap的缺点: 自动装箱导致的性能损失; 使用拉链法来解决hash冲突,如果hash冲突较多,需要遍历链表,导致性能下降,在Java 8 中,如果链表长度>8,会使用红黑树来代替链表; ...