机器学习:KMeans学习笔记
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from numpy import *
def loaddataSet(fileName):
file=open(fileName)
dataMat=[]
for line in file.readlines():
curLine=line.strip().split('\t')
floatLine=map(float,curLine)//这里使用的是map函数直接把数据转化成为float类型
dataMat.append(floatLine)
return dataMat
def distEclud(point1,point2)://pwer(x,2)计算x的平方
return sqrt(sum(power(point1-point2,2)))
//随机的产生中心点
def createRandCenter(dataSet,k):
n=shape(dataSet)[1]
centerPoint=mat(zeros((k,n)))//需要使用相乘的都定义成为矩阵
for i in xrange(n)://这里在给赋值的时候是直接对每列数据操作
minData=min(dataSet[:,i])
maxData=max(dataSet[:,i])
skipNum=float(maxData-minData)
centerPoint[:,i]=minData+skipNum*random.rand(k,1)
return centerPoint
//lmeans函数,找出当前的每一个点距离centor中的哪个点在最近
def kmeans(dataSet,k,distMesns=distEclud,createCenter=createRandCenter):
m=shape(dataSet)[0]
clusterAssment=mat(zeros((m,2)))//第一位表示当前点属于哪个center,第二个表示距离大小
centorPoint=createCenter(dataSet,k)//中心点
clusteredChanged=True
while clusteredChanged://直到不再发生改变
clusteredChanged=False
for i in xrange(m):
minDist=inf;minIndex=-1
for j in xrange(k):
distij=distMesns(dataSet[i,:],centorPoint[j,:])
if distij<minDist:
minDist=distij
minIndex=j
if clusterAssment[i,0]!=minIndex:clusteredChanged=True//判断计算得到最近点center是否在上次一迭代已经获得了
clusterAssment[i,:]=minIndex,minDist**2//否则就更新当前点隶属的center
print centorPoint
for cent in xrange(k)://对每一个簇再继续进行迭代
ptsInClust=dataSet[nonzero(clusterAssment[:,0].A==cent)[0]]//找出属于当前k中心点的点集合,得到一维坐标,表示就是点的集合
centorPoint[cent,:]=mean(ptsInClust,axis=0)
return centorPoint,clusterAssment
import matplotlib.pyplot as plt
def showCluster(dataSet, k, centroids, clusterAssment):
m=shape(dataSet)[0]
print m
mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']
for i in xrange(m)://绘制每个点
center=int(clusterAssment[i,0])
plt.plot(dataSet[i,0],dataSet[i,1],mark[center])
mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']
for i in xrange(k)://绘制中心点
plt.plot(centroids[i,0],centroids[i,1],mark[i],markersize = 12)
plt.show()