K-近邻算法_使用k最近邻算法进行多分类 输入说明:输入由三行组成,每行由一个数组成,第一行表-程序员宅基地

技术标签: 算法  机器学习实践  

K-近邻算法

  • 优点:精度高,对异常值不敏感,无数据输入假定
  • 缺点:计算复杂度高,空间复杂度高
  • 适用数据范围:数值型和标称型

K-近邻算法的一般流程

  1. 收集数据:可以使用任何方法
  2. 准备数据:距离计算所需要的数值,最好是结构化的数据格式
  3. 分析数据:可以使用任何方法
  4. 训练方法:此步骤不适用于K-近邻算法
  5. 测试算法:计算错误率
  6. 使用算法:首先需要输入样本数据和结构化的输出结果,然后运行K-近邻算法判定输入数据分别属于那个分类,最后应用对计算出的分类执行后续的处理
    tile(A,rep):重复A的各个维度
from numpy import *
import operator
def createDataSet():
    group=array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels=['A','B','C','D']
    return group,labels

def classify0(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    #距离计算
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDoffMat=diffMat**2
    sqDistances=sqDoffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndices=distances.argsort()
    classCount={}
    #选择激励最小的K个点
    for i in range(k):
        voteIlabel=labels[sortedDistIndices[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
    sortedClassCount=sorted(classCount.items(),
                           key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]   

group,labels=createDataSet()
classify0([0,0],group,labels,3)
'C'

函数详解

tile([1,2],2)
array([1, 2, 1, 2])
tile([1,2],(2,2))
array([[1, 2, 1, 2],
       [1, 2, 1, 2]])
x=array([[1,2,3],[2,3,4]])
print(x.shape)
print(x.shape[0])
(2, 3)
2
x=array([[1,2,3],[2,3,4]])
print(x**2)
[[ 1  4  9]
 [ 4  9 16]]
x = np.array([[0, 3], [2, 2]])
np.argsort(x, axis=0)
np.argsort(x, axis=1)
array([[0, 1],
       [1, 0]])
array([[0, 1],
       [0, 1]])
dict = {
   'Name': 'Zara', 'Age': 27}
print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Sex', "Never")
Value : 27
Value : Never
""
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组
""
dict = {
   'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}

print "字典值 : %s" %  dict.items()

# 遍历字典列表
for key,values in  dict.items():
    print key,values
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
#operator库块提供了一系列的函数操作。比如,operator.add(x, y)等于x+y 
abs(...)
        abs(a) -- Same as abs(a).
and_(...)
        and_(a, b) -- Same as a & b.
contains(...)
        contains(a, b) -- Same as b in a (note reversed operands).
eq(...)
        eq(a, b) -- Same as a==b.

operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号。operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。

a = [1,2,3] 
>>> b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值
>>> b(a) 

2

>>> b=operator.itemgetter(1,0)  //定义函数b,获取对象的第1个域和第0个的值
>>> b(a) 
(2, 1)

sorted函数用来排序,sorted(iterable[, cmp[, key[, reverse]]])

其中key的参数为一个函数或者lambda函数。所以itemgetter可以用来当key的参数

a = [(‘john’, ‘A’, 15), (‘jane’, ‘B’, 12), (‘dave’, ‘B’, 10)]

根据第二个域和第三个域进行排序

sorted(students, key=operator.itemgetter(1,2))
只要是可迭代对象都可以用sorted 。

sorted(itrearble, cmp=None, key=None, reverse=False)

=号后面是默认值 默认是升序排序的, 如果想让结果降序排列,用reverse=True

最后会将排序的结果放到一个新的列表中, 而不是对iterable本身进行修改。

1, 简单排序

sorted('123456')  字符串

['1', '2', '3', '4', '5', '6']

sorted([1,4,5,2,3,6])  列表
[1, 2, 3, 4, 5, 6]

sorted({
    1:'q',3:'c',2:'g'}) 字典, 默认对字典的键进行排序
[1, 2, 3]

 sorted({
    1:'q',3:'c',2:'g'}.keys())  对字典的键
[1, 2, 3]

sorted({
    1:'q',3:'c',2:'g'}.values())  对字典的值
['c', 'g', 'q']

sorted({
    1:'q',3:'c',2:'g'}.items())  对键值对组成的元组的列表
[(1, 'q'), (2, 'g'), (3, 'c')]

自定义比较函数

def comp(x, y):
if x < y:
return 1
elif x > y:
return -1
else:
return 0

nums = [3, 2, 8 ,0 , 1]
nums.sort(comp)
print nums # 降序排序[8, 3, 2, 1, 0]
nums.sort(cmp) # 调用内建函数cmp ,升序排序
print nums # 降序排序[0, 1, 2, 3, 8]

key在使用时必须提供一个排序过程总调用的函数

x = ['mmm', 'mm', 'mm', 'm' ]
x.sort(key = len)
print x # ['m', 'mm', 'mm', 'mmm']

在约会网站上使用K近邻算法

  1. 收集算法:提供文本文件
  2. 准备数据:使用Python解析文本文件
  3. 分析数据:使用matplotlib画二维扩散图
  4. 训练算法:不适用K近邻算法
  5. 测试算法:使用海伦提供的部分数据作为测试样本。
    测试样本与非测试样本的区别在于:测试样本是已经完成分类的 数据,如果预测分类与实际类别不同,则标记为一个错误
  6. 使用算法:产生简单的命令行程序,然后海伦可以输入一些特征数据以判断对方是否为自己喜欢的类型

    完整代码:

from numpy import *
import operator

def classify0(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    #距离计算
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDoffMat=diffMat**2
    sqDistances=sqDoffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndices=distances.argsort()
    classCount={}
    #选择激励最小的K个点
    for i in range(k):
        voteIlabel=labels[sortedDistIndices[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
    sortedClassCount=sorted(classCount.items(),
                           key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]

def file2matrix(filename):
    fr=open(filename)
    arrayOLines=fr.readlines()
    numberOfLines=len(arrayOLines)
    returnMat=zeros((numberOfLines,3))
    classLabelVector=[]
    index=0
    for line in arrayOLines:
        #跳过所有的空格字符,使用tab‘\t’分割数据
        line=line.strip()
        listFromLine=line.split('\t')
        returnMat[index,:]=listFromLine[0:3]
        classLabelVector.append(int(listFromLine[-1]))
        index+=1
    return returnMat,classLabelVector
data_path='E:/dataset/machinelearninginaction/Ch02/'
datMat,datLabel=file2matrix(data_path+'datingTestSet2.txt')
print(datMat)
print(datLabel[0:20])
#分析数据:使用matplotlib创建散点图
import matplotlib
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
ax.scatter(datMat[:,0],datMat[:,1],
           15.0*array(datLabel),15.0*array(datLabel))
plt.show()
#准备数据:归一化数据
def autoNorm(dataSet):
    minVals=dataSet.min(0)
    maxVals=dataSet.max(0)
    ranges=maxVals-minVals
    m=dataSet.shape[0]
    normData=dataSet-tile(minVals,(m,1))
    normData=normData/tile(ranges,(m,1))
    return normData,ranges,minVals
normData,ranges,minVals=autoNorm(datMat)
print(normData)
print(ranges)
#测试算法:作为完整程序验证分类器
def datingClassTest():
    hoRatio=0.10
    datingDataMat,datingDatalabel=file2matrix(data_path+\
                                              'datingTestSet2.txt')
    norm,range1,minVals=autoNorm(datingDataMat)
    m=norm.shape[0]
    numTest=int(m*hoRatio)
    errorCount=0
    for i in range(numTest):
        classResult=classify0(norm[i,:],norm[numTest:m,:],\
                              datLabel[numTest:m],3)
        print('分类器学习的结果,%d,真实值是%d'%(classResult,datingDatalabel[i]))
        if(classResult!=datingDatalabel[i]):errorCount+=1
    print("错误率是:%f"%(errorCount/numTest))
if __name__ == '__main__':
    datingClassTest()

实例:手写识别系统

  1. 收集数据:提供文本文件
  2. 准备数据:编写函数img2vector函数,将图像格式转换为分类器的向量形式
  3. 分析数据:在Python命令提示符中检查数据,确保它符合要求
  4. 训练算法:此步骤不适用KNN
  5. 测试算法:编写函数使用提供的部分数据集作为测试样本,测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果测试分类与实际类别不同,则标记为一个错误
  6. 使用算法:本例没有完成此步骤,若你感兴趣可以构建完整的应用程序,从图像中提取数字,并完成数字识别,美国的邮件分拣系统就是一个实际运行的类似系统

准备数据:将图像转换为测试向量

from numpy import *
import operator
def img2vector(filename):
    file_path = "E:/dataset/machinelearninginaction/Ch02/digits/trainingDigits/"
    returnVec=zeros((1,1024))
    fr=open(file_path+filename)
    for i2 in range(32):
        lineStr=fr.readline()
        for j2 in range(32):
            returnVec[0,32*i2+j2]=int(lineStr[j2])
    return returnVec

def classify0(inX,dataSet,labels,k):
    dataSetSize=dataSet.shape[0]
    #距离计算
    diffMat=tile(inX,(dataSetSize,1))-dataSet
    sqDoffMat=diffMat**2
    sqDistances=sqDoffMat.sum(axis=1)
    distances=sqDistances**0.5
    sortedDistIndices=distances.argsort()
    classCount={}
    #选择激励最小的K个点
    for i in range(k):
        voteIlabel=labels[sortedDistIndices[i]]
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1
    sortedClassCount=sorted(classCount.items(),
                           key=operator.itemgetter(1),reverse=True)
    return sortedClassCount[0][0]

import os
def handWritingClassTest():
    hwLabels=[]
    trainingFileList=os.listdir('E:/dataset/machinelearninginaction/Ch02/digits/trainingDigits')
    m=len(trainingFileList)
    print(m)
    trainVec=zeros((m,1024))
    #traingLabel=zeros((m,1))
    traingLabel=[]
    i=0
    for filename in trainingFileList:
        img=img2vector(filename)
        trainVec[i,:]=img
        label=filename.split('_')[0]
        traingLabel.append(int(label))
        i+=1
    testFileList=os.listdir("E:/dataset/machinelearninginaction/Ch02/digits/testDigits")
    #n=len(testFileList)
    i=0
    for filename in testFileList:
        img=img2vector(filename)
        #testVect[i]=img
        resu=classify0(img,trainVec,traingLabel,3)
        label = filename.split('_')[0]
        print("predict:%d    the true value:%d"%(resu,int(label)))
        if(resu!=label):
            i+=1
    print("the precision is %f"%(i/len(testFileList)))

file_path="E:/dataset/machinelearninginaction/Ch02/digits/trainingDigits/"
#testVec=img2vector(file_path+"0_0.txt")
#print(testVec[0:32])
handWritingClassTest()
the precision is 1.000000
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u012778718/article/details/78681504

智能推荐

WCE Windows hash抓取工具 教程_wce.exe -s aaa:win-9r7tfgsiqkf:0000000000000000000-程序员宅基地

文章浏览阅读6.9k次。WCE 下载地址:链接:https://share.weiyun.com/5MqXW47 密码:bdpqku工具界面_wce.exe -s aaa:win-9r7tfgsiqkf:00000000000000000000000000000000:a658974b892e

各种“网络地球仪”-程序员宅基地

文章浏览阅读4.5k次。Weather Globe(Mackiev)Google Earth(Google)Virtual Earth(Microsoft)World Wind(NASA)Skyline Globe(Skylinesoft)ArcGISExplorer(ESRI)国内LTEarth(灵图)、GeoGlobe(吉奥)、EV-Globe(国遥新天地) 软件名称: 3D Weather Globe(http:/_网络地球仪

程序员的办公桌上,都出现过哪些神奇的玩意儿 ~_程序员展示刀,产品经理展示枪-程序员宅基地

文章浏览阅读1.9w次,点赞113次,收藏57次。我要买这些东西,然后震惊整个办公室_程序员展示刀,产品经理展示枪

霍尔信号、编码器信号与电机转向-程序员宅基地

文章浏览阅读1.6w次,点赞7次,收藏63次。霍尔信号、编码器信号与电机转向从电机出轴方向看去,电机轴逆时针转动,霍尔信号的序列为编码器信号的序列为将霍尔信号按照H3 H2 H1的顺序组成三位二进制数,则霍尔信号翻译成状态为以120°放置霍尔为例如不给电机加电,使用示波器测量三个霍尔信号和电机三相反电动势,按照上面所说的方向用手转动电机得到下图① H1的上升沿对应电机q轴与H1位置电角度夹角为0°,..._霍尔信号

个人微信淘宝客返利机器人搭建教程_怎么自己制作返利机器人-程序员宅基地

文章浏览阅读7.1k次,点赞5次,收藏36次。个人微信淘宝客返利机器人搭建一篇教程全搞定天猫淘宝有优惠券和返利,仅天猫淘宝每年返利几十亿,你知道么?技巧分享:在天猫淘宝京东拼多多上挑选好产品后,按住标题文字后“复制链接”,把复制的淘口令或链接发给机器人,复制机器人返回优惠券口令或链接,再打开天猫或淘宝就能领取优惠券啦下面教你如何搭建一个类似阿可查券返利机器人搭建查券返利机器人前提条件1、注册微信公众号(订阅号、服务号皆可)2、开通阿里妈妈、京东联盟、拼多多联盟一、注册微信公众号https://mp.weixin.qq.com/cgi-b_怎么自己制作返利机器人

【团队技术知识分享 一】技术分享规范指南-程序员宅基地

文章浏览阅读2.1k次,点赞2次,收藏5次。技术分享时应秉持的基本原则:应有团队和个人、奉献者(统筹人)的概念,同时匹配团队激励、个人激励和最佳奉献者激励;团队应该打开工作内容边界,成员应该来自各内容方向;评分标准不应该过于模糊,否则没有意义,应由客观的基础分值以及分团队的主观综合结论得出。应有心愿单激励机制,促进大家共同聚焦到感兴趣的事情上;选题应有规范和框架,具体到某个小类,这样收获才有目标性,发布分享主题时大家才能快速判断是否是自己感兴趣的;流程和分享的模版应该有固定范式,避免随意的格式导致随意的内容,评分也应该部分参考于此;参会原则,应有_技术分享

随便推点

O2OA开源企业办公开发平台:使用Vue-CLI开发O2应用_vue2 oa-程序员宅基地

文章浏览阅读1k次。在模板中,我们使用了标签,将由o2-view组件负责渲染,给o2-view传入了两个参数:app="内容管理数据"和name="所有信息",我们将在o2-view组件中使用这两个参数,用于展现“内容管理数据”这个数据应用下的“所有信息”视图。在o2-view组件中,我们主要做的事是,在vue组件挂载后,将o2的视图组件,再挂载到o2-view组件的根Dom对象。当然,这里我们要在我们的O2服务器上创建好数据应用和视图,对应本例中,就是“内容管理数据”应用下的“所有信息”视图。..._vue2 oa

[Lua]table使用随笔-程序员宅基地

文章浏览阅读222次。table是lua中非常重要的一种类型,有必要对其多了解一些。

JAVA反射机制原理及应用和类加载详解-程序员宅基地

文章浏览阅读549次,点赞30次,收藏9次。我们前面学习都有一个概念,被private封装的资源只能类内部访问,外部是不行的,但这个规定被反射赤裸裸的打破了。反射就像一面镜子,它可以清楚看到类的完整结构信息,可以在运行时动态获取类的信息,创建对象以及调用对象的属性和方法。

Linux-LVM与磁盘配额-程序员宅基地

文章浏览阅读1.1k次,点赞35次,收藏12次。Logical Volume Manager,逻辑卷管理能够在保持现有数据不变的情况下动态调整磁盘容量,从而提高磁盘管理的灵活性/boot分区用于存放引导文件,不能基于LVM创建PV(物理卷):基于硬盘或分区设备创建而来,生成N多个PE,PE默认大小4M物理卷是LVM机制的基本存储设备,通常对应为一个普通分区或整个硬盘。创建物理卷时,会在分区或硬盘的头部创建一个保留区块,用于记录 LVM 的属性,并把存储空间分割成默认大小为 4MB 的基本单元(PE),从而构成物理卷。

车充产品UL2089安规测试项目介绍-程序员宅基地

文章浏览阅读379次,点赞7次,收藏10次。4、Dielecteic voltage-withstand test 介电耐压试验。1、Maximum output voltage test 输出电压试验。6、Resistance to crushing test 抗压碎试验。8、Push-back relief test 阻力缓解试验。7、Strain relief test 应变消除试验。2、Power input test 功率输入试验。3、Temperature test 高低温试验。5、Abnormal test 故障试验。

IMX6ULL系统移植篇-系统烧写原理说明_正点原子 imx6ull nand 烧录-程序员宅基地

文章浏览阅读535次。镜像烧写说明_正点原子 imx6ull nand 烧录