机器学习算法中的监督学习分为分类和回归两类。分类机器学习算法比较常用且易于理解。本文就从最简单的K-NN( k-Nearest Neighbor )分类算法开始,来了解机器学习模型的创建过程。
K-NN算法概述
K-NN也称为K-近邻算法,通过测量不同特征值之间的距离进行分类。
K-NN算法的工作原理是:首先准备一个已经分类的训练数据集,这个数据集的分类结果已知;其次,对于一个没有分类的新数据,将新数据的每个特征与训练数据集中的数据进行比较;然后,提取训练集中与新样本最接近的k个分类结果;最后,在k个结果中选择一个出现最多的分类作为新数据的类别。
本文通过一个对手写数字进行分类模型来简述K-NN算法的建模步骤。说明:本文中的代码基于Python3实现的。
手写数字分类
因为K-NN算法不需要训练模型,直接使用已经分类好的数据集来分类就可以。因此我们准备好已经分类好的数据集。
准备的数据集分为训练数据集trainingDigits和测试数据集testDigits,且两组数据相互独立没有重叠。
为了方便处理,我们将图形文件转换为一个numpy数组。下面我们给出将数字文件转换为numpy数组的代码:
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
实现K-NN算法
#dataSet为输入的训练数据集
#k为选择距离最小的k个点
def classify(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
sortedDistIndicies = distances.argsort()
classCount={}
#选择距离最小的k个点
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
#对选择的k个点进行排序,以方便选择分类最多的
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
使用K-NN算法测试手写数字识别算法,其中模型中使用的训练数据集和测试数据集可以通过以下链接得到:
其中trainingDigits为训练数据集,testDigits为测试数据集
代码如下:
def handwritingClassTest():
hwLabels = []
#训练数据集的文件目录
trainingFileList = listdir('digits/trainingDigits')
m = len(trainingFileList)
trainingMat = zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
hwLabels.append(classNumStr)
#加载并转换训练数据集
trainingMat[i,:] = img2vector('digits/trainingDigits/%s' % fileNameStr)
#测试数据集的目录
testFileList = listdir('digits/testDigits')
#errorCount记录分类错误的数量
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('digits/testDigits/%s' % fileNameStr)
#调用K-NN分类函数
classifierResult = classify(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))
输出结果为:
the classifier came back with: 0, the real answer is: 0
the classifier came back with: 0, the real answer is: 0
...
the classifier came back with: 1, the real answer is: 8
the classifier came back with: 8, the real answer is: 8
...
the classifier came back with: 9, the real answer is: 9
the classifier came back with: 1, the real answer is: 9
the classifier came back with: 9, the real answer is: 9
the total number of errors is: 10
the total error rate is: 0.010571
从运行结果可以看出这个手写数字分类模型的错误率非常的低,仅为1.06%。我们还可以通过修改模型的参数来观察错误率的变化,可修改的参数包括k的值,训练样本的数目。
总结
本文通过一个手写数字分类的例子展示了K-NN算法,K-NN是分类算法总最简单有效的算法。而K-NN算法不需要模型的训练过程,直接基于已分类号的数据进行预测,因此比较容易上手。
参考资料
《机器学习实战》第二章 k-近邻算法