k-近邻算法


K-近邻算法

机器学习与实战是对《机器学习实战》这本书的学习总结。

一:k-近邻算法分析

简单说,k-近邻算法采用测量不同特征值之间的举例方法进行分类。

工作原理:存在一个样本数据集合,也称训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一数据与所属分类对应的关系。输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似的数据(最近邻)的分类标签。一般来说,我们只选择样本数据集中前k个最相似的数据,这就是k-近邻算法k的出处,通常k是不大于20的整数。最后,选择k个最相似数据中出现次数最多的分类,做为新数据的标签。

二:示例

注:示例中用的Numpy,Matplotlib等请自行网上下载安装

示例1

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]

    #计算欧式距离  
    # tile(A, reps): 构造一个数据,重复 A reps 次  
    diffMat = tile(inX, (dataSetSize,1)) - dataSet # Subtract element-wise

    sqDiffMat = diffMat**2 # 平方  

    sqDistances = sqDiffMat.sum(axis=1)# sum is performed by row
    distances = sqDistances**0.5

    # argsort() 升序方式排序,返回索引值
    sortedDistIndicies = distances.argsort()

    classCount = {} # 定义一个字典,可以追加元素

    for i in range(k):
        voteIlabel = labels[sortedDistIndicies[i]]
    
        ## 计算 label 出现的次数 ,如果没有返回0
        classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 

   #返回最大值的类
    maxCount = 0   
    for key, value in classCount.items():  
        if value > maxCount:  
            maxCount = value  
            maxIndex = key  

    return maxIndex

欧式距离公式:计算两个向量A(x0,y0),B(x1,y1)的距离

d = \sqrt{(x_0-y_0)^2+(y_0-y_1)^2}

测试:

group,labels = kNN.createDataSet();
kNN.classify0([0,0],group, labels, 3)
结果:


示例2 使用k-近邻算法改进约会网站的配对效果

1、将文本记录转换为NumPy的解析程序

def file2Matrix(filename):
    fr = open(filename)
    arrayOLines = fr.readlines()
    numberOfLines = len(arrayOLines)#获得行数
    returnMat = zeros((numberOfLines,3))#创建一个相同行,3列的矩阵
    classLabelVector = []
    index = 0 
    for line in arrayOLines:
        line = line.strip()#截取掉所有的回车字符
        listFormLine = line.split('\t')#将整行数据分割成一个元素列表
        returnMat[index,:] = listFormLine[0:3]#每行取前3个元素
        classLabelVector.append(int(listFormLine[-1]))#将每行的最后一列的元素,添加到向量中
        index +=1 
    return returnMat,classLabelVector
2、使用Matplotlib创建散点图

from numpy import *
import numpy as np  
import matplotlib
import matplotlib.pyplot as plt 
import kNN

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15*array(datingLabels),15*array(datingLabels))
plt.show()

结果如下图



3、归一化数值 数值的属性对计算结果影响很大,因此在处理不同取值范围的特征值时,通常采用的方法是将数值归一化。 将任意取值范围的数值转化为0到1区间内:

newValue = (oldValue - min)/(man - min)

def autoNorm(dataSet):
    minVals = dataSet.min(0)#每列的最小值
    maxVals = dataSet.max(0)
    ranges = maxVals - minVals
    normDataSet = zeros(shape(dataSet))#创建和dataSet同样维度的矩阵
    m = dataSet.shape[0]#获取dataSet的列数
    normDataSet = dataSet - tile(minVals,(m,1)) #矩阵对应元素相减
    normDataSet = dataSet / tile(ranges,(m,1)) 
    return normDataSet, ranges, minVals
4、验证分类器

#创建测试代码, 10%用来测试
def datingClassTest():
    hoRatio = 0.10 #10%
    datingDataMat,datingLabels = file2Matrix('datingTestSet2.txt')
    normMat,ranges,minVals = autoNorm(datingDataMat)
    m = normMat.shape[0] #  Matrix normMat's row number is  m
    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))
测试:
kNN.datingClassTest()

测试结果

the classifier came back with: 1 , the real answer is: 1
the classifier came back with: 2 , the real answer is: 2
the classifier came back with: 1 , the real answer is: 1
the classifier came back with: 3 , the real answer is: 3
the classifier came back with: 3 , the real answer is: 3
the classifier came back with: 2 , the real answer is: 2
the classifier came back with: 1 , the real answer is: 1
the classifier came back with: 3 , the real answer is: 1
the total error rate is : 0.050000

示例3:手写识别系统

#将一个filename中矩阵转化为一个向量
def img2vector(filename):
    returnVect = zeros((1,1024))    #定义一个1行1024列的矩阵
    fr = open(filename)
    for i in range(32):             #共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') #打开训练集目录,获取目录(trainingDigits)的内容
    m = len(trainingFileList) #目录中文件个数
    trainingMat = zeros((m,1024)) #定义一个m行1024列的矩阵
    for i in range(m):
        fileNameStr = trainingFileList[i]   #第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)) 

源代码混合数据下载地址

(End)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值