import numpy as np
import matplotlib.pyplot as plt from sklearn import cluster
from sklearn.metrics import adjusted_rand_score
from sklearn.datasets.samples_generator import make_blobs def create_data(centers,num=100,std=0.7):
X, labels_true = make_blobs(n_samples=num, centers=centers, cluster_std=std)
return X,labels_true # 用于产生聚类的中心点
centers=[[1,1],[2,2],[1,2],[10,20]]
# 产生用于聚类的数据集
X,labels_true=create_data(centers,1000,0.5) #K-MEANS聚类模型
def test_Kmeans(*data):
X,labels_true=data
clst=cluster.KMeans()
clst.fit(X)
predicted_labels=clst.predict(X)
print("ARI:%s"% adjusted_rand_score(labels_true,predicted_labels))
print("Sum center distance %s"%clst.inertia_) # 用于产生聚类的中心点
centers=[[1,1],[2,2],[1,2],[10,20]]
# 产生用于聚类的数据集
X,labels_true=create_data(centers,1000,0.5)
# 调用 test_Kmeans 函数
test_Kmeans(X,labels_true)

def test_Kmeans_nclusters(*data):
'''
测试 KMeans 的聚类结果随 n_clusters 参数的影响
'''
X,labels_true=data
nums=range(1,50)
ARIs=[]
Distances=[]
for num in nums:
clst=cluster.KMeans(n_clusters=num)
clst.fit(X)
predicted_labels=clst.predict(X)
ARIs.append(adjusted_rand_score(labels_true,predicted_labels))
Distances.append(clst.inertia_)
## 绘图
fig=plt.figure()
ax=fig.add_subplot(1,2,1)
ax.plot(nums,ARIs,marker="+")
ax.set_xlabel("n_clusters")
ax.set_ylabel("ARI")
ax=fig.add_subplot(1,2,2)
ax.plot(nums,Distances,marker='o')
ax.set_xlabel("n_clusters")
ax.set_ylabel("inertia_")
fig.suptitle("KMeans")
plt.show() test_Kmeans_nclusters(X,labels_true) # 调用 test_Kmeans_nclusters 函数

def test_Kmeans_n_init(*data):
'''
测试 KMeans 的聚类结果随 n_init 和 init 参数的影响
'''
X,labels_true=data
nums=range(1,50)
## 绘图
fig=plt.figure() ARIs_k=[]
Distances_k=[]
ARIs_r=[]
Distances_r=[]
for num in nums:
clst=cluster.KMeans(n_init=num,init='k-means++')
clst.fit(X)
predicted_labels=clst.predict(X)
ARIs_k.append(adjusted_rand_score(labels_true,predicted_labels))
Distances_k.append(clst.inertia_) clst=cluster.KMeans(n_init=num,init='random')
clst.fit(X)
predicted_labels=clst.predict(X)
ARIs_r.append(adjusted_rand_score(labels_true,predicted_labels))
Distances_r.append(clst.inertia_) ax=fig.add_subplot(1,2,1)
ax.plot(nums,ARIs_k,marker="+",label="k-means++")
ax.plot(nums,ARIs_r,marker="+",label="random")
ax.set_xlabel("n_init")
ax.set_ylabel("ARI")
ax.set_ylim(0,1)
ax.legend(loc='best')
ax=fig.add_subplot(1,2,2)
ax.plot(nums,Distances_k,marker='o',label="k-means++")
ax.plot(nums,Distances_r,marker='o',label="random")
ax.set_xlabel("n_init")
ax.set_ylabel("inertia_")
ax.legend(loc='best') fig.suptitle("KMeans")
plt.show() test_Kmeans_n_init(X,labels_true) # 调用 test_Kmeans_n_init 函数

吴裕雄 python 机器学习——K均值聚类KMeans模型的更多相关文章

  1. 吴裕雄 python 机器学习——混合高斯聚类GMM模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import mixture from sklearn.metrics ...

  2. 吴裕雄 python 机器学习——超大规模数据集降维IncrementalPCA模型

    # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from sklearn import datas ...

  3. 吴裕雄 python 机器学习——数据预处理正则化Normalizer模型

    from sklearn.preprocessing import Normalizer #数据预处理正则化Normalizer模型 def test_Normalizer(): X=[[1,2,3, ...

  4. 吴裕雄 python 机器学习——数据预处理标准化MaxAbsScaler模型

    from sklearn.preprocessing import MaxAbsScaler #数据预处理标准化MaxAbsScaler模型 def test_MaxAbsScaler(): X=[[ ...

  5. 吴裕雄 python 机器学习——数据预处理标准化StandardScaler模型

    from sklearn.preprocessing import StandardScaler #数据预处理标准化StandardScaler模型 def test_StandardScaler() ...

  6. 吴裕雄 python 机器学习——数据预处理标准化MinMaxScaler模型

    from sklearn.preprocessing import MinMaxScaler #数据预处理标准化MinMaxScaler模型 def test_MinMaxScaler(): X=[[ ...

  7. 吴裕雄 python 机器学习——支持向量机线性分类LinearSVC模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets, linear_model,svm fr ...

  8. 吴裕雄 python 机器学习——数据预处理字典学习模型

    from sklearn.decomposition import DictionaryLearning #数据预处理字典学习DictionaryLearning模型 def test_Diction ...

  9. 吴裕雄 python 机器学习——数据预处理流水线Pipeline模型

    from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn import neighbor ...

随机推荐

  1. 8、技术分析fastJson使用

    一.导入包 二.使用 package com.itheima.test; import java.util.ArrayList; import java.util.List; import org.j ...

  2. tyvj P3737 逐个击破

    http://tyvj.cn/p/3737 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 秉承伟大军事家的战略思想,作为一个有智慧的军长你,遇到了一个类似的 ...

  3. python3--json反序列化

    # Auther: Aaron Fan # 加载文件中的数据 import json with open('test.txt','r',encoding='utf-8') as f: info = j ...

  4. Spring.net 容器注入是替换(后处理器appConfigPropertyHolder)

    .定义节点 下面两个都定义为键值对 <section name="DaoConfiguration" type="System.Configuration.Name ...

  5. centos环境下如何导出数据库

    MySQL数据库的导入导出可以用数据库备份工具mysqldump mysqldump工具是mysql自带的一个非常方便的一款小工具,存在mysql安装目录的/usr/local/mysql/bin ( ...

  6. .NET分布式事务处理(转)

    出处:http://www.cnblogs.com/youring2/archive/2011/06/12/MSDTC.html 在进行数据持久化的时候,我们会经常用到事务处理.一般情况下,ADO.N ...

  7. monkeyrunner小结

    上次说到已经配好了MonkeyRunner的运行环境,现在讲解怎么进行简单的MonkeyRunner测试.这个拖了很久才有时间和心情总结一下.真是计划赶不上变化啊. 就不说废话了.http://dev ...

  8. app里面嵌套的H5页面上电话号码怎么才能点击拨号?

    代码: <p>联系我们:<a href="tel://66666666666">66666666666</a> </p>

  9. CodeForces 682C Alyona and the Tree (树上DFS)

    题意:给定一棵树,每个叶子有一个权值,每条边也有一个权值,现在让你删最少的结点,使得从任何结点出发到另一个结点的边上权值和都小于两个结点的权值. 析:很明显是DFS,不过要想找出最少的结点可能不太容易 ...

  10. win7 iis7 ftp配置

    1.安装ftp服务器 开始菜单找到控制面板>在左侧找到打开或关闭windows功能点击 弹出如下对话框, 在弹出的对话框中找到Internet信息服务,如下 然后如上图所示,选中ftp服务器复选 ...