一 算法原理:已知一个训练样本集,其中每个训练样本都有自己的标记(label),即我们知道样本集中每一个样本数据与所属分类的对应关系。输入没有标记的新数据后,将新数据的每个特征与样本集中的数据对应的特征进行比较,然后提取样本集中特征最相似数据的分类标记。一般的,我们选择样本集中前k个最相似的数据分类标签,其中出现次数最多的分类作为我们新数据的分类标记。简单的说,k_近邻算法采用测量不同特征值之间的距离方法进行分类。
算法优点: 精度高、对异常值不敏感,无数据输入假设。
算法缺点: 由于要将每个待分类的数据特征与样本集中的每个样例进行对应特征距离的计算,所以计算的时间空间复杂度高。
二 算法的实现(手写体识别)
1.数据准备:采用的是32*32像素的黑白图像(0-9,每个数字大约200个样本,trainingDigits用于数据分类器训练,testDigits用于测试),这里为了方便理解,将图片转换成了文本格式。
2.代码实现:
将图片转化为一个向量,我们把一个32*32的二进制图像矩阵转化为一个1*1024的向量,编写一个函数vector2d,如下代码
def vector2d(filename):
rows = 32
cols = 32
imgVector = zeros((1,rows * cols))
fileIn = open(filename)
for row in xrange(rows):
lineStr = fileIn.readline()
for col in xrange(cols):
imgVector[0,row *32 + col] = int(lineStr[col])
return imgVector
trainingData set 和testData set 的载入
'''load dataSet '''
def loadDataSet():
print '....Getting training data'
dataSetDir = 'D:/pythonCode/MLCode/KNN/'
trainingFileList = os.listdir(dataSetDir + 'trainingDigits')
numSamples = len(trainingFileList) train_x = zeros((numSamples,1024))
train_y = []
for i in xrange(numSamples):
filename = trainingFileList[i]
train_x[i,:] = vector2d(dataSetDir + 'trainingDigits/%s'%filename)
label = int(filename.split('_')[0])
train_y.append(label)
''' ....Getting testing data...'''
print '....Getting testing data...'
testFileList = os .listdir(dataSetDir + 'testDigits')
numSamples = len(testFileList)
test_x = zeros((numSamples,1024))
test_y = []
for i in xrange(numSamples):
filename = testFileList[i]
test_x[i,:] = vector2d(dataSetDir + 'testDigits/%s'%filename)
label = int(filename.split('_')[0])
test_y.append(label) return train_x,train_y,test_x,test_y
分类器的构造
from numpy import * import os def kNNClassify(newInput,dataSet,labels,k):
numSamples = dataSet.shape[0] diff = tile(newInput,(numSamples,1)) - dataSet
squaredDiff = diff ** 2
squaredDist = sum(squaredDiff,axis = 1)
distance = squaredDist ** 0.5 sortedDistIndex = argsort(distance) classCount = {}
for i in xrange(k):
votedLabel = labels[sortedDistIndex[i]]
classCount[votedLabel] = classCount.get(votedLabel,0) + 1 maxValue = 0
for key,value in classCount.items():
if maxValue < value:
maxValue = value
maxIndex = key
分类测试
def testHandWritingClass():
print 'load data....'
train_x,train_y,test_x,test_y = loadDataSet()
print'training....' print'testing'
numTestSamples = test_x.shape[0]
matchCount = 0.0
for i in xrange(numTestSamples):
predict = kNNClassify(test_x[i],train_x,train_y,3)
if predict != test_y[i]: print 'the predict is ',predict,'the target value is',test_y[i] if predict == test_y[i]:
matchCount += 1
accuracy = float(matchCount)/numTestSamples print'The accuracy is :%.2f%%'%(accuracy * 100)
测试结果
testHandWritingClass()
load data....
....Getting training data
....Getting testing data...
training....
testing
the predict is 7 the target value is 1
the predict is 9 the target value is 3
the predict is 9 the target value is 3
the predict is 3 the target value is 5
the predict is 6 the target value is 5
the predict is 6 the target value is 8
the predict is 3 the target value is 8
the predict is 1 the target value is 8
the predict is 1 the target value is 8
the predict is 1 the target value is 9
the predict is 7 the target value is 9
The accuracy is :98.84%
注:以上代码运行环境为Python2.7.11
从上面结果可以看出knn 分类效果还不错,在我看来,knn就是简单粗暴,就是把未知分类的数据特征与我们分类好的数据特征进行比对,选择最相似的标记作为自己的分类,辣么问题来了,如果我们的新数据的特征在样本集中比较少见,这时候就会出现问题,分类错误的可能性非常大,反之,如果样例集中某一类的样例比较多,那么新数据被分成该类的可能性就会大,如何保证分类的公平性,我们就需要进行加权了。
补充:关于K值的选取,当k越小时,分类结果对原数据的敏感性越强,易受到异常数据的影响,即模型越复杂。