1. C++实现
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <ctime> using namespace std; const int k = 3; const int dims = 4; const int dataNum = 150; typedef vector<double> Tuple; void doKmeans(vector<Tuple>& tuples); void assignTuples(vector<Tuple> clusters[],vector<Tuple> tuples,Tuple means[]); double getDist(const Tuple& t1, const Tuple& t2); double getVal(vector<Tuple> clusters[], Tuple means[]); Tuple updateMeans(const vector<Tuple>& cluster_i); void print(vector<Tuple> clustes[]); int main() { char filename[] = "bezdekIris.data"; fstream file(filename); //打开存放样本数据的文件 if (!file) { cout << "Cannot open the file" << endl; return 0; } vector<Tuple> tuples; int pos = 0; while (!file.eof()) { string str; getline(file,str); stringstream ss(str); Tuple tuple(dims+1,0); tuple[0] = pos + 1; for (int i = 1; i <= dims; i++) ss >> tuple[i]; tuples.push_back(tuple); pos++; } // doKmeans(tuples); system("pause"); return 0; } void doKmeans(vector<Tuple>& tuples) { cout << "初始化......" << endl; //初始化k个聚类中心 vector<Tuple> clusters[k]; Tuple means[k]; srand((unsigned)time(NULL)); for (int i = 0; i < k; i++) { int temp = rand()%tuples.size(); means[i] = tuples[temp]; } //将样本分配到与其最近的聚类中心 assignTuples(clusters,tuples,means); //计算初始整体误差平方和 double newVal = getVal(clusters,means); double oldVal = -1; int t = 0; while ((abs(newVal - oldVal)) > 1) { cout << "开始第" << t + 1 << "次迭代......" << endl; cout << "更新聚类中心..." << endl; for (int i = 0; i < k; i++) means[i] = updateMeans(clusters[i]); cout << "计算新的整体误差平方和..." << endl; oldVal = newVal; newVal = getVal(clusters,means); } print(clusters); } void assignTuples(vector<Tuple> clusters[], vector<Tuple> tuples,Tuple means[]) { for (int i = 0; i < tuples.size(); i++) { int label = 0; double dist = getDist(tuples[i],means[0]); for (int j = 1; j < k; j++) { double temp = getDist(tuples[i],means[j]); if (temp < dist) { dist = temp; label = j; } } clusters[label].push_back(tuples[i]); } } double getDist(const Tuple& t1, const Tuple& t2) { double sum = 0; for (int i = 1; i <= dims; i++) sum += (t1[i] - t2[i]) * ((t1[i] - t2[i])); return sum; } double getVal(vector<Tuple> clusters[], Tuple means[]) { double val = 0; for (int i = 0; i < k; i++) { vector<Tuple> t = clusters[i]; for (int j = 0; j < t.size(); j++) val += getDist(t[j],means[i]); } return val; } Tuple updateMeans(const vector<Tuple>& cluster_i) { Tuple t(dims+1,0); for (int i = 0; i < cluster_i.size(); i++) for (int j = 1; j <= dims; j++) t[j] += cluster_i[i][j]; for (int i = 1; i <= dims; i++) t[i] /= cluster_i.size(); return t; } void print(vector<Tuple> clustes[]) { for (int i = 0; i < k; i++) { cout << "第" << i+1 << "簇:" << endl; vector<Tuple> t = clustes[i]; for (int j = 0; j < t.size(); j++) { for (int d = 0; d <= dims; d++) cout << t[j][d] << " "; cout << endl; } } }
Python实现:
(1)kmeans.py
from numpy import * import pdb import matplotlib.pyplot as plt def createCenter(dataSet,k): n = shape(dataSet)[0] d = shape(dataSet)[1] centroids = zeros((k,d)) for i in range(k): c = int(random.uniform(0,n-1)) #浮点数 centroids[i,:] = dataSet[c,:] return centroids def getDist(vecA,vecB): return sqrt(sum(power(vecA - vecB,2))) def kmeans(dataSet, k): n = shape(dataSet)[0] clusterAssment = mat(zeros((n,2))) centroids = createCenter(dataSet,k) clusterChnaged = True while clusterChnaged: clusterChnaged = False for i in range(n): minDist = inf minIndex = -1 for j in range(k): distJI = getDist(dataSet[i,:],centroids[j,:]) if distJI < minDist: minDist = distJI minIndex = j if clusterAssment[i,0] != minIndex: #收敛条件:分配结果不再变化 clusterChnaged = True clusterAssment[i,:] = minIndex,minDist**2 #更新质心的位置 for i in range(k): ptsdataSet = dataSet[nonzero(clusterAssment[:,0].A == i)[0]] centroids[i,:] = mean(ptsdataSet,axis = 0) #沿矩阵的列方向进行矩阵计算 return centroids,clusterAssment def print_result(dataSet,k,centroids,clusterAssment): n,d = dataSet.shape if d !=2: print "Cannot draw!" return 1 mark = ['or', 'ob', 'og', 'ok', '^r', '+r', 'sr', 'dr', '<r', 'pr'] if k > len(mark): print "Sorry your k is too large" return 1 for i in range(n): markIndex = int(clusterAssment[i,0]) plt.plot(dataSet[i, 0],dataSet[i, 1],mark[markIndex]) mark = ['Dr', 'Db', 'Dg', 'Dk', '^b', '+b', 'sb', 'db', '<b', 'pb'] # draw the centroids for i in range(k): plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize = 12) plt.show()
from numpy import * import matplotlib.pyplot as plt import kmeans dataSet = [] file = open('E:\\ZForWorks\\MLPython\\kmeansP\\testSet.txt') for line in file.readlines(): strline = line.strip().split('\t') sline = map(float,strline) dataSet.append(sline) dataSet = mat(dataSet) k = 4 kcentroids, clusterAssment = kmeans.kmeans(dataSet,k) kmeans.print_result(dataSet,k,kcentroids,clusterAssment)
结果:
print_result只针对二维的样本数据
测试数据:
1.658985 4.285136
-3.453687 3.424321
4.838138 -1.151539
-5.379713 -3.362104
0.972564 2.924086
-3.567919 1.531611
0.450614 -3.302219
-3.487105 -1.724432
2.668759 1.594842
-3.156485 3.191137
3.165506 -3.999838
-2.786837 -3.099354
4.208187 2.984927
-2.123337 2.943366
0.704199 -0.479481
-0.392370 -3.963704
2.831667 1.574018
-0.790153 3.343144
2.943496 -3.357075
-3.195883 -2.283926
2.336445 2.875106
-1.786345 2.554248
2.190101 -1.906020
-3.403367 -2.778288
1.778124 3.880832
-1.688346 2.230267
2.592976 -2.054368
-4.007257 -3.207066
2.257734 3.387564
-2.679011 0.785119
0.939512 -4.023563
-3.674424 -2.261084
2.046259 2.735279
-3.189470 1.780269
4.372646 -0.822248
-2.579316 -3.497576
1.889034 5.190400
-0.798747 2.185588
2.836520 -2.658556
-3.837877 -3.253815
2.096701 3.886007
-2.709034 2.923887
3.367037 -3.184789
-2.121479 -4.232586
2.329546 3.179764
-3.284816 3.273099
3.091414 -3.815232
-3.762093 -2.432191
3.542056 2.778832
-1.736822 4.241041
2.127073 -2.983680
-4.323818 -3.938116
3.792121 5.135768
-4.786473 3.358547
2.624081 -3.260715
-4.009299 -2.978115
2.493525 1.963710
-2.513661 2.642162
1.864375 -3.176309
-3.171184 -3.572452
2.894220 2.489128
-2.562539 2.884438
3.491078 -3.947487
-2.565729 -2.012114
3.332948 3.983102
-1.616805 3.573188
2.280615 -2.559444
-2.651229 -3.103198
2.321395 3.154987
-1.685703 2.939697
3.031012 -3.620252
-4.599622 -2.185829
4.196223 1.126677
-2.133863 3.093686
4.668892 -2.562705
-2.793241 -2.149706
2.884105 3.043438
-2.967647 2.848696
4.479332 -1.764772
-4.905566 -2.911070