###《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),分别是: 约会对象预测 手写数 ...
随机推荐
- [Objective-c 基础 - 3.4] protocol
A.概念 1.用来声明方法(不能声明成员变量) 2.只要某个类遵守了这个协议,相当于拥有了协议中得所有方法的声明 3.属性 (1)@required:默认,要求实现,不实现就会发出警告 (2)@opt ...
- 优化UITableViewCell高度计算的那些事(RunLoop)
这篇总结你可以读到: UITableView高度计算和估算的机制 不同iOS系统在高度计算上的差异 iOS8 self-sizing cell UITableView+FDTemplateLayout ...
- Modbus Poll :Byte Missing Error或CRC Error
原因: 1.通信线路受干扰或是路线接触不良: 用显示器测量物理电平信号 2.从机工作不正常: 检测电源不正常或查程序bug 3.PC主机串口不正常: PC串口2.3脚答短接用串口调试器测 ...
- android http 通信(httpclient 实现)
1.httpclient get 方式 HttpGet httpGet = new HttpGet(url); HttpClient client = new DefaultHttpClient(); ...
- IPO
Initial Public Offerings,简称IPO,首次公开募股(Initial Public Offerings,简称IPO):是指一家企业或公司 [1] (股份有限公司)第一次将它的股份 ...
- Struts2中的session、request、respsonse获取方法
个人对于struts有一种复杂的心情,平心而论,struts2是个人最早接触到的的框架,在学校的时候就已经开始学习了,大四毕业设计,无疑用的还是struct,那时候SSH还是很流行的,后来出来实习,直 ...
- PHP strpos() 函数
定义和用法 strpos() 函数返回字符串在另一个字符串中第一次出现的位置. 如果没有找到该字符串,则返回 false. 语法 strpos(string,find,start) 参数 描述 str ...
- Centos6 源代码部署MySQL5.6
mysql从5.5版本号開始,不再使用./configure编译,而是使用cmake编译器,详细的cmake编译參数能够參考mysql官网文档(※ 很重要) http://dev.mysql.com/ ...
- TQ210裸机编程(3)——按键(查询法)
首先查看TQ210的底板原理图 这次编程只操作KEY1和KEY2,在TQ210核心板原理图中搜索XEINT0 可以看出KEY1和KEY2分别接在S5PV210的GPH0_0和GPH0_1引脚. 这次编 ...
- android开发 Fragment嵌套调用常见错误
在activity中有时须要嵌套调用fragment,但嵌套调用往往带来视图的显示与预期的不一样或是fragment的切换有问题.在使用时要注意几点: 1.fragment中嵌套fragment,子f ...