【机器学习算法-python实现】K-means无监督学习实现分类

来源:互联网 发布:桌面透明软件下载 编辑:程序博客网 时间:2024/06/14 19:23

1.背景

        无监督学习的定义就不多说了,不懂得可以google。因为项目需要,需要进行无监督的分类学习。
        K-means里面的K指的是将数据分成的份数,基本上用的就是算距离的方法。
        大致的思路就是给定一个矩阵,假设K的值是2,也就是分成两个部分,那么我们首先确定两个质心。一开始是找矩阵每一列的最大值max,最小值min,算出range=max-min,然后设质心就是min+range*random。之后在逐渐递归跟进,其实要想明白还是要跟一遍代码,自己每一步都输出一下看看跟自己想象的是否一样。
(顺便吐槽一下,网上好多人在写文章的事后拿了书上的代码就粘贴上,也不管能不能用,博主改了一下午才改好。。。,各种bug)

2.代码     

'''@author: hakuri'''from numpy import *import matplotlib.pyplot as pltdef loadDataSet(fileName):      #general function to parse tab -delimited floats    dataMat = []                #assume last column is target value    fr = open(fileName)    for line in fr.readlines():        curLine = line.strip().split('\t')        fltLine = map(float,curLine) #map all elements to float()        dataMat.append(fltLine)    return dataMatdef distEclud(vecA, vecB):    return sqrt(sum(power(vecA - vecB, 2))) #la.norm(vecA-vecB)def randCent(dataSet, k):    n = shape(dataSet)[1]    centroids = mat(zeros((k,n)))#create centroid mat    for j in range(n):#create random cluster centers, within bounds of each dimension        minJ = min(array(dataSet)[:,j])                rangeJ = float(max(array(dataSet)[:,j]) - minJ)        centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))    return centroidsdef 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 = True    while clusterChanged:        clusterChanged = False        for i in range(m):#for each data point assign it to the closest centroid            minDist = inf; minIndex = -1            for j in range(k):                distJI = distMeas(array(centroids)[j,:],array(dataSet)[i,:])                if distJI < minDist:                    minDist = distJI; minIndex = j            if clusterAssment[i,0] != minIndex: clusterChanged = True            clusterAssment[i,:] = minIndex,minDist**2        print centroids#         print nonzero(array(clusterAssment)[:,0]        for cent in range(k):#recalculate centroids                ptsInClust = dataSet[nonzero(array(clusterAssment)[:,0]==cent)[0][0]]#get all the point in this cluster                                centroids[cent,:] = mean(ptsInClust, axis=0) #assign centroid to mean     id=nonzero(array(clusterAssment)[:,0]==cent)[0]     return centroids, clusterAssment,iddef plotBestFit(dataSet,id,centroids):           dataArr = array(dataSet)    cent=array(centroids)    n = shape(dataArr)[0]     n1=shape(cent)[0]    xcord1 = []; ycord1 = []    xcord2 = []; ycord2 = []    xcord3=[];ycord3=[]    j=0    for i in range(n):        if j in id:            xcord1.append(dataArr[i,0]); ycord1.append(dataArr[i,1])        else:            xcord2.append(dataArr[i,0]); ycord2.append(dataArr[i,1])        j=j+1     for k in range(n1):          xcord3.append(cent[k,0]);ycord3.append(cent[k,1])                 fig = plt.figure()    ax = fig.add_subplot(111)    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')    ax.scatter(xcord2, ycord2, s=30, c='green')    ax.scatter(xcord3, ycord3, s=50, c='black')    plt.xlabel('X1'); plt.ylabel('X2');    plt.show()    if __name__=='__main__':    dataSet=loadDataSet('/Users/hakuri/Desktop/testSet.txt')# #     print randCent(dataSet,2)#      print dataSet#      #      print  kMeans(dataSet,2)    a=[]    b=[]    a, b,id=kMeans(dataSet,2)    plotBestFit(dataSet,id,a)                  

用的时候直接看最后的main,dataSet是数据集输入,我会在下载地址提供给大家。
kmeans函数第一个参数是输入矩阵、第二个是K的值,也就是分几份。
plotBestFit是画图函数,需要加plot库,而且目前只支持二维且K=2的情况。

3.效果图

      里面黑色的大点是两个质心,怎么样,效果还可以吧!大笑测试的时候一定要多用一点数据才会明显。



4.下载地址


     我的github地址https://github.com/jimenbian,喜欢就点个starO(∩_∩)O哈!
     点我下载



/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



3 0