Python实现K-means聚类

kmeans是最简单的聚类算法之一,但是运用十分广泛。最近在工作中也经常遇到这个算法。kmeans一般在数据分析前期使用,选取适当的k,将数据分类后,然后分类研究不同聚类下数据的特点。

kmeans算法步骤:

1 随机选取k个中心点

2 遍历所有数据,将每个数据划分到最近的中心点中

3 计算每个聚类的平均值,并作为新的中心点

4 重复2-3,直到这k个聚类中心点不再变化(收敛了),或执行了足够多的迭代


下面是一个对二维数据用K-means进行聚类的示例,类中心标记为绿色大圆环,聚类出的两类分别标记为蓝色星号和红色点。

实现代码:

from scipy.cluster.vq import *
from numpy.random import randn
from numpy import vstack
from numpy import array
from numpy import where
from matplotlib.pyplot import figure
from matplotlib.pyplot import plot
from matplotlib.pyplot import axis
from matplotlib.pyplot import show

class1=1.5*randn(100,2)
class2=randn(100,2)+array([5,5])

features=vstack((class1,class2))

centriods,variance=kmeans(features,2)

code,distance=vq(features,centriods)

figure()
ndx=where(code==0)[0]
plot(features[ndx,0],features[ndx,1],'*')

ndx=where(code==1)[0]
plot(features[ndx,0],features[ndx,1],'r.')

plot(centriods[:,0],centriods[:,1],'go')
axis('off')
show()



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值