Create test.xtx

This commit is contained in:
那伊抹微笑
2017-04-08 13:11:22 +08:00
committed by GitHub
parent 3b850216ec
commit 926009ec68

View File

@@ -0,0 +1,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]]