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

xiaoxiao2025-12-02  8

程序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))>>> aarray([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])>>> a[1][0]=2>>> a[2][0]=3>>> aarray([[ 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.0print "the total error rate is: %f" % (errorCount/float(numTestVecs))

转载请注明原文地址: https://www.6miu.com/read-5040239.html

最新回复(0)