赞
踩
一、算法流程
(1)收集数据:可以使用任何方法;
(2)准备数据:距离计算所需要的数值,最好是结构化的数据格式;
(3)分析数据:可以使用任何方法;
(4)训练算法:此步骤不适用于k-近邻算法;
(5)测试算法:计算错误率;
(6)使用算法:首先需要输入样本数据和结构化的输出结果,然后运行k-近邻算法,判定输入数据分别属于哪个分类,最后应用,对计算出的分类执行后续的处理。
二、算法实施
对未知类别属性的数据集中的每个点依次执行以下操作:
(1)计算已知类别数据集中的点与当前点之间的距离;
(2)按照距离递增次序排序;
(3)选取与当前点距离最小的k个点;
(4)确定前k个点所在类别的出现频率;
(5)返回前k个点出现频率最高的类别作为当前点的预测分类。
三、代码详解
(python开发环境搭建,包括安装numpy,scipy,matplotlib等科学计算库的安装不再赘述,百度即可)
(1)进入python交互式开发环境,编写并保存如下代码,本文档中代码保存名为“KNN”;
- import numpy
- import operator
- from os import listdir
- from numpy import *
- #k-近邻算法
- def classify0(inX, dataSet, labels, k):
- # type: (object, object, object, object) -> object
- dataSetSize = dataSet.shape[0] #计算距离,使用欧氏距离。
- diffMat = numpy.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]
- #编写基本的通用函数
- 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
- #将文本记录转换为numpy的解析程序
- def file2matrix(filename):
- fr = open(filename)
- numberOfLines = len(fr.readlines()) #get the number of lines in the file得到文件行数
- returnMat = numpy.zeros((numberOfLines, 3)) #prepare matrix to return创建返回的numpy矩阵
- 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(numpy.int(listFromLine[-1]))
- index += 1
- return returnMat, classLabelVector
- #归一化特征值
- def autoNorm(dataSet):
- minVals = dataSet.min(0)
- maxVals = dataSet.max(0)
- ranges = maxVals - minVals
- m = dataSet.shape[0]
- normDataSet = dataSet - numpy.tile(minVals, (m, 1))
- normDataSet = normDataSet / numpy.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 = numpy.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 / numpy.float(numTestVecs))
- print errorCount'''
- #将图像转换为向量
- def img2vector(filename):
- returnVect = numpy.zeros((1, 1024))
- fr = open(filename)
- for i in range(32):
- lineStr = fr.readline()
- for j in range(32):
- returnVect[0,32*i+j] = numpy.int(lineStr[j])
- return returnVect
- #手写数字识别系统的测试代码
- def handwritingClassTest():
- hwLabels = []
- trainingFileList = listdir('trainingDigits') #load the training set获取目录内容
- m = len(trainingFileList)
- trainingMat = numpy.zeros((m, 1024))
- for i in range(m):
- fileNameStr = trainingFileList[i]
- fileStr = fileNameStr.split('.')[0] #take off .txt 从文件名解析分类数字
-
-
- classNumStr = numpy.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 = numpy.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 'the total number of errors is: %d' % errorCount
- print 'the total error rate is: %f' % (errorCount / numpy.float(mTest))
(2)python交互式界面输入以下命令导入上面编辑的程序模块。
- >>>import KNN
- >>>group,labels=KNN.createDataSet()
- >>>import matplotlib
- >>>import matplotlib.pyplot as plot
- >>>fig=plt.figure()
- >>>ax=fig.add_subplot(111)
- >>>ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))
(4)测试输出结果
KNN.handwritingClassTest()
四、算法优缺点
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。