import numpy as np
import operator
import random
import os def file2matrix(filePath):#从文本中提取特征矩阵和标签
f = open(filePath,'r+').readlines()
fileLength = len(f)
dataSet = np.zeros((fileLength,3),np.float64)
labelList = []
for i in range(fileLength):
row = f[i].split('\t')
dataSet[i,:] = row[0:3]
labelList.append(row[-1].strip('\n'))
return dataSet,labelList def autoNormal(data):#归一化处理
dataShape = data.shape
dataMin = data.min(0)
dataMax = data.max(0)
normalDataSet = np.zeros(dataShape,np.float64)
diff = dataMax - dataMin
normalDataSet = (data -np.tile(dataMin,(dataShape[0],1)))/np.tile(diff,(dataShape[0],1))
return normalDataSet,diff,dataMin def dataClassTest(dataSet,labelList):#测试算法准确率
ratio = 0.1
correntCount = 0
testNumber = int(ratio*dataSet.shape[0])
for i in range(testNumber):
k = random.randint(0, dataSet.shape[0])
label = classify0(dataSet[k],dataSet,labelList,20)
if label == labelList[k]:
correntCount += 1
return correntCount*100/testNumber def classifyPerson():#输入数据进行预测
dataSet,labelSet = file2matrix('datingTestSet.txt')
percentTats = float(input('Please input percentage of time spend playing video games?'))
miles = float(input('Please input frequent flier miles earned per year?'))
cream = float(input('Please input liters of ice cream consumed per year?'))
dataSet,diff,dataMin = autoNormal(dataSet)
intX = np.array([percentTats,miles,cream],np.float64) label = classify0((intX-dataMin)/diff,dataSet,labelSet,20)
print("You likely {0} the man!".format(label)) correntPercent = dataClassTest(dataSet,labelSet)
print("The estimate corrent percent is {0}%!".format(correntPercent)) def classify0(intX,dataSet,labelSet,k):#kNN分类算法
intX = np.tile(intX,(dataSet.shape[0],1))
square = (intX - dataSet)**2
sum = square.sum(axis=1)
sqrt = sum**0.5
sortedDistIndicies = sqrt.argsort()
classCount={}
for i in range(k):
label = labelSet[sortedDistIndicies[i]]
classCount[label] = classCount.get(label,0)+1
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1),reverse=True) return sortedClassCount[0][0] def img2vector(filename):#将32*32图片转换成1*1024向量
vector = np.zeros((1,1024))
f = open(filename)
for i in range(32):
fr = f.readline()
for j in range(32):
vector[0,32*i+j] = int(fr[j])
return vector def handwritingClassTest():
filenameList = os.listdir(r'machinelearninginaction\Ch02\digits\trainingDigits')
m = len(filenameList)
trainLabelList = []
trainDataMatrix = np.zeros((m,1024))
for i in range(m):
trainLabelList.append(int(filenameList[i].strip('_')[0]))
trainDataMatrix[i,:] = img2vector(r'machinelearninginaction\Ch02\digits\trainingDigits\{0}'.format(filenameList[i]))
filenameList = os.listdir(r'machinelearninginaction\Ch02\digits\testDigits')
m = len(filenameList)
corrent = 0.0
for i in range(m):
testLabel = int(filenameList[i].strip('_')[0])
testIn = img2vector(r'machinelearninginaction\Ch02\digits\testDigits\{0}'.format(filenameList[i]))
testOut = classify0(testIn,trainDataMatrix,trainLabelList,3)
if testOut == testLabel:
corrent += 1
else:
print("Error:the classifier came back with:{0}, the real answer is:{1}。".format(testOut,testLabel))
print("the corrent percent is:%.2f %%。"%(corrent*100/m))
if __name__ == '__main__':
classifyPerson() #约会预测
#handwritingClassTest() #手写识别

约会预测运行结果:

Please input percentage of time spend playing video games?100
Please input frequent flier miles earned per year?8
Please input liters of ice cream consumed per year?200
You likely didntLike the man!
The estimate corrent percent is 96.0%! 进程已结束,退出代码 0

手写识别运行结果:

Error:the classifier came back with:7, the real answer is:1。
Error:the classifier came back with:9, the real answer is:3。
Error:the classifier came back with:3, the real answer is:5。
Error:the classifier came back with:6, the real answer is:5。
Error:the classifier came back with:6, the real answer is:8。
Error:the classifier came back with:3, the real answer is:8。
Error:the classifier came back with:1, the real answer is:8。
Error:the classifier came back with:1, the real answer is:8。
Error:the classifier came back with:1, the real answer is:9。
Error:the classifier came back with:7, the real answer is:9。
the corrent percent is:98.94 %。 进程已结束,退出代码 0

测试数据:

说明:代码参考《机器学习实战》

kNN算法实例(约会对象喜好预测和手写识别)的更多相关文章

  1. 吴裕雄--天生自然python机器学习实战:K-NN算法约会网站好友喜好预测以及手写数字预测分类实验

    实验设备与软件环境 硬件环境:内存ddr3 4G及以上的x86架构主机一部 系统环境:windows 软件环境:Anaconda2(64位),python3.5,jupyter 内核版本:window ...

  2. 第二篇:基于K-近邻分类算法的约会对象智能匹配系统

    前言 假如你想到某个在线约会网站寻找约会对象,那么你很可能将该约会网站的所有用户归为三类: 1. 不喜欢的 2. 有点魅力的 3. 很有魅力的 你如何决定某个用户属于上述的哪一类呢?想必你会分析用户的 ...

  3. k最邻近算法——使用kNN进行手写识别

    上篇文章中提到了使用pillow对手写文字进行预处理,本文介绍如何使用kNN算法对文字进行识别. 基本概念 k最邻近算法(k-Nearest Neighbor, KNN),是机器学习分类算法中最简单的 ...

  4. python 实现 KNN 分类器——手写识别

    1 算法概述 1.1 优劣 优点:进度高,对异常值不敏感,无数据输入假定 缺点:计算复杂度高,空间复杂度高 应用:主要用于文本分类,相似推荐 适用数据范围:数值型和标称型 1.2 算法伪代码 (1)计 ...

  5. 机器学习实战一:kNN手写识别系统

    实战一:kNN手写识别系统 本文将一步步地构造使用K-近邻分类器的手写识别系统.由于能力有限,这里构造的系统只能识别0-9.需要识别的数字已经使用图形处理软件,处理成具有相同的色彩和大小:32像素*3 ...

  6. TensorFlow 入门之手写识别(MNIST) softmax算法

    TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  7. 机器学习实战kNN之手写识别

    kNN算法算是机器学习入门级绝佳的素材.书上是这样诠释的:“存在一个样本数据集合,也称作训练样本集,并且样本集中每个数据都有标签,即我们知道样本集中每一条数据与所属分类的对应关系.输入没有标签的新数据 ...

  8. TensorFlow 入门之手写识别(MNIST) softmax算法 二

    TensorFlow 入门之手写识别(MNIST) softmax算法 二 MNIST Fly softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  9. TensorFlow MNIST(手写识别 softmax)实例运行

    TensorFlow MNIST(手写识别 softmax)实例运行 首先要有编译环境,并且已经正确的编译安装,关于环境配置参考:http://www.cnblogs.com/dyufei/p/802 ...

随机推荐

  1. zookeeper分布式之学习搭建

    一.下载: 下载地址:https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/  下载解压到 C:\Users\Administrator\Desk ...

  2. moc_XXXX.o:(.data.rel.ro._ZTI12CalculatorUI[_ZTI12CalculatorUI]+0x10): undefined reference to `typeinfo for QWidget' collect2: error: ld returned 1 exit status make: *** [Makefile:144: myCalculator]

    main.cpp:(.text.startup+0x22): undefined reference to `QApplication::QApplication(int&, char**, ...

  3. wepy-数据双向绑定input

    初入wepy,发现wepy和vue神似,但还是有不一样的地方,例如v-model数据双向绑定 场景: 一个input搜索框,用户输入内容,点击“叉叉”按钮,输入的内容全部清空,这是一个很常见的场景 j ...

  4. kettle imestamp : Unable to get timestamp from resultset at index 22

    在做ETL的时候,连接MySQL读取含有timestamp类型的表,出现如下错误: 经Google,据说是MySQL自身的问题.解决方法也很简单,在Spoon的数据库连接中,打开选项,加入一行命令参数 ...

  5. 1. svn 简介

    参考文档: http://svndoc.iusesvn.com/ SVN的 相关网站 什么是svn?Subversion是一个“集中式”的信息共享系统.版本库是Subversion的核心部分,是数据的 ...

  6. java基础拓展

    1. 作用域:public private protected 默认的区别 public:在同一项目中,被public修饰的在任何地方都可以被调用 private:被private修饰的,只能在本类中 ...

  7. CDMA与OFDM之技术比较

    频谱利用率.支持高速率多媒体服务.系统容量.抗多径信道干扰等因素是目前大多数固定宽带无线接入设备商在选择CDMA(码分多址)或OFDM(正交 频分复用)作为点到多点(PMP)的关键技术时的主要出发点. ...

  8. Linux GDB 程序调试工具使用详解

    转自    http://www.codeceo.com/article/linux-gdb-tools.html 整理的挺全的 GDB概述 GDB是GNU开源组织发布的一个强大的UNIX下的程序调试 ...

  9. 多数据源(sql server 2008,二个数据库不ip,)

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  10. EOF和~

    输入包含多组数据 while(~scanf("%d",&n))<=>  while(scanf("%d",&n)!=EOF)