###《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),分别是: 约会对象预测 手写数 ...
随机推荐
- light oj 1138
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu Submit Status Pract ...
- 单机c/s软件如何让老板在异地看销售营业报表
单机软件,让人的感觉就只能在本地使用. 单机版c/s软件,数据存放在本机上,老板想要查看销售报表的话,需要跑到公司的那台电脑上才能查看,这对于在外面四处跑业务的老板来说,基本上是不可能做到的.但每天的 ...
- Activity详解
Activity是android应用的重要组成单元之一(另外3个是Service,BroadcastReceiver和ContentProvider).实际应用包含了多个Activity,不同的Act ...
- Oracle- 包
在一个大型项目中,可能有很多模块,而每个模块又有自己的过程.函数等.而这些过程.函数默认是放在一起的(如在PL/SQL中,过程默认都是放在一起的,即Procedures中),这些非常不方便查询和维护. ...
- 利用sqlmap和burpsuite绕过csrf token进行SQL注入 (转)
问题:post方式的注入验证时遇到了csrf token的阻止,原因是csrf是一次性的,失效导致无法测试. 解决方案:Sqlmap配合burpsuite,以下为详细过程,参照国外牛人的blog(不过 ...
- 【M19】了解临时对象的来源
1.首先,确认什么是临时对象.在swap方法中,建立一个对象temp,程序员往往把temp称为临时对象.实际上,temp是个局部对象.C++中所谓的临时对象是不可见的,产生一个non-heap对象,并 ...
- git克隆远程项目分支到本地对应分支
最近公司改用git了,研究了一下如何把远程的代码克隆到本地. 1. 配置对应信息 git config --global user.name git config --global user.emai ...
- UVa 131 - The Psychic Poker Player
题目:手里有五张牌,桌上有一堆牌(五张).你能够弃掉手中的k张牌,然后从牌堆中取最上面的k个. 比較规则例如以下:(按优先级排序) 1.straight-flush:同花顺.牌面为T(10) - A, ...
- CustomViewWith_Image_Text_Video
CustomViewOfTextVideoImage.rar https://github.com/Grishu/CustomViewWith_Image_Text_Video
- android学习日记03--常用控件tabSpec/tabHost
常用控件7.TabSpec和TabHost 比较常用的控件,感觉手机QQ的整体布局就是这个,只不过tab放在底部而已.TabSpec相当于浏览器的分页,而TabHost就相当于分页的集合TabSpec ...