python 实现kmeans聚类
编程中在做数值相等判断的时候,直接使用==判断并不可靠。实际上经过运算后的两个值(浮点型)并不可能完全一致,可能会因为小数点后的些许差异导致判断为false。
比如:
|
1
|
print 1e-5 == 1e-6 //这肯定是false,但是实际这两个值可以看作近似相等。 |
在kmeans中判断是否结束循环,就是判断重新计算的聚类中心点是否和原聚类中心点一致,实际上新旧聚类中心点之间会有一个可允许的误差。修改代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import numpy as npdef kmeans(data, n, m, k): rarray = np.random.random(size=k) rarray = np.floor(rarray*n) rarray.astype(int) cls = np.zeros([1,n],np.int) center = np.take(data,rarray) pcenter = np.zeros([k,m]) end = True while end: for i in xrange(n): tmp = data[i] - center tmp = np.square(tmp) tmp = np.sum(tmp,axis=1) cls[i] = np.argmin(tmp) center = np.zeros([k,m]) count = np.zeros([1,k],np.int) for i in xrange(n): center[cls[i]]=center[cls[i]]+data[i] count[cls[i]]= count[cls[i]]+1 if np.sum(center/count - pcenter) <= 1e-4: end = False pcenter = center/count |
浙公网安备 33010602011771号