机器学习002_k-近邻算法

1.1 概述

采用测量不同特征值之间的距离方法进行分类。

优点:精度高、对异常值不敏感、无数据输入假定

缺点:计算复杂度高、空间复杂度高

适用数据范围:数值型和标称型

 

1.2 kNN分类算法

伪代码:

对位置类别属性的数据集中的每个点依次执行以下操作:

(1)计算已知类别数据集中的点与当前点之间的距离;

(2)按照距离递增次序进行排序;

(3)选取与当前点距离最小的k个点;

(4)确定前k个点所在类别的出现频率;

(5)返回前k个点出现频率最高的类别作为当前点的预测分类。

 

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
    # argsort()函数是将x中的元素从小到大排列,提取其对应的index(索引),然后输出到y
    # 在这里y相当于计算后距离所对应的分类项
    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]

注意:代码中iteritems( ) 在python3.5中已被改为 items( )

1.3 示例:改进约会网站的配对效果

针对于约会网站收集的额外的数据信息:

* 每年获得的飞行常客历程数

* 玩视频游戏所消耗时间百分比

* 每周消费的冰淇淋公升数

项目流程:

(1)收集数据:提供文本文件

(2)准备数据:使用Python进行文本文件的解析

(3)分析数据:使用Matplotlib画二维扩散图

(4)训练算法

(5)测试算法

(6)使用算法:产生简单的命令行程序,然后约会人员可以通过输入一些特征数据以判断对方是否为自己喜欢的类型

准备数据:文本记录转换为Numpy的解析程序

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


datingDataMat, datingLabels = kNN.file2matrix('datingTestSet2.txt')

分析数据:使用Matplotlib创建散点图

3种不同的特征,两两之间进行相应的数据展示

from numpy import array
import kNN
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)#add_subplot(mnp)添加子轴、图。subplot(m,n,p)或者subplot(mnp)
#此函数最常用:subplot是将多个图画到一个平面上的工具。其中,m表示是图排成m行,n表示图排成n列,
#也就是整个figure中有n个图是排成一行的,一共m行,如果第一个数字是2就是表示2行图。p是指你现在要把曲线画到figure中哪个图上,
#最后一个如果是1表示是从左到右第一个位置。
ax.scatter(datingDataMat[:,0],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
#以第二列和第三列为x,y轴画出散列点,给予不同的颜色和大小
#scatter(x,y,s=1,c="g",marker="s",linewidths=0)
#s:散列点的大小,c:散列点的颜色,marker:形状,linewidths:边框宽度
plt.show()

准备数据:归一化数值

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

刚刚发现这操作,以前用Matlb进行数据处理,表示麻烦的心累……写了十多个文件进行每一步骤的数据处理操作

测试算法:作为完整程序验证分类器

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)

错误率为6.4% 由此可见,错误率还是比较高的,这里划分的训练集与测试为9:1,但是没有用到测试集,只有训练集。所以说,完全可以通过输入位置对象的属性信息,由分类软件帮助判定某一对象的可交往程度:讨厌、一般喜欢、非常喜欢。

使用算法:构建完整可用系统

通过输入某个人的信息,程序给出她喜欢程度的预测值

def classifyPerson():
    resultList = ['not at all','in small doses','in large doses']
    percentTats = float(input("percentage of time spent playing video games?"))
    ffMiles = float(input("frequent flier miles earned per year?"))
    iceCream = float(input("liters of ice cream consumed per year?"))
    datingDataMat,datingLabels = file2matrix('datingTestSet.txt')
    normMat,ranges,minVals = autoNorm(datingDataMat)	
    inArr = array([ffMiles,percentTats,iceCream])
    classifierResult = classify0((inArr-minVals)/ranges,normMat,datingLabels,3)
    #这边减1是由于最后分类的数据是1,2,3对应到数组中是0,1,2
    print ("You will probably like this person: ",resultList[classifierResult -1])

以上就是如何在数据上构建分类器,数据让人看起来很容易;但是如何在人看不懂的数据上使用分类器呢?

1.4 示例:手写识别系统

项目流程:

32*32像素的黑白图片

(1)收集数据:提供文本文件;

(2)准备数据:编写函数img2vector(),将图片格式转化为分类器使用的向量格式;

(3)分析数据:在Python命令提示符中检查数据,确保符合要求

(4)训练算法

(5)测试算法:测试样本与非测试样本的区别在于测试样本是已经完成分类的数据,如果预测分类与实际类别不同,则标记为一个错误。

(6)使用算法:美国的邮件分拣系统

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

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

testVector = kNN.img2vector('testDigits/0_13.txt')
testVector[0,0:31]

测试算法:使用k-近邻算法识别手写数字

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)))

识别结果:

1.5 算法小结

每个测试向量做2000次距离计算,每个距离包括1024个维度浮点运算,总共执行900次。还要为测试向量准备2MB的存储空间。所以说,这个算法对于存储空间和计算时间的开销是比较大的。

k-近邻算法的另一个缺陷是它无法给出任何数据的基础结构信息,也无法知晓平均实例样本和典型实例样本具有什么特征。

资料来源:《 Machine Learning in Action 》

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值