初学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的更多相关文章

  1. 《Machine Learning in Action》—— 懂的都懂,不懂的也能懂。非线性支持向量机

    说在前面:前几天,公众号不是给大家推送了第二篇关于决策树的文章嘛.阅读过的读者应该会发现,在最后排版已经有点乱套了.真的很抱歉,也不知道咋回事,到了后期Markdown格式文件的内容就解析出现问题了, ...

  2. 《Machine Learning in Action》—— 白话贝叶斯,“恰瓜群众”应该恰好瓜还是恰坏瓜

    <Machine Learning in Action>-- 白话贝叶斯,"恰瓜群众"应该恰好瓜还是恰坏瓜 概率论,可以说是在机器学习当中扮演了一个非常重要的角色了.T ...

  3. 《Machine Learning in Action》—— 浅谈线性回归的那些事

    <Machine Learning in Action>-- 浅谈线性回归的那些事 手撕机器学习算法系列文章已经肝了不少,自我感觉质量都挺不错的.目前已经更新了支持向量机SVM.决策树.K ...

  4. 《Machine Learning in Action》—— Taoye给你讲讲Logistic回归是咋回事

    在手撕机器学习系列文章的上一篇,我们详细讲解了线性回归的问题,并且最后通过梯度下降算法拟合了一条直线,从而使得这条直线尽可能的切合数据样本集,已到达模型损失值最小的目的. 在本篇文章中,我们主要是手撕 ...

  5. 《Machine Learning in Action》—— 剖析支持向量机,单手狂撕线性SVM

    <Machine Learning in Action>-- 剖析支持向量机,单手狂撕线性SVM 前面在写NumPy文章的结尾处也有提到,本来是打算按照<机器学习实战 / Machi ...

  6. 《Machine Learning in Action》—— 剖析支持向量机,优化SMO

    <Machine Learning in Action>-- 剖析支持向量机,优化SMO 薄雾浓云愁永昼,瑞脑销金兽. 愁的很,上次不是更新了一篇关于支持向量机的文章嘛,<Machi ...

  7. 《Machine Learning in Action》—— Taoye给你讲讲决策树到底是支什么“鬼”

    <Machine Learning in Action>-- Taoye给你讲讲决策树到底是支什么"鬼" 前面我们已经详细讲解了线性SVM以及SMO的初步优化过程,具体 ...

  8. 《Machine Learning in Action》—— 小朋友,快来玩啊,决策树呦

    <Machine Learning in Action>-- 小朋友,快来玩啊,决策树呦 在上篇文章中,<Machine Learning in Action>-- Taoye ...

  9. Machine Learning In Action 第二章学习笔记: kNN算法

    本文主要记录<Machine Learning In Action>中第二章的内容.书中以两个具体实例来介绍kNN(k nearest neighbors),分别是: 约会对象预测 手写数 ...

随机推荐

  1. 起底多线程同步锁(iOS)

    iOS/MacOS为多线程.共享内存(变量)提供了多种的同步解决方案(即同步锁),对于这些方案的比较,大都讨论了锁的用法以及锁操作的开销,然后就开销表现排个序.春哥以为,最优方案的选用还是看应用场景, ...

  2. jquery-ui 之Sortable详解

    <div class="aaa"> <ul id="sortable"> <li id="test">I ...

  3. MSSQLSERVER数据库- 作业调度定时备份数据库

    作业调度和备份数据库是常见的行为,掌握这两项技术我觉的非常有必要. 在网上找到这个示例,记录在这里 备份数据库的SQL语句 --自动备份并保存最近5天的SQL数据库作业脚本 ) DECLARE @da ...

  4. ABAP ALV 颜色设置(行,列,单元格)

    BCALV_EDIT_03 http://blog.sina.com.cn/s/blog_a87b19300102who3.html 关于ALV表格颜色,这种需求在项目中会经常用到. 列颜色 列的颜色 ...

  5. SUSE的SSHD配置及设置防火墙

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  6. linux的root登录password问题

    以Ubuntu为样例, 第一次登录root用户的时候,让输入password总是显示认证失败 由于安装Ubuntu的时候没有设置root的password.所以每次开机都会分配不同的rootpassw ...

  7. 在iOS中怎样创建可展开的Table View?(上)

    原文地址 本文作者:gabriel theodoropoulos 原文:How To Create an Expandable Table View in iOS 原文链接 几乎所有的app都有一个共 ...

  8. 用 jQuery Masonry 插件创建瀑布流式的页面(转)

    瀑布流式的页面,最早我是在国外的一个叫 Pinterest 的网站上看到,这个网站爆发,后来国内的很多网站也使用了这种瀑布流方式来展示页面(我不太喜欢瀑布流这个名字). 我们可以使用 jQuery 的 ...

  9. Mysql数据库导入命令Source详解

    Mysql数据库导入命令Source详解 几个常用用例: 1.导出整个数据库 mysqldump -u 用户名 -p 数据库名 > 导出的文件名 mysqldump -u root -p dat ...

  10. Component migration documentation

    Component migration documentation The following is a list of migration documents for components we s ...