python机器人算法_Kemans算法及其Python 实现

#coding=utf-8

from numpy import *

defloadDataSet(fileName):

dataMat=[]

fr=open(fileName)for line infr.readlines():

curLine= line.strip().split('\t')

fltLine=map(float, curLine)

dataMat.append(fltLine)returndataMat#计算两个向量的距离,用的是欧几里得距离

defdistEclud(vecA, vecB):return sqrt(sum(power(vecA - vecB, 2)))#随机生成初始的质心(ng的课说的初始方式是随机选K个点)

defrandCent(dataSet, k):

n= shape(dataSet)[1]

centroids=mat(zeros((k,n)))for j inrange(n):

minJ=min(dataSet[:,j])

rangeJ= float(max(array(dataSet)[:,j]) -minJ)

centroids[:,j]= minJ + rangeJ * random.rand(k,1)returncentroidsdef kMeans(dataSet, k, distMeas=distEclud, createCent=randCent):

m=shape(dataSet)[0]

clusterAssment= mat(zeros((m,2)))#create mat to assign data points

#to a centroid, also holds SE of each point

centroids =createCent(dataSet, k)

clusterChanged=TruewhileclusterChanged:

clusterChanged=Falsefor i in range(m):#for each data point assign it to the closest centroid

minDist =inf

minIndex= -1

for j inrange(k):

distJI=distMeas(centroids[j,:],dataSet[i,:])if distJI

minDist= distJI; minIndex =jif clusterAssment[i,0] !=minIndex:

clusterChanged=True

clusterAssment[i,:]= minIndex,minDist**2

printcentroidsfor cent in range(k):#recalculate centroids

ptsInClust = dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]#get all the point in this cluster

centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean

returncentroids, clusterAssmentdefshow(dataSet, k, centroids, clusterAssment):from matplotlib importpyplot as plt

numSamples, dim=dataSet.shape

mark= ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '

markIndex=int(clusterAssment[i, 0])

plt.plot(dataSet[i, 0], dataSet[i,1], mark[markIndex])

mark= ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '

plt.plot(centroids[i, 0], centroids[i,1], mark[i], markersize = 12)

plt.show()defmain():

dataMat= mat(loadDataSet('testSet.txt'))

myCentroids, clustAssing= kMeans(dataMat,4)printmyCentroids

show(dataMat,4, myCentroids, clustAssing)if __name__ == '__main__':

main()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值