Fork me on GitHub

机器学习实战-边学边读python代码(4)

程序2-4 分类器针对约会网站的测试代码(4)

def datingClassTest():
hoRatio = 0.10

//将文件读入内存矩阵
datingDataMat,datingLabels = file2matrix('datingTestSet.txt')

//归一化,请看(3)
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]

//训练样本从第m*hoRatio行开始
numTestVecs = int(m*hoRatio)
errorCount = 0.0

//待预测向量从0开始到m*hoRatio结束
for i in range(numTestVecs):

/*

normMat[i,:] 为取出mormMat的第i+1行,作为待预测的向量

关于normMat[numTestVecs:m,:],为训练样本,取出从i+1行开始的m行,这里m可以大于矩阵的总行数,看下面的例子。

>>> a = zeros((3,3))
>>> a
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> a[1][0]=2
>>> a[2][0]=3
>>> a
array([[ 0., 0., 0.],
[ 2., 0., 0.],
[ 3., 0., 0.]])
>>> a[0:2,:]
array([[ 0., 0., 0.],
[ 2., 0., 0.]])
>>> a[0:4,:]
array([[ 0., 0., 0.],
[ 2., 0., 0.],
[ 3., 0., 0.]])
>>> a[1:4,:]
array([[ 2., 0., 0.],
[ 3., 0., 0.]])

datingLabels[numTestVecs:m] 为训练样本的标签向量,用于预测待预测向量,

取出待预测向量离训练样本最小的3个标签,

*/
classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],
datingLabels[numTestVecs:m],3)

//检查预测值和实际值是否相符合
print "the classifier came back with: %d, the real answer is: %d"
% (classifierResult, datingLabels[i])

if (classifierResult != datingLabels[i]): errorCount += 1.0
print "the total error rate is: %f" % (errorCount/float(numTestVecs))

posted @ 2015-11-26 22:29  HarlanC  阅读(439)  评论(0编辑  收藏  举报