---恢复内容开始---

《 Machine Learning 机器学习实战》的确是一本学习python,掌握数据相关技能的,不可多得的好书!!

最近邻算法源码如下,给有需要的入门者学习,大神请绕道。

数字识别文件

'''
Created on Sep 16, 2010
kNN: k Nearest Neighbors Input: inX: vector to compare to existing dataset (1xN)
dataSet: size m data set of known vectors (NxM)
labels: data set labels (1xM vector)
k: number of neighbors to use for comparison (should be an odd number) Output: the most popular class label @author: pbharrin
'''
from numpy import *
import operator
from os import listdir 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={}
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] 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 file2matrix(filename):
fr = open(filename)
numberOfLines = len(fr.readlines()) #get the number of lines in the file
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip()
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)) #element wise divide
return normDataSet, ranges, minVals def datingClassTest():
hoRatio = 0.50 #hold out 10%
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') #load data setfrom file
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],3)
print "the classifier came back with: %d, the real answer is: %d" % (classifierResult, datingLabels[i])
if (classifierResult != datingLabels[i]): errorCount += 1.0
print "the total error rate is: %f" % (errorCount/float(numTestVecs))
print errorCount  

手写数字识别

# 解析文本数据

def img2vector(filename):
    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') #load the training set
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0] #take off .txt
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
trainingMat[i,:] = img2vector('trainingDigits/%s' % fileNameStr)
testFileList = listdir('testDigits') #iterate through the test set
errorCount = 0.0
mTest = len(testFileList)
for i in range(mTest):
fileNameStr = testFileList[i]
fileStr = fileNameStr.split('.')[0] #take off .txt
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 "\nthe total number of errors is: %d" % errorCount
print "\nthe total error rate is: %f" % (errorCount/float(mTest))

使用k-近邻算法改进约会网站的配对效果的更多相关文章

  1. 使用K近邻算法改进约会网站的配对效果

    1 定义数据集导入函数 import numpy as np """ 函数说明:打开并解析文件,对数据进行分类:1 代表不喜欢,2 代表魅力一般,3 代表极具魅力 Par ...

  2. k-近邻(KNN)算法改进约会网站的配对效果[Python]

    使用Python实现k-近邻算法的一般流程为: 1.收集数据:提供文本文件 2.准备数据:使用Python解析文本文件,预处理 3.分析数据:可视化处理 4.训练算法:此步骤不适用与k——近邻算法 5 ...

  3. 【Machine Learning in Action --2】K-近邻算法改进约会网站的配对效果

    摘自:<机器学习实战>,用python编写的(需要matplotlib和numpy库) 海伦一直使用在线约会网站寻找合适自己的约会对象.尽管约会网站会推荐不同的人选,但她没有从中找到喜欢的 ...

  4. 机器学习读书笔记(二)使用k-近邻算法改进约会网站的配对效果

    一.背景 海伦女士一直使用在线约会网站寻找适合自己的约会对象.尽管约会网站会推荐不同的任选,但她并不是喜欢每一个人.经过一番总结,她发现自己交往过的人可以进行如下分类 不喜欢的人 魅力一般的人 极具魅 ...

  5. 吴裕雄--天生自然python机器学习:使用K-近邻算法改进约会网站的配对效果

    在约会网站使用K-近邻算法 准备数据:从文本文件中解析数据 海伦收集约会数据巳经有了一段时间,她把这些数据存放在文本文件(1如1^及抓 比加 中,每 个样本数据占据一行,总共有1000行.海伦的样本主 ...

  6. 机器学习实战1-2.1 KNN改进约会网站的配对效果 datingTestSet2.txt 下载方法

    今天读<机器学习实战>读到了使用k-临近算法改进约会网站的配对效果,道理我都懂,但是看到代码里面的数据样本集 datingTestSet2.txt 有点懵,这个样本集在哪里,只给了我一个文 ...

  7. KNN算法项目实战——改进约会网站的配对效果

    KNN项目实战——改进约会网站的配对效果 1.项目背景: 海伦女士一直使用在线约会网站寻找适合自己的约会对象.尽管约会网站会推荐不同的人选,但她并不是喜欢每一个人.经过一番总结,她发现自己交往过的人可 ...

  8. kNN分类算法实例1:用kNN改进约会网站的配对效果

    目录 实战内容 用sklearn自带库实现kNN算法分类 将内含非数值型的txt文件转化为csv文件 用sns.lmplot绘图反映几个特征之间的关系 参考资料 @ 实战内容 海伦女士一直使用在线约会 ...

  9. k-近邻算法-优化约会网站的配对效果

    KNN原理 1. 假设有一个带有标签的样本数据集(训练样本集),其中包含每条数据与所属分类的对应关系. 2. 输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进行比较. a. 计算新 ...

随机推荐

  1. lucene 索引流程整理笔记

    索引的原文档(Document). 为了方便说明索引创建过程,这里特意用两个文件为例: 文件一:Students should be allowed to go out with their frie ...

  2. sybase参数调整

  3. UIview 学习与自定义--ios

    UIView *view1=[[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]; view1.backgroundColor=[UI ...

  4. AngularJS 1.5.0-beta.2 and 1.4.8 have been released

    AngularJS 1.5.0-beta.2 With AngularJS 1.5.0-beta.2, we’ve improved the performance and flexibility o ...

  5. JQuery Pagenation 知识点整理——(function($){...})应用(20150517)

    首先:(function($){...})为Jquery提供的匿名函数: 代码实例(一) <script type="text/javascript"> (functi ...

  6. [转]Linux环境下查看线程数的几种方法

    1.cat /proc/${pid}/status 2.pstree -p ${pid} 3.top -p ${pid} 再按H,或者直接输入 top -bH -d 3 -p  ${pid} top ...

  7. 查看.Net Framework版本的方法

    乐博网最新补充(乐博网一步步教你如何最快查看本机.net framework的版本): 方法一: 第一步: 打开“我的电脑“,在地址栏输入  %systemroot%\Microsoft.NET\Fr ...

  8. 08socket编程

    有个SO_REUSEADDR值得注意一下: 服务器端尽可能使用SO_REUSEADDR 在绑定之前尽可能调用setsockopt来设置SO_REUSEADDR套接字选项. 使用SO_REUSEADDR ...

  9. bzoj2467: [中山市选2010]生成树

    Description 有一种图形叫做五角形圈.一个五角形圈的中心有1个由n个顶点和n条边组成的圈.在中心的这个n边圈的每一条边同时也是某一个五角形的一条边,一共有n个不同的五角形.这些五角形只在五角 ...

  10. poj2352消防站

    题目大意:有n个点的一棵树,每个点有两个值:w和c.现在要在其中若干点建立消防站,使得每个点到最近的消防站的距离不超过该点的c值,i点建立消防站的费用为w.求最小费用. 分析:本题显然是树型Dp.定义 ...