import numpy as np

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances
import matplotlib.pyplot as plt
import matplotlib as mpl
from cycler import cycler from .tools import discrete_scatter
from .plot_2d_separator import plot_2d_classification
from .plot_helpers import cm3 def plot_kmeans_algorithm(): X, y = make_blobs(random_state=1)
# we don't want cyan in there
with mpl.rc_context(rc={'axes.prop_cycle': cycler('color', ['#0000aa',
'#ff2020',
'#50ff50'])}):
fig, axes = plt.subplots(3, 3, figsize=(10, 8), subplot_kw={'xticks': (), 'yticks': ()})
axes = axes.ravel()
axes[0].set_title("Input data")
discrete_scatter(X[:, 0], X[:, 1], ax=axes[0], markers=['o'], c='w') axes[1].set_title("Initialization")
init = X[:3, :]
discrete_scatter(X[:, 0], X[:, 1], ax=axes[1], markers=['o'], c='w')
discrete_scatter(init[:, 0], init[:, 1], [0, 1, 2], ax=axes[1],
markers=['^'], markeredgewidth=2) axes[2].set_title("Assign Points (1)")
km = KMeans(n_clusters=3, init=init, max_iter=1, n_init=1).fit(X)
centers = km.cluster_centers_
# need to compute labels by hand. scikit-learn does two e-steps for max_iter=1
# (and it's totally my fault)
labels = np.argmin(pairwise_distances(init, X), axis=0)
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[2])
discrete_scatter(init[:, 0], init[:, 1], [0, 1, 2],
ax=axes[2], markers=['^'], markeredgewidth=2) axes[3].set_title("Recompute Centers (1)")
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[3])
discrete_scatter(centers[:, 0], centers[:, 1], [0, 1, 2],
ax=axes[3], markers=['^'], markeredgewidth=2) axes[4].set_title("Reassign Points (2)")
km = KMeans(n_clusters=3, init=init, max_iter=1, n_init=1).fit(X)
labels = km.labels_
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[4])
discrete_scatter(centers[:, 0], centers[:, 1], [0, 1, 2],
ax=axes[4], markers=['^'], markeredgewidth=2) km = KMeans(n_clusters=3, init=init, max_iter=2, n_init=1).fit(X)
axes[5].set_title("Recompute Centers (2)")
centers = km.cluster_centers_
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[5])
discrete_scatter(centers[:, 0], centers[:, 1], [0, 1, 2],
ax=axes[5], markers=['^'], markeredgewidth=2) axes[6].set_title("Reassign Points (3)")
labels = km.labels_
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[6])
markers = discrete_scatter(centers[:, 0], centers[:, 1], [0, 1, 2],
ax=axes[6], markers=['^'],
markeredgewidth=2) axes[7].set_title("Recompute Centers (3)")
km = KMeans(n_clusters=3, init=init, max_iter=3, n_init=1).fit(X)
centers = km.cluster_centers_
discrete_scatter(X[:, 0], X[:, 1], labels, markers=['o'],
ax=axes[7])
discrete_scatter(centers[:, 0], centers[:, 1], [0, 1, 2],
ax=axes[7], markers=['^'], markeredgewidth=2)
axes[8].set_axis_off()
axes[8].legend(markers, ["Cluster 0", "Cluster 1", "Cluster 2"], loc='best') def plot_kmeans_boundaries():
X, y = make_blobs(random_state=1)
init = X[:3, :]
km = KMeans(n_clusters=3, init=init, max_iter=2, n_init=1).fit(X)
discrete_scatter(X[:, 0], X[:, 1], km.labels_, markers=['o'])
discrete_scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1],
[0, 1, 2], markers=['^'], markeredgewidth=2)
plot_2d_classification(km, X, cm=cm3, alpha=.4) def plot_kmeans_faces(km, pca, X_pca, X_people, y_people, target_names):
n_clusters = 10
image_shape = (87, 65)
fig, axes = plt.subplots(n_clusters, 11, subplot_kw={'xticks': (), 'yticks': ()},
figsize=(10, 15), gridspec_kw={"hspace": .3}) for cluster in range(n_clusters):
center = km.cluster_centers_[cluster]
mask = km.labels_ == cluster
dists = np.sum((X_pca - center) ** 2, axis=1)
dists[~mask] = np.inf
inds = np.argsort(dists)[:5]
dists[~mask] = -np.inf
inds = np.r_[inds, np.argsort(dists)[-5:]]
axes[cluster, 0].imshow(pca.inverse_transform(center).reshape(image_shape), vmin=0, vmax=1)
for image, label, asdf, ax in zip(X_people[inds], y_people[inds],
km.labels_[inds], axes[cluster, 1:]):
ax.imshow(image.reshape(image_shape), vmin=0, vmax=1)
ax.set_title("%s" % (target_names[label].split()[-1]), fontdict={'fontsize': 9}) # add some boxes to illustrate which are similar and which dissimilar
rec = plt.Rectangle([-5, -30], 73, 1295, fill=False, lw=2)
rec = axes[0, 0].add_patch(rec)
rec.set_clip_on(False)
axes[0, 0].text(0, -40, "Center") rec = plt.Rectangle([-5, -30], 385, 1295, fill=False, lw=2)
rec = axes[0, 1].add_patch(rec)
rec.set_clip_on(False)
axes[0, 1].text(0, -40, "Close to center") rec = plt.Rectangle([-5, -30], 385, 1295, fill=False, lw=2)
rec = axes[0, 6].add_patch(rec)
rec.set_clip_on(False)
axes[0, 6].text(0, -40, "Far from center")

过程解析:

在大数据集的情况下还可以使用scikit-learn 提供了MiniBatchKMeans算法,大致思想就是对数据进行抽样,每次不使用所有的数据来计算,这就会导致准确率的损失。

MiniBatchKmeans 继承自Kmeans 因为MiniBathcKmeans 本质上还利用了Kmeans 的思想.从构造方法和文档大致能看到这些参数的含义,了解了这些参数会对使用的时候有很大的帮助。batch_size 是每次选取的用于计算的数据的样本量,默认为100.Mini Batch K-Means算法是K-Means算法的变种,采用小批量的数据子集减小计算时间,同时仍试图优化目标函数,这里所谓的小批量是指每次训练算法时所随机抽取的数据子集,采用这些随机产生的子集进行训练算法,大大减小了计算时间,与其他算法相比,减少了k-均值的收敛时间,小批量k-均值产生的结果,一般只略差于标准算法。

代码只需要修改一行:

clf = MiniBatchKMeans(n_clusters = 3)

聚类K-Means和大数据集的Mini Batch K-Means算法的更多相关文章

  1. 转载: scikit-learn学习之K-means聚类算法与 Mini Batch K-Means算法

    版权声明:<—— 本文为作者呕心沥血打造,若要转载,请注明出处@http://blog.csdn.net/gamer_gyt <—— 目录(?)[+] ================== ...

  2. 数学建模及机器学习算法(一):聚类-kmeans(Python及MATLAB实现,包括k值选取与聚类效果评估)

    一.聚类的概念 聚类分析是在数据中发现数据对象之间的关系,将数据进行分组,组内的相似性越大,组间的差别越大,则聚类效果越好.我们事先并不知道数据的正确结果(类标),通过聚类算法来发现和挖掘数据本身的结 ...

  3. R处理大数据集

    R会把所有的对象读存入虚拟内存中.对我们大多数用户来说,这种设计可以提高与R相互的速度,但是当分析大数据集时,这种设计会降低程序运行速度有时还会产生跟内存相关的错误. 内存限制主要取决于R的build ...

  4. centos7 ambari2.6.1.5+hdp2.6.4.0 大数据集群安装部署

    前言 本文是讲如何在centos7(64位) 安装ambari+hdp,如果在装有原生hadoop等集群的机器上安装,需要先将集群服务停掉,然后将不需要的环境变量注释掉即可,如果不注释掉,后面虽然可以 ...

  5. CDH版本大数据集群下搭建Hue(hadoop-2.6.0-cdh5.5.4.gz + hue-3.9.0-cdh5.5.4.tar.gz)(博主推荐)

    不多说,直接上干货! 我的集群机器情况是 bigdatamaster(192.168.80.10).bigdataslave1(192.168.80.11)和bigdataslave2(192.168 ...

  6. 大数据集群Linux CentOS 7.6 系统调优篇

    大数据集群Linux CentOS 7.6 系统调优篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.设置主机hosts文件 1>.修改主机名 [root@node100 ...

  7. 使用ansible部署CDH 5.15.1大数据集群

    使用ansible离线部署CDH 5.15.1大数据集群 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在此之前,我之前分享过使用shell自定义脚本部署大数据集群,不管是部署CD ...

  8. FineReport层式报表解决大数据集展示问题攻略

    本文以填报报表为例,通过分页的方式,来解决大数据集展示的问题. 实现的思想就是通过在SQL里筛选部分数据库数据,以达到浏览器可以合理的展示报表页面.(数据分段,语句我这采用的是MYSQL,如果要用其他 ...

  9. 【网站运营】网站被K的原因大总结

    对于广大的站长来说网站被K或者是被降权是经常有的事情,不过我基本上还没有看见过Google的K站情况,也就是给网站降个权什么的处罚.如果你是用了很严重的作弊手段的话,那指定会是被Google给K掉的. ...

随机推荐

  1. 关于C3P0-mySQL关于url的细节问题

    1.为url设置?useUnicode=true&characterEncoding=UTF-8 为了统一编码,我们会为数据库封装的实体类加上上面的那句话,但是C3P0数据库连接池是xml配置 ...

  2. Spring Cloud 组件 —— hystrix

    作用与功能 ① 资源隔离, 每个依赖配备单独的线程池,为每个依赖提供一个小的线程池(或信号),如果线程池已满调用将被立即拒绝,默认不采用排队.加速失败判定时间.② 依赖超时,可配置依赖调用超时时间,超 ...

  3. C++编译原理

    链接

  4. c语言中字符串转数字的函数

    ANSI C 规范定义了 atof().atoi().atol().strtod().strtol().strtoul() 共6个可以将字符串转换为数字的函数,大家可以对比学习.另外在 C99 / C ...

  5. jumpserver 安装

    # CentOS 7 安装jumpserver $ setenforce 0 # 可以设置配置文件永久关闭$ systemctl stop iptables.service$ systemctl st ...

  6. 【一起来烧脑】一步学会HTML体系

    [外链图片转存失败(img-zk4xNuy1-1563431241992)(https://upload-images.jianshu.io/upload_images/11158618-4e9cac ...

  7. Oracle误删除数据恢复。Oracle删除后恢复数据

    发现误删除时需要及时处理,速度要快,姿势要帅.晚了就恢复不了额 1.查询时间 以确保恢复到某个时间点 select SQL_TEXT, LAST_ACTIVE_TIME from v$sqlarea ...

  8. Flask一种通用视图,增删改查RESTful API的设计

    模型设计是后端开发的第一步.数据模型反映了各种对象之间的相互关系. from app import db class Role(db.Model): """角色" ...

  9. SVN版本回滚实战

    天在使用SVN发布的时候不小心修改了一些不正确的东西,新增和编辑了一些错误的文件,由于文件数量比较多,并且目录复杂,不可能单个进行处理,所以想到了SVN版本回滚. 回滚本地工作目录: 1.右键工作目录 ...

  10. Bootstrap selectpicker 下拉框多选获取选中value和多选获取文本值

    1.页面代码: 页面引入: bootstrap-select.min.css和 bootstrap-select.min.js. defaults-zh_CN.min.js文件,并初始化下拉选项框. ...