###《Machine Learning in Action》 - KNN
初学
Python;理解机器学习。
算法是需要实现的,纸上得来终觉浅。
// @author: gr
// @date: 2015-01-16
// @email: forgerui@gmail.com
一、简单的KNN
from numpy import *
import operator
def createDataSet():
group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
def 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 = {}
# 对前k个样例的标签进行计数
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]
二、KNN用于约会网站配对效果
def file2matrix(filename):
# 读取文件
fr = open(filename)
arrayOLines = fr.readlines()
numberOfLines = len(arrayOLines)
returnMat = zeros((numberOfLines, 3))
classLabelVector = []
index = 0
for line in arrayOLines:
# 去除换行符
line = line.strip()
# 按Tab键分割列
listFromLine = line.split('\t')
returnMat[index, :] = listFromLine[0:3]
# 存储标签
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat, classLabelVector
def autoNorm(dataSet):
minVals = dataSet.min(0)
maxVals = dataSet.max(0)
ranges = maxVals - minVals
normDataSet = zeros(shape(dataSet))
# 数据的行数
m = dataSet.shape[0]
normDataSet = dataSet - tile(minVals, (m, 1))
normDataSet = normDataSet / tile(ranges, (m, 1))
return normDataSet, ranges, minVals
def datingClassTest():
hoRatio = 0.10
datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
normMat, ranges, minVals = autoNorm(datingDataMat)
m = normMat.shape[0]
# 选取测试集数量
numTestVecs = int(m * hoRatio)
errorCount = 0.0
for i in range(numTestVecs):
classifierResult = classify0(normMat[i, :], normMat[numTestVecs:m, :], \
datingLabels[numTestVecs:m], 7)
print "the classifirer came back with: %d, the real answer is: %d"\
% (classifierResult, datingLabels[i])
# 记录错误数
if (classifierResult != datingLabels[i]) : errorCount += 1.0
print "numTestVecs: %f" % float(numTestVecs)
print "the total error rate is: %f" % (errorCount/float(numTestVecs))
def classifyPerson():
# 针对一个人判断
resultList = ['not at all', 'in small doses', 'in large doses']
percentTats = float(raw_input(\
"percentage of time spent playing video games?"))
ffMiles = float(raw_input("frequent flier miles earned per year?"))
iceCream = float(raw_input("liters of ice cream consumed per year?"))
datingDataMat, datingLabels = file2matrix('datingTestSet2.txt')
normMat, ranges, minVals = autoNorm(datingDataMat)
inArr = array([ffMiles, percentTats, iceCream])
classifierResult = classify0((inArr-\
minVals)/ranges, normMat, datingLabels, 3)
print "You will probably like this person: ", \
resultList[classifierResult - 1]
三、手写识别系统
def img2vector(filename):
# 32*32的图片转成一个向量
returnVect = zeros((1, 1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVect[0, 32*i+j] = int(lineStr[j])
return returnVect
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = zeros((m, 1024))
# 把训练的文件图片转换成一个m*1024矩阵
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i, :] = img2vector('trainingDigits/%s' % fileNameStr)
testFileList = listdir('testDigits')
errorCount = 0.0
# 在测试集上测试
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
vectorUnderTest = img2vector('testDigits/%s' % fileNameStr)
classifierResult = classify0(vectorUnderTest, \
trainingMat, hwLabels, 3)
print "the classifier came back with: %d, the real answer is: %d" \
% (classifierResult, classNumStr)
if (classifierResult != classNumStr):
errorCount += 1.0
print "\n the total number of errors is: %d" % errorCount
print "\n the total error rate is: %f" % (errorCount/float(mTest))
###《Machine Learning in Action》 - KNN的更多相关文章
- 《Machine Learning in Action》—— 懂的都懂,不懂的也能懂。非线性支持向量机
说在前面:前几天,公众号不是给大家推送了第二篇关于决策树的文章嘛.阅读过的读者应该会发现,在最后排版已经有点乱套了.真的很抱歉,也不知道咋回事,到了后期Markdown格式文件的内容就解析出现问题了, ...
- 《Machine Learning in Action》—— 白话贝叶斯,“恰瓜群众”应该恰好瓜还是恰坏瓜
<Machine Learning in Action>-- 白话贝叶斯,"恰瓜群众"应该恰好瓜还是恰坏瓜 概率论,可以说是在机器学习当中扮演了一个非常重要的角色了.T ...
- 《Machine Learning in Action》—— 浅谈线性回归的那些事
<Machine Learning in Action>-- 浅谈线性回归的那些事 手撕机器学习算法系列文章已经肝了不少,自我感觉质量都挺不错的.目前已经更新了支持向量机SVM.决策树.K ...
- 《Machine Learning in Action》—— Taoye给你讲讲Logistic回归是咋回事
在手撕机器学习系列文章的上一篇,我们详细讲解了线性回归的问题,并且最后通过梯度下降算法拟合了一条直线,从而使得这条直线尽可能的切合数据样本集,已到达模型损失值最小的目的. 在本篇文章中,我们主要是手撕 ...
- 《Machine Learning in Action》—— 剖析支持向量机,单手狂撕线性SVM
<Machine Learning in Action>-- 剖析支持向量机,单手狂撕线性SVM 前面在写NumPy文章的结尾处也有提到,本来是打算按照<机器学习实战 / Machi ...
- 《Machine Learning in Action》—— 剖析支持向量机,优化SMO
<Machine Learning in Action>-- 剖析支持向量机,优化SMO 薄雾浓云愁永昼,瑞脑销金兽. 愁的很,上次不是更新了一篇关于支持向量机的文章嘛,<Machi ...
- 《Machine Learning in Action》—— Taoye给你讲讲决策树到底是支什么“鬼”
<Machine Learning in Action>-- Taoye给你讲讲决策树到底是支什么"鬼" 前面我们已经详细讲解了线性SVM以及SMO的初步优化过程,具体 ...
- 《Machine Learning in Action》—— 小朋友,快来玩啊,决策树呦
<Machine Learning in Action>-- 小朋友,快来玩啊,决策树呦 在上篇文章中,<Machine Learning in Action>-- Taoye ...
- Machine Learning In Action 第二章学习笔记: kNN算法
本文主要记录<Machine Learning In Action>中第二章的内容.书中以两个具体实例来介绍kNN(k nearest neighbors),分别是: 约会对象预测 手写数 ...
随机推荐
- nyoj 811 变态最大值
变态最大值 时间限制:1000 ms | 内存限制:65535 KB 难度:1 描述 Yougth讲课的时候考察了一下求三个数最大值这个问题,没想到大家掌握的这么烂,幸好在他的帮助下大家算是解 ...
- _int、NSInteger、NSUInteger、NSNumber的区别和联系
1.首先先了解下NSNumber类型: 苹果官方文档地址:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/F ...
- Umbraco中的权限体系结构
分为管理用户体系,和成员用户体系,也就是 Users(用户)和Members(成员). 2.1. Users(用户) 用户是对功能操作权限定义的,首先看一下所有Action的Permissions: ...
- java IO选择流的原则及其与IO流相关类的关系
1 按照用途进行分类 1.1 按照数据的来源(去向)分类 是文件:FileInputStream, FileOutputStream, FileReader, FileWriter 是byte[]:B ...
- Vim Skills——Windows利用Vundle和Github进行Vim配置和插件的同步
OS:Windows Vim安装完成之后,目录如下 vim73:vim运行时所需的文件,对应目录为$VIMRUNTIME变量 vimfiles:第三方的文件,对应目录为$VIM/vimfiles _v ...
- xcode中create groups 和 create folder reference 的区别
(文章为博主原创,未经允许,不得转载!) 今天在项目中搭建框架忽然发现工程中有黄蓝文件夹的区别,而且对应到不同的情况: 1.蓝色文件夹下文件不能被读取: 2.蓝色文件夹下创建新的文件类会直接跳过选择类 ...
- SQLite使用教程4 创建数据库
http://www.runoob.com/sqlite/sqlite-create-database.html SQLite 创建数据库 SQLite 的 sqlite3 命令被用来创建新的 SQL ...
- Lync安装随笔
使用域管理员权限扩展架构 1.iis角色安装 2.net3.5,消息队列服务器.目录服务集成.桌面体验.AD DS和AD LDS工具(远程服务管理工具中),启用WindowsFirewall服务 3. ...
- Android develop tricks——整理自国外的一些Blog
ViewDragHelper --视图拖动是一个比較复杂的问题.这个类能够帮助解决不少问题.假设你须要一个样例,DrawerLayout就是利用它实现扫滑.Flavient Laurent 还写了一些 ...
- python第三方库系列之十九--python測试使用的mock库
一.为什么须要mock 在写unittest的时候,假设系统中有非常多外部依赖,我们不须要也不希望把全部的部件都执行一遍.比方,要验证分享到微博的功能,假设每次測试的时候都要真实地把接 ...