kNN_约会网站匹配效果改进

【准备数据】数据处理函数

import numpy as np
import os
def file2matrix(filename):fr = open(filename)arrayOLines = fr.readlines()numberOfLines = len(arrayOLines)returnMat = np.zeros((numberOfLines,3))classLabelVector = []index = 0for line in arrayOLines:line = line.strip()listFromLine = line.split('\t')returnMat[index,:] = listFromLine[0:3]classLabelVector.append(label2int(listFromLine[-1]))index += 1return returnMat,classLabelVectordef label2int(labelName):if labelName == 'didntLike':return 0elif labelName == 'smallDoses':return 1elif labelName == 'largeDoses':return 2datingDataMat,datingLabels = file2matrix('datingTestSet.txt')

【分析数据】绘制数据散点图

import matplotlib
import matplotlib.pyplot as pltdef arrColor(labels):arrColor = []for i in datingLabels:if i == 0:arrColor.append('r')elif i == 1:arrColor.append('y')elif i == 2:arrColor.append('g')  return arrColorfig = plt.figure(figsize=(8,20))
#plt.axis([-1,22,-0.1,1.8])
ax1 = fig.add_subplot(311)
ax1.scatter(datingDataMat[:,0],datingDataMat[:,1],c = arrColor(datingLabels))ax2 = fig.add_subplot(312)
ax2.scatter(datingDataMat[:,1],datingDataMat[:,2],c = arrColor(datingLabels))ax3 = fig.add_subplot(313)
ax3.scatter(datingDataMat[:,0],datingDataMat[:,2],c = arrColor(datingLabels))plt.show()

由数据两两对比的三幅散点图分布可知,取第一列和第二列为x,y轴绘制散点图(图一)时,三种类型的人基本分属于不同的区域。

注:用scatter绘制散点图时,当数据在列表中未分类时,无法按照颜色给出图例。
想要显示图例,需对数据进行分类,然后分别用不同的scatter绘制,则可有不同分类的图例。

import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname='C:/Windows/Fonts/msyh.ttf')def showClassify(datingDataMat,datingLabels,x,y,x_name='',y_name=''):type1_x = []type1_y = []type2_x = []type2_y = []type3_x = []type3_y = []for i in range(len(datingLabels)):if datingLabels[i] == 0:type1_x.append(datingDataMat[i][x])type1_y.append(datingDataMat[i][y])if datingLabels[i] == 1:type2_x.append(datingDataMat[i][x])type2_y.append(datingDataMat[i][y])if datingLabels[i] == 2:type3_x.append(datingDataMat[i][x])type3_y.append(datingDataMat[i][y])fig = plt.figure()plt.xlabel(x_name,fontproperties=myfont)plt.ylabel(y_name,fontproperties=myfont)#plt.title("pythoner.com",fontproperties=myfont)ax = fig.add_subplot(111)type1 = ax.scatter(type1_x,type1_y,c = 'r')type2 = ax.scatter(type2_x,type2_y,c = 'y')type3 = ax.scatter(type3_x,type3_y,c = 'g') ax.legend((type1, type2, type3), (u'不喜欢', u'魅力一般', u'极具魅力'),loc=2,prop=myfont)plt.show()showClassify(datingDataMat,datingLabels,0,1,u'每年获取的飞行常客里程数',u'玩视频游戏所耗时间百分比')

【准备数据】归一化特征值函数

def autoNorm(dataSet):minValues = dataSet.min(0)maxValues = dataSet.max(0)ranges = maxValues - minValuesnormDataSet = np.zeros(np.shape(dataSet))m = dataSet.shape[0]normDataSet = dataSet - np.tile(minValues,(m,1))normDataSet = normDataSet / np.tile(ranges,(m,1))return normDataSet, ranges, minValuesnormMat, ranges, minValues = autoNorm(datingDataMat)
array([[ 0.44832535,  0.39805139,  0.56233353],[ 0.15873259,  0.34195467,  0.98724416],[ 0.28542943,  0.06892523,  0.47449629],..., [ 0.29115949,  0.50910294,  0.51079493],[ 0.52711097,  0.43665451,  0.4290048 ],[ 0.47940793,  0.3768091 ,  0.78571804]])

k-近邻算法

import operator
def classify0(inX, dataSet, labels, k):dataSetSize = dataSet.shape[0]diffMat = np.tile(inX,(dataSetSize,1)) - dataSetsqDiffMat = diffMat**2sqDistances = sqDiffMat.sum(axis=1)distances = sqDistances**0.5sortedDistIndicies = distances.argsort()classCount = {}for i in range(k):voteIlabel = labels[sortedDistIndicies[i]]classCount[voteIlabel] = classCount.get(voteIlabel,0)+1sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)return sortedClassCount[0][0]classify0([ 0.28542943,  0.06892523,  0.47449629],normMat,datingLabels,5)
0

【测试算法】测试错误率函数

def datingClassTest():hoRatio = 0.1datingDataMat,datingLabels = file2matrix('datingTestSet.txt')normMat, ranges, minValues = autoNorm(datingDataMat)m=normMat.shape[0]numTestVecs = int(m*hoRatio)errorCount = 0.0for i in range(numTestVecs):classifierResult = classify0(normMat[i,:],normMat[numTestVecs:,:],datingLabels[numTestVecs:],5)if(classifierResult != datingLabels[i]):errorCount += 1.0print("the total error rate is: %f" % (errorCount/float(numTestVecs)))datingClassTest()
the total error rate is: 0.040000

【使用算法】采集数据并输出预测结果

def classifyPerson():resultList = ['not at all','in small doses','in large doses']percentTats = float(input("percentage of thime spent playing video games?"))ffMiles = float(input("frequent flier miles earned per year?"))iceCream = float(input("liters of ice cream consumed per year?"))datingDataMat,datingLabels = file2matrix('datingTestSet.txt')normMat, ranges, minValues = autoNorm(datingDataMat)inArr = np.array([ffMiles,percentTats,iceCream])classifierResult = classify0((inArr-minValues)/ranges,normMat,datingLabels,5)print("You will probably like this person:",resultList[classifierResult])classifyPerson()  
percentage of thime spent playing video games?8
frequent flier miles earned per year?40000
liters of ice cream consumed per year?0.95
You will probably like this person: in large doses

kNN_约会网站匹配效果改进实现代码相关推荐

  1. KNN算法改进约会网站匹配效果

    文章目录 实验 一.示例:KNN改进约会网站配对 二.实验过程 1.准备数据:从文本文件中解析数据 2.分析数据:使用Matplotlib创建散点图 3.准备数据:归一化数值 4.测试算法:作为完整程 ...

  2. 机器学习算法(一):k-近邻理论与python实现+经典应用(约会网站匹配、手写识别系统)

    一份算法学习笔记~ 亲爱的朋友,恭喜你点开神秘之门,哈哈哈哈!从这里开始,我们一起学习机器学习的经典算法吧. 这一次的主要内容是机器学习入门算法:k-近邻.理论相当好理解,下面我们正式开始啦! 算法简 ...

  3. 模式识别和机器学习实战-K近邻算法(KNN)- Python实现 - 约会网站配对效果判断和手写数字识别

    文章目录 前言 一. k-近邻算法(KNN) 1.算法介绍 2.举个例子--电影分类 3.步骤描述 4.来了--代码实现 二.实战之约会网站配对效果判断 1.导入数据 2.分析数据 3.数据归一化 4 ...

  4. 机器学习:K-近邻算法(二)约会网站配对效果

    目录 K-近邻算法实战(二):约会网站配对效果判断 实战 1.背景介绍 2.准备数据:数据分类 3.分析数据:数据可视化 4.准备数据:数据归一化 5.测试算法:验证分类器 6.使用算法:构建完整可用 ...

  5. KNN实战 —— 约会网站配对效果判定

    (公众号:落叶归根的猪.获取更多资源干货,交个朋友也可) 二.k-近邻算法实战之约会网站配对效果判定 上一小结学习了简单的k-近邻算法的实现方法,但是这并不是完整的k-近邻算法流程,k-近邻算法的一般 ...

  6. 机器学习 (三) k-近邻算法应用-约会网站匹配系统

    前言 目前一些姻缘网站专门给人介绍对象,也经常有人陷入介绍门中,怎么样来提高准确率降低网站带来的风险呢?其实里面有些推荐算法和匹配算法在里面,今天我们简单介绍其中一种.        大家是否还记得在 ...

  7. 《机器学习实战》个人学习记录笔记(二)———k-近邻算法实战之约会网站配对效果判定

    第二章 k-近邻算法 PS:个人笔记 根据<机器学习实战>这本书,Jack-Cui的博客,以及深度眸的视频进行学习 k-近邻算法的一般流程 ①收集数据:可以使用爬虫进行数据的收集,也可以使 ...

  8. 使用k-近邻算法改进约会网站的配对效果

    2.2 使用k-近邻算法改进约会网站的配对效果 Helen交往过三种类型的人: 不喜欢的人 魅力一般的人 极具魅力的人 示例:在约会网站上使用k-近邻算法 (1)收集数据:提供文本文件: dating ...

  9. k-近邻算法1(kNN)使用kNN算法改进约会网站的配对效果

    最近边看NG老师的机器学习课程和西瓜书,无奈交织着各种数学推导,有些晦涩难懂,看到网上推荐了<machine learning in action>比较适合新手入门, 书中数据和源码在此  ...

最新文章

  1. 应用设计模式进行重构来消除坏味道
  2. 子域名绑定html,DEDE二级域名(多站点)绑定详解
  3. 域名解析跳转到另一个域名_github建立静态网站,域名解析和跳转
  4. Python基础教程:类的property特性
  5. 75-商品服务-品牌分类关联与级联更新
  6. C/C++ OpenCV高斯滤波
  7. Mono源代码学习笔记:Console类(五)
  8. Ionic!用Web技术开发移动应用!
  9. C# 程序启动其他进程程序
  10. [ Python - 6 ] 正则表达式实现计算器功能
  11. Java版小米商城项目简介
  12. Observium Feature分析
  13. YYF根据学生编号查询学生签到状态
  14. 网络协议安全性分析(思维导图word版本)
  15. 外网/公网出口IP查询方法汇总
  16. 某年某月有多少天c语言程序,判断某年某月有多少天(C语言)
  17. 如何开会——高效会议八项原则
  18. 安徽农业大学计算机考研分数线,安徽农业大学考研录取分数线
  19. CA数字证书是什么?
  20. spark分区读写mysql

热门文章

  1. 南通万豪酒店开业;诺瓦瓦克斯任命新任总裁兼CEO | 美通企业日报
  2. 笔记本重装windows系统,office全家桶消失的解决方案
  3. Reggie外卖项目 —— 项目开发整体介绍
  4. QR code二维码简介及Qrencode库的移植与使用
  5. verilog简单奇校验
  6. 半丸子头java教程视频教程_半丸子头怎么扎?半丸子头扎发视频教程
  7. HTTPS、HTTPS、SSH、MSTSC等常用网络服务的端口号
  8. 哪些方法可以用来提高微信小程序的应用速度?
  9. esd win10 /win8 最简单快速的安装方法 双系统、vhd、wimboot+VHD
  10. CSS面试须知--样式属性