读懂《机器学习实战》代码—K-近邻算法改进约会网站配对效果

来源:互联网 发布:软件测试活动周期 编辑:程序博客网 时间:2024/05/15 00:36

从上一篇文章大概了解了K-近邻算法的原理,并实现了分类函数:

#inX为用于分类的输入向量  #dataSet为输入的训练样本集  #lables为标签向量  #参数k表示用于选择最近邻居的数目  def classify0(inX,dataSet,lables,k)

接下来,通过人物特点将约会者分到不同的类型中,约会数据集格式为


第一行表示每年的飞行里程数,第二行表示玩视频游戏所耗时间比,第三行表示每周消费的冰淇淋公升数,最后一行表示约会对象等级,《机器学习实战》中将读取文件数据封装到函数中:

##########################将文件内容转化成所需的矩阵格式#########################def file2matrix(filename):    #获得文件内容    fileReader = open(filename)    #分行获取文件内容    arrayOfLines = fileReader.readlines()    #获取文件总行数    numberOfLines = len(arrayOfLines)    #创建一个零填充的numpy矩阵    returnMat = zeros((numberOfLines,3))    #    classLabelVector = []    index = 0    for line in arrayOfLines:        #将每一行回车符截取掉,去掉前后空格        # strip() 方法用于移除字符串头尾指定的字符(默认为空格)        #strip()方法语法:str.strip([chars]);        #参数chars -- 移除字符串头尾指定的字符。        line = line.strip()        #split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串        #split()方法语法:str.split(str="", num=string.count(str)).        #参数:str -- 分隔符,默认为空格。num -- 分割次数。        #'\t'代表一个tab字符        listFromLine = line.split('\t')        #取出数据的前三个元素放入numpy矩阵中        returnMat[index,:] = listFromLine[0:3]        #运用-1索引取出最后一列的特征元素        classLabelVector.append(int(listFromLine[-1]))        index +=1    return returnMat,classLabelVector


由于三个人物特性具有相同的权重,如果单纯用原始数据进行欧氏距离的计算,明显每年的飞行里程数这一项数据会造成严重的影响,其余两项的作用会被明显弱化,所以要先将数据归一化,可用等式newValue = (value-minValue)/(maxValue-minValue)将数据归一化到0-1区间

########################输入参数为原始数据集#返回参数为normDataset归一化数据集,ranges归一化间距,minVals各项特性中的最小值#######################def autoNorm(dataset):    #求出数据集中的最大值最小值,dataset.min(0)或max(0)中的参数0可以使函数从列中获得最小(大)值,而不是从行中获得最小(大)值    minVals = dataset.min(0)    maxVals = dataset.max(0)    ranges = maxVals - minVals    normDataset = zeros(shape(dataset))    m = dataset.shape[0]    #minVals与ranges都是1*3的矩阵,通过tile函数被扩展为m*3的矩阵,这就是tile函数的作用    normDataset = dataset - tile(minVals,(m,1))    normDataset = normDataset/tile(ranges,(m,1))    return normDataset,ranges,minVals

将数据的分布可视化出来



可视化的程序

#获取figure对象fig = plt.figure()#指定图像所在的子视图位置,add_subplot(nmi),意思为在fig视图被划分为n*m个子视图,i指定接下来的图像放在哪一个位置ax = fig.add_subplot(111)l=datingDataMat.shape[0]#存储第一类,第二类,第三类的数组X1=[]Y1=[]X2=[]Y2=[]X3=[]Y3=[]for i in range(l):    if datingLabels[i]==1:        X1.append(datingDataMat[i,1]);Y1.append(datingDataMat[i,2])    elif datingLabels[i]==2:        X2.append(datingDataMat[i,1]);Y2.append(datingDataMat[i,2])    else:        X3.append(datingDataMat[i,1]);Y3.append(datingDataMat[i,2])#画出散点图,坐标分别为datingDataMat的第一列数据与第二列数据,c='color'指定点的颜色type1=ax.scatter(X1,Y1,c='red')type2=ax.scatter(X2,Y2,c='green')type3=ax.scatter(X3,Y3,c='blue')ax.axis([-2,25,-0.2,2.0])ax.legend([type1, type2, type3], ["Did Not Like", "Liked in Small Doses", "Liked in Large Doses"], loc=2)plt.xlabel('Percentage of Time Spent Playing Video Games')plt.ylabel('Liters of Ice Cream Consumed Per Week')plt.show()

然后写测试程序

#可适当调整k值来调整准确率def datingClassTest():    #取出10%的数据作为测试样例    hoRatio = 0.10        k = 4    #载入数据    datingDataMat,datingLabels = file2matrix('F:\PythonProject\datingTestSet2.txt')           #进行数据归一化    normMat, ranges, minVals = autoNorm(datingDataMat)    m = normMat.shape[0]    numTestVecs = int(m*hoRatio)    errorCount = 0.0    for i in range(numTestVecs):        #输入参数:normMat[i,:]为测试样例,表示归一化后的第i行数据        #       normMat[numTestVecs:m,:]为训练样本数据,样本数量为(m-numTestVecs)个        #       datingLabels[numTestVecs:m]为训练样本对应的类型标签        #       k为k-近邻的取值        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],k)        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))    print "the total error times is:"+str(errorCount)

当k取4,取10%的数据作为测试样本时,可得到3%的失误率


完整代码:

from numpy import * import matplotlibimport matplotlib.pyplot as pltimport operatorfrom os import listdirdef classify0(inX, dataSet, labels, k):    dataSetSize = dataSet.shape[0]    diffMat = tile(inX, (dataSetSize,1)) - dataSet    sqDiffMat = diffMat**2    sqDistances = sqDiffMat.sum(axis=1)    distances = sqDistances**0.5    sortedDistIndicies = distances.argsort()         classCount={}              for i in range(k):        voteIlabel = labels[sortedDistIndicies[i]]        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)    return sortedClassCount[0][0]    ##########################将文件内容转化成所需的矩阵格式#########################def file2matrix(filename):    #获得文件内容    fileReader = open(filename)    #分行获取文件内容    arrayOfLines = fileReader.readlines()    #获取文件总行数    numberOfLines = len(arrayOfLines)    #创建一个零填充的numpy矩阵    returnMat = zeros((numberOfLines,3))    #    classLabelVector = []    index = 0    for line in arrayOfLines:        #将每一行回车符截取掉,去掉前后空格        # strip() 方法用于移除字符串头尾指定的字符(默认为空格)        #strip()方法语法:str.strip([chars]);        #参数chars -- 移除字符串头尾指定的字符。        line = line.strip()        #split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串        #split()方法语法:str.split(str="", num=string.count(str)).        #参数:str -- 分隔符,默认为空格。num -- 分割次数。        #'\t'代表一个tab字符        listFromLine = line.split('\t')        #取出数据的前三个元素放入numpy矩阵中        returnMat[index,:] = listFromLine[0:3]        #运用-1索引取出最后一列的特征元素        classLabelVector.append(int(listFromLine[-1]))        index +=1    return returnMat,classLabelVector########################输入参数为原始数据集#返回参数为normDataset归一化数据集,ranges归一化间距,minVals各项特性中的最小值#######################def autoNorm(dataset):    #求出数据集中的最大值最小值,dataset.min(0)或max(0)中的参数0可以使函数从列中获得最小(大)值,而不是从行中获得最小(大)值    minVals = dataset.min(0)    maxVals = dataset.max(0)    ranges = maxVals - minVals    normDataset = zeros(shape(dataset))    m = dataset.shape[0]    #minVals与ranges都是1*3的矩阵,通过tile函数被扩展为m*3的矩阵,这就是tile函数的作用    normDataset = dataset - tile(minVals,(m,1))    normDataset = normDataset/tile(ranges,(m,1))    return normDataset,ranges,minVals    #可适当调整k值来调整准确率def datingClassTest():    #取出10%的数据作为测试样例    hoRatio = 0.10        k = 4    #载入数据    datingDataMat,datingLabels = file2matrix('F:\PythonProject\datingTestSet2.txt')           #进行数据归一化    normMat, ranges, minVals = autoNorm(datingDataMat)    m = normMat.shape[0]    numTestVecs = int(m*hoRatio)    errorCount = 0.0    for i in range(numTestVecs):        #输入参数:normMat[i,:]为测试样例,表示归一化后的第i行数据        #       normMat[numTestVecs:m,:]为训练样本数据,样本数量为(m-numTestVecs)个        #       datingLabels[numTestVecs:m]为训练样本对应的类型标签        #       k为k-近邻的取值        classifierResult = classify0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],k)        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))    print "the total error times is:"+str(errorCount)################################画图################################获取figure对象fig = plt.figure()#指定图像所在的子视图位置,add_subplot(nmi),意思为在fig视图被划分为n*m个子视图,i指定接下来的图像放在哪一个位置ax = fig.add_subplot(111)l=datingDataMat.shape[0]#存储第一类,第二类,第三类的数组X1=[]Y1=[]X2=[]Y2=[]X3=[]Y3=[]for i in range(l):    if datingLabels[i]==1:        X1.append(datingDataMat[i,1]);Y1.append(datingDataMat[i,2])    elif datingLabels[i]==2:        X2.append(datingDataMat[i,1]);Y2.append(datingDataMat[i,2])    else:        X3.append(datingDataMat[i,1]);Y3.append(datingDataMat[i,2])#画出散点图,坐标分别为datingDataMat的第一列数据与第二列数据,c='color'指定点的颜色type1=ax.scatter(X1,Y1,c='red')type2=ax.scatter(X2,Y2,c='green')type3=ax.scatter(X3,Y3,c='blue')ax.axis([-2,25,-0.2,2.0])ax.legend([type1, type2, type3], ["Did Not Like", "Liked in Small Doses", "Liked in Large Doses"], loc=2)plt.xlabel('Percentage of Time Spent Playing Video Games')plt.ylabel('Liters of Ice Cream Consumed Per Week')plt.show()#测试datingClassTest()

datintTestSet2.txt文件下载:http://download.csdn.net/detail/u013457382/9467348

0 0
原创粉丝点击