forked from apachecn/ailearning
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.txt
More file actions
43 lines (38 loc) · 1.4 KB
/
test.txt
File metadata and controls
43 lines (38 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# import
>>> import kMeans
>>> from numpy import *
# 从文本中构建矩阵,加载测试数据集
>>> datMat=mat(kMeans.loadDataSet('testSet.txt'))
# 测试 randCent() 函数是否正常运行。
# 首先,先看一下矩阵中的最大值与最小值
>>> min(datMat[:,0])
matrix([[-5.379713]])
>>> min(datMat[:,1])
matrix([[-4.232586]])
>>> max(datMat[:,1])
matrix([[ 5.1904]])
>>> max(datMat[:,0])
matrix([[ 4.838138]])
# 然后看看 randCent() 函数能否生成 min 到 max 之间的值
>>> kMeans.randCent(datMat, 2)
matrix([[-3.59997714, -1.43558065],
[-3.03744979, 4.35541488]])
# 最后测试一下距离计算方法
>>> kMeans.distEclud(datMat[0], datMat[1])
5.184632816681332
# 该算法会创建k个质心,然后将每个点分配到最近的质心,再重新计算质心。
# 这个过程重复数次,知道数据点的簇分配结果不再改变位置。
# 运行结果(多次运行结果可能会不一样,可以试试,原因为随机质心的影响,但总的结果是对的, 因为数据足够相似)
>>> myCentroids, clustAssing = kMeans.kMeans(datMat, 4)
[[ 0.15357605 -0.94962877]
[ 3.3593825 1.05965957]
[-2.41900657 3.30513371]
[-2.80505526 -3.73280289]]
[[ 2.35622556 -3.02056425]
[ 2.95373358 2.32801413]
[-2.46154315 2.78737555]
[-3.38237045 -2.9473363 ]]
[[ 2.65077367 -2.79019029]
[ 2.6265299 3.10868015]
[-2.46154315 2.78737555]
[-3.53973889 -2.89384326]]