请选择 进入手机版 | 继续访问电脑版

Hello Mat

 找回密码
 立即注册
查看: 7496|回复: 0

K均值Kmeans聚类算法

[复制链接]

1288

主题

1514

帖子

90

金钱

管理员

Rank: 9Rank: 9Rank: 9

积分
22589
发表于 2017-4-8 20:15:59 | 显示全部楼层 |阅读模式
Kmeans聚类算法——K均值聚类算法
百度网盘链接:
视频链接:http://pan.baidu.com/s/1jIwYfky
具体链接在halcom.cn论坛,联系人QQ:3283892722
该论坛是一个学习交流平台,我会逐一的和大家分享学习。
欢迎大家录制视频,并提交给我,我来设置视频,你可在论坛进行打赏分享。
视频专用播放器:http://halcom.cn/forum.php?mod=viewthread&tid=258&extra=page%3D1

使用环境:Win7-32bit-Anaconda2-4.3.1-Windows-x86.exe具体的代码如下:Kmeans_function.py子函数文件:
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat Apr 08 22:19:29 2017

  4. @author: ysw
  5. """
  6. from numpy import *  
  7. #import time
  8. import matplotlib.pyplot as plt

  9. # calculate Euclidean distance  
  10. def euclDistance(vector1, vector2):  
  11.     return sqrt(sum(power(vector2 - vector1, 2)))  

  12. # init centroids with random samples  
  13. def initCentroids(dataSet, k):  
  14.     numSamples, dim = dataSet.shape  
  15.     centroids = zeros((k, dim))  
  16.     for i in range(k):  
  17.         index = int(random.uniform(0, numSamples))  
  18.         centroids[i, :] = dataSet[index, :]  
  19.     return centroids  
  20.   
  21. # k-means cluster  
  22. def kmeans(dataSet, k):  
  23.     numSamples = dataSet.shape[0]  
  24.     # first column stores which cluster this sample belongs to,  
  25.     # second column stores the error between this sample and its centroid  
  26.     clusterAssment = mat(zeros((numSamples, 2)))  
  27.     clusterChanged = True  
  28.   
  29.     ## step 1: init centroids  
  30.     centroids = initCentroids(dataSet, k)  
  31.   
  32.     while clusterChanged:  
  33.         clusterChanged = False  
  34.         ## for each sample  
  35.         for i in xrange(numSamples):  
  36.             minDist  = 100000000.0  
  37.             minIndex = 0  
  38.             ## for each centroid  
  39.             ## step 2: find the centroid who is closest  
  40.             for j in range(k):  
  41.                 distance = euclDistance(centroids[j, :], dataSet[i, :])  
  42.                 if distance < minDist:  
  43.                     minDist  = distance  
  44.                     minIndex = j  
  45.               
  46.             ## step 3: update its cluster  
  47.             if clusterAssment[i, 0] != minIndex:  
  48.                 clusterChanged = True  
  49.                 clusterAssment[i, :] = minIndex, minDist**2  
  50.   
  51.         ## step 4: update centroids  
  52.         for j in range(k):  
  53.             pointsInCluster = dataSet[nonzero(clusterAssment[:, 0].A == j)[0]]  
  54.             centroids[j, :] = mean(pointsInCluster, axis = 0)  
  55.   
  56.     print 'Congratulations, cluster complete!'  
  57.     return centroids, clusterAssment  
  58.   
  59. # show your cluster only available with 2-D data  
  60. def showCluster(dataSet, k, centroids, clusterAssment):  
  61.     numSamples, dim = dataSet.shape  
  62.     if dim != 2:  
  63.         print "Sorry! I can not draw because the dimension of your data is not 2!"  
  64.         return 1  
  65.   
  66.     mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr']  
  67.     if k > len(mark):  
  68.         print "Sorry! Your k is too large!"  
  69.         return 1  
  70.   
  71.     # draw all samples  
  72.     for i in xrange(numSamples):  
  73.         markIndex = int(clusterAssment[i, 0])  
  74.         plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex])  
  75.   
  76.     mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb']  
  77.     # draw the centroids  
  78.     for i in range(k):  
  79.         plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12)  
  80.   
  81.     plt.show()  
复制代码
Kmeans_main.py主函数程序:
  1. from numpy import *  
  2. #import time
  3. #import matplotlib.pyplot as plt
  4. import Kmeans_function

  5. ## step 1: load data  
  6. print "step 1: load data..."  
  7. dataSet = []  
  8. fileIn = open(r'C:\Users\ysw\Desktop\Python(x,y)2.7.10\testSet.txt')  
  9. for line in fileIn.readlines():  
  10.     lineArr = line.strip().split()  
  11.     dataSet.append([float(lineArr[0]), float(lineArr[1])])  
  12.   
  13. ## step 2: clustering...  
  14. print "step 2: clustering..."  
  15. dataSet = mat(dataSet)  
  16. k = 4
  17. centroids, clusterAssment = Kmeans_function.kmeans(dataSet, k)  

  18. ## step 3: show the result  
  19. print "step 3: show the result..."  
  20. Kmeans_function.showCluster(dataSet, k, centroids, clusterAssment)  
复制代码


参考链接:http://blog.csdn.net/zouxy09/article/details/17589329
http://halcom.cn/forum.php?mod=viewthread&tid=2770&extra=



本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
算法QQ  3283892722
群智能算法链接http://halcom.cn/forum.php?mod=forumdisplay&fid=73
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Python|Opencv|MATLAB|Halcom.cn ( 蜀ICP备16027072号 )

GMT+8, 2024-3-29 20:39 , Processed in 0.230777 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表