k均值python_《机器学习实战》之K-均值聚类算法的python实现

《机器学习实战》之K-均值聚类算法的python实现

最近的项目是关于“基于数据挖掘的电路故障分析”,项目基本上都是师兄们在做,我只是在研究关于项目中用到的如下几种算法:二分均值聚类、最近邻分类、基于规则的分类器以及支持向量机。基于项目的保密性(其实也没有什么保密的,但是怕以后老板看到我写的这篇博文,所以,你懂的),这里就不介绍“基于数据挖掘的电路故障分析”的思路了。

废话不多说了,开始正题哈。

基本K-均值聚类算法

基本K均值算法的基本思路为:首先选择K个初始质心(集合中所有点度量值的均值), K值为期望得到簇的个数,大小由用户指定;将每个点指派到最近的质心,点与点之间的距离通过两点对应的度量值差的绝对值进行度量,然后根据指派到簇的点,更新每个簇的质心,重复指派和更新,直到簇不再发生变化,或者满足终止条件。

其伪代码如下:

创建k个点作为初始的质心点(随机选择)

当任意一个点的簇分配结果发生改变时

对数据集中的每一个数据点

对每一个质心

计算质心与数据点的距离

将数据点分配到距离最近的簇

对每一个簇,计算簇中所有点的均值,并将均值作为质心

python实现代码如下:注释基本上写的相当相当详细,由于自己还是python的初学者,觉得注释过多不方便看,还请大家谅解,有错误希望大家指正。

用到的库有numpy和matplotlib,直接通过如下命令安装即可。

pip install numpy

pip install matplotlib

KMeans.py文件

from numpy import *

import time

import matplotlib.pyplot as plt

# calculate Euclidean distance

def euclDistance(vector1, vector2):

return sqrt(sum(power(vector2 - vector1, 2))) #求这两个矩阵的距离,vector1、2均为矩阵

# init centroids with random samples

#在样本集中随机选取k个样本点作为初始质心

def initCentroids(dataSet, k):

numSamples, dim = dataSet.shape #矩阵的行数、列数

centroids = zeros((k, dim)) #感觉要不要你都可以

for i in range(k):

index = int(random.uniform(0, numSamples)) #随机产生一个浮点数,然后将其转化为int型

centroids[i, :] = dataSet[index, :]

return centroids

# k-means cluster

#dataSet为一个矩阵

#k为将dataSet矩阵中的样本分成k个类

def kmeans(dataSet, k):

numSamples = dataSet.shape[0] #读取矩阵dataSet的第一维度的长度,即获得有多少个样本数据

# first column stores which cluster this sample belongs to,

# second column stores the error between this sample and its centroid

clusterAssment = mat(zeros((numSamples, 2))) #得到一个N*2的零矩阵

clusterChanged = True

## step 1: init centroids

centroids = initCentroids(dataSet, k) #在样本集中随机选取k个样本点作为初始质心

while clusterChanged:

clusterChanged = False

## for each sample

for i in range(numSamples): #range

minDist = 100000.0

minIndex = 0

## for each centroid

## step 2: find the centroid who is closest

#计算每个样本点与质点之间的距离,将其归内到距离最小的那一簇

for j in range(k):

distance = euclDistance(centroids[j, :], dataSet[i, :])

if distance < minDist:

minDist = distance

minIndex = j

## step 3: update its cluster

#k个簇里面与第i个样本距离最小的的标号和距离保存在clusterAssment中

#若所有的样本不在变化,则退出while循环

if clusterAssment[i, 0] != minIndex:

clusterChanged = True

clusterAssment[i, :] = minIndex, minDist**2 #两个**表示的是minDist的平方

## step 4: update centroids

for j in range(k):

#clusterAssment[:,0].A==j是找出矩阵clusterAssment中第一列元素中等于j的行的下标,返回的是一个以array的列表,第一个array为等于j的下标

pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]] #将dataSet矩阵中相对应的样本提取出来

centroids[j, :] = mean(pointsInCluster, axis = 0) #计算标注为j的所有样本的平均值

print (‘Congratulations, cluster complete!‘)

return centroids, clusterAssment

# show your cluster only available with 2-D data

#centroids为k个类别,其中保存着每个类别的质心

#clusterAssment为样本的标记,第一列为此样本的类别号,第二列为到此类别质心的距离

def showCluster(dataSet, k, centroids, clusterAssment):

numSamples, dim = dataSet.shape

if dim != 2:

print ("Sorry! I can not draw because the dimension of your data is not 2!")

return 1

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

if k > len(mark):

print ("Sorry! Your k is too large! ")

return 1

# draw all samples

for i in range(numSamples):

markIndex = int(clusterAssment[i, 0]) #为样本指定颜色

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

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

# draw the centroids

for i in range(k):

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

plt.show()

测试文件test.py

from numpy import *

import time

import matplotlib.pyplot as plt

import KMeans

## step 1: load data

print ("step 1: load data..." )

dataSet = [] #列表,用来表示,列表中的每个元素也是一个二维的列表;这个二维列表就是一个样本,样本中包含有我们的属性值和类别号。

#与我们所熟悉的矩阵类似,最终我们将获得N*2的矩阵,

fileIn = open("D:/xuepython/testSet.txt") #是正斜杠

for line in fileIn.readlines():

temp=[]

lineArr = line.strip().split(‘\t‘) #line.strip()把末尾的‘\n‘去掉

temp.append(float(lineArr[0]))

temp.append(float(lineArr[1]))

dataSet.append(temp)

#dataSet.append([float(lineArr[0]), float(lineArr[1])])#上面的三条语句可以有这条语句代替

fileIn.close()

## step 2: clustering...

print ("step 2: clustering..." )

dataSet = mat(dataSet) #mat()函数是Numpy中的库函数,将数组转化为矩阵

k = 4

centroids, clusterAssment = KMeans.kmeans(dataSet, k) #调用KMeans文件中定义的kmeans方法。

## step 3: show the result

print ("step 3: show the result..." )

KMeans.showCluster(dataSet, k, centroids, clusterAssment)

运行结果图如下:

上面是出现的两种聚类的结果。由于基本K均值聚类算法质心选择的随机性,其聚类的结果一般比较随机,一般不会很理想,最终结果往往出现自然簇无法区分的情况,为避免此问题,本文采用二分K均值聚类算法。

二分K-均值聚类的python的实现将在下篇博文给出。

完整代码和测试所用的数据可以在这里获取,还是希望大家从连接获取源码,因为从网页上copy的代码会出现没有缩进的情况,需要大家添加缩进,比较麻烦,当你遇到IndentationError:unindent does not match any outer indentation level这样的错误的时候,就是缩进引起的错误,可以看这篇博文,这篇博文给予了解决方法。

除了参考了《机器学习实战》这本书之外,还参考了如下博客,这篇博客基本上也是参考了《机器学习实战》这本书,在此,感谢作者。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值