《机器学习实战》学习笔记——K-近邻算法(KNN)(二)海伦约会网站匹配实战

来源:互联网 发布:绿色破解软件 编辑:程序博客网 时间:2024/05/18 15:30

《机器学习实战》中KNN算法实例一:关于这个实战的故事背景可以搜索“海伦 约会网站”基本上就可以了解。
这个实验的目的是根据已有的海伦整理出来的约会对象的资料和海伦对约会对象的评价,构造分类器,使对新的约会对象进行自动分类(不喜欢的人,魅力一般的人,极具魅力的人)。

数据准备

海伦准备的约会数据datingTestSet.txt,我已上传github
我们可以先看一下截图:
这里写图片描述
文件一共有四列,每一行为一个约会对象的信息(“每年获得的飞行常客里程数”,“玩视频游戏所消耗的时间百分比”,“每周消费的冰激凌公斤数”),最后一列是海伦对他的评价。
那么得到数据后,我们从下面几个方面来处理数据,帮助海伦来预测约会对象是否合适:
1.先将文本的数据文件转换为NumPy的解析程序
2.分析数据,将数据可视化
3.准备数据:归一化数值
4.测试分类器,计算准确率
5.使用算法,对新的约会对象进行预测

将文本的数据文件转换为NumPy的解析程序

def file2matrix(filename):    fr = open(filename)    arrayOLines = fr.readlines()    numberofLines = len(arrayOLines) #计算文件总行数    returnMat = np.zeros((numberofLines,3))     #np.zeros((m,n)) 创建m行,n列的由0填充的矩阵    classLabelVector = []    #记录海伦对每一个约会对象的评价    index = 0    for line in arrayOLines:        line = line.strip()        listFromLine = line.split("\t")        returnMat[index,:] = listFromLine[0:3]        if listFromLine[-1] == "didntLike":            classLabelVector.append(int(1))        elif listFromLine[-1] == "smallDoses":            classLabelVector.append(int(2))        elif listFromLine[-1] == "largeDoses":            classLabelVector.append(int(3))        index +=1    return returnMat,classLabelVector

分析数据,将数据可视化

根据数据,我们选用散点图。

#根据上面创建的函数,我们可以调用并得到数据矩阵datingDataMat,datingLabels = file2matrix("datingTestSet.txt")index = 0index_1 = []index_2 = []index_3 = []for i in datingLabels:    if i == 1:        index_1.append(index)    elif i == 2:        index_2.append(index)    elif i == 3:        index_3.append(index)    index +=1type_1 = datingDataMat[index_1,:]type_2 = datingDataMat[index_2,:]type_3 = datingDataMat[index_3,:]fig = plt.figure()ax = fig.add_subplot(111)type_1 = ax.scatter(type_1[:,1],type_1[:,2],c="red")type_2 = ax.scatter(type_2[:,1],type_2[:,2],c="blue")type_3 = ax.scatter(type_3[:,1],type_3[:,2],c="green")plt.legend((type_1, type_2, type_3), ("didntLike","smallDoses","largeDoses"),loc=4)plt.show()

这里写图片描述

阅读全文
0 0