注:转载请标明原文出处链接:https://xiongyiming.blog.csdn.net/article/details/95311111
k-近邻(k-Nearest Neighbor,kNN)分类算法,是一个理论上比较成熟的方法,也是最简单的机器学习算法之一。该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别。
所谓k近邻算法,即是给定一个训练数据集,对新的输入实例,在训练数据集中找到与该实例最邻近的k个实例(也就是上面所说的k个邻居,这k个实例的多数属于某个类,就把该输入实例分类到这个类中。
(以上来源于百度百科)
例如,下图中的样本有红色和蓝色两个颜色的类别。
那么问题来了,如下图所示,如果在这些样本中出来一个新的未知分类的数据点(图中绿色的点),那么这个数据点术语那种类别呢? k k k-近邻算法是如何计算的?
首先设置 k k k=3,那么k-近邻算法就是计算未知点(图中绿色的点)与样本中最近的3个点( k k k=3),如下图所示:
现在判断最近的三个点的类别,都属于蓝色,则属于蓝色的频率为1。则未知点的类别应属于蓝色。
下面再看一个例子,如下图所示,样本中有出现一个未知点(图中绿色的点),那么这个位置点有属于哪类呢?
同样的方式,首先设置 k k k=3,那么k-近邻算法就是计算未知点(图中绿色的点)与样本中最近的3个点( k k k=3),如下图所示:
现在判断最近的三个点的类别,两个属于红色,一个属于蓝色,则属于蓝色的频率为1/3,而属于红色的频率为2/3。因此则未知点的类别应属于红色。
以上就是算法的思想,思路非常简单,找出最近的点,然后找到类别最大的频率即可。
(1) 计算已知类别数据集中的点与当前点之间的距离;
(2) 按照距离递增次序排序;
(3) 选取与当前点距离最小的k个点;
(4) 确定 k k k个点所在类别出现的概率;
(5) 返回前 k k k个点出现频率最高的类别作为当前点的预测分类。
调用 kNN.classify0(inX, dataSet, labels, k) 函数即可,其函数用法如下:
kNN.classify0(inX, dataSet, labels, k)
其中,参数:
inX: 测试集(1xN)
dataSet: 输入的样本集(NxM)
labels: 标签 (1xM vector)
k: 选择最近邻的数据
kNN.py 子函数文件
# kNN: k Nearest Neighbors
#
# Input: inX: vector to compare to existing dataset (1xN)
# dataSet: size m data set of known vectors (NxM)
# labels: data set labels (1xM vector)
# k: number of neighbors to use for comparison (should be an odd number)
#
# Output: the most popular class label
from numpy import *
import operator
from os import listdir
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
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k): # 投票
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
Main.py 主函数文件
from numpy import *
import kNN
group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
dataSet=group
inX=[0,0]
k=3
print("dataSet=",group)
print("labels=",labels)
print("k=",k)
# 调用kNN.classify0()函数
# inX 测试集(1xN)
# dataSet 输入的样本集(NxM)
# labels 标签 (1xM vector)
# k 选择最近邻的数据
result=kNN.classify0(inX, dataSet, labels, k)
# 打印结果
print("testdata=",inX)
print("result=",result)
手写识别系统
训练集trainingDigits目录下包含约2000个样本,每种数字大约200个样本。 测试集testDigits目录下包含900个测试数据。
kNN.py (k=3)
# kNN: k Nearest Neighbors
#
# Input: inX: vector to compare to existing dataset (1xN)
# dataSet: size m data set of known vectors (NxM)
# labels: data set labels (1xM vector)
# k: number of neighbors to use for comparison (should be an odd number)
#
# Output: the most popular class label
from numpy import *
import operator
from os import listdir
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
sortedDistIndicies = distances.argsort()
classCount={}
for i in range(k): # 投票
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
sortedClassCount = sorted(classCount.items(), 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
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
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
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)
def img2vector(filename): # 将32*32大小的图像转化成向量
returnVect = zeros((1,1024)) # 创建32*32=1024的Numpy数组
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
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir('digits/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('digits/trainingDigits/%s' % fileNameStr)
testFileList = listdir('digits/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('digits/testDigits/%s' % fileNameStr)
classifierResult = classify0(vectorUnderTest, trainingMat, hwLabels, 3) # k=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)))
main.py
from numpy import *
import kNN
# 手写识别系统
from os import listdir #从os模块中导入listdir,他可以列出给定目录的文件名
result=kNN.handwritingClassTest()
[1] 机器学习实战. 人民邮电出版社.
[2] https://coding.imooc.com/class/chapter/169.html#Anchor
[3] https://blog.csdn.net/BaiHuaXiu123/article/details/54579296