机器学习经典分类算法——k-近邻算法(附python实现代码及数
据集)
⽬录
⼯作原理
存在⼀个样本数据集合,也称作训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每⼀数据与所属分类的对应关系。输⼊没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进⾏⽐较,然后算法提取样本集中特征最相似数据(最近邻)的分类特征。⼀般来说,我们只选择样本数据集中前k个最相似的数据,这就是k-近邻算法中k的出处,通常k是不⼤于20的整数。最后选择k个最相似数据中出现次数最多的分类,作为新数据的分类。
举个例⼦,现在我们⽤k-近邻算法来分类⼀部电影,判断它属于爱情⽚还是动作⽚。现在已知六部电影的打⽃镜头、接吻镜头以及电影评估类型,如下图所⽰。
现在我们有⼀部电影,它有18个打⽃镜头、90个接吻镜头,想知道这部电影属于什么类型。根据k-近邻算法,我们可以这么算。⾸先计算未知电影与样本集中其他电影的距离(先不管这个距离如何算,后⾯会提到)。现在我们得到了样本集中所有电影与未知电影的距离。按照距离递增排序,可以到k个距离最近的电影。
现在假定k=3,则三个最靠近的电影依次是He's Not Really into Dudes、Beautiful Woman、California Man。
python实现
⾸先编写⼀个⽤于创建数据集和标签的函数,要注意的是该函数在实际⽤途上没有多⼤意义,仅⽤于测试代码。
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
然后是函数classify0(),该函数的功能是使⽤k-近邻算法将每组数据划分到某个类中,其伪代码如下:
对未知类别属性的数据集中的每个点依次执⾏以下操作:
(1)计算已知类别数据集中的点与当前点之间的距离;
(2)按照距离递增次序排序;
(3)选取与当前点距离最⼩的k个点;
(4)确定前k个点所在类别的出现频率;
(5)返回前k个点出现频率最⾼的类别作为当前点的预测分类。
Python代码如下:
def classify0(inX, dataSet, labels, k):
dataSetSize = dataSet.shape[0]  # shape[0]表⽰矩阵有多少⾏ shape[1]表⽰矩阵有多少列
diffMat = tile(inX, (dataSetSize,1)) - dataSet  # 计算Ai-Bi
sqDiffMat = diffMat**2  #计算(Ai-Bi)^2
sqDistances = sqDiffMat.sum(axis=1) # 计算(A0-B0)^2+...+(Ai-Bi)^2
distances = sqDistances**0.5    # 计算((A0-B0)^2+...+(Ai-Bi)^2)^0.5 也就是欧式距离
sortedDistIndicies = distances.argsort()    # 得到数组的值按递增排序的索引
classCount = {}
for i in range (k): #距离最近的k个点
voteIlabel = labels[sortedDistIndicies[i]]
classCount[voteIlabel] = (voteIlabel, 0)+1    # 如果voteIlabels的key不存在就返回0
sortedClassCount = sorted(classCount.items(),key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
该函数具有4个输⼊参数,分别是待分类的输⼊向量inX、输⼊的训练样本集dataSet、标签向量labels、选择距离最近的k个点。其中距离使⽤欧式距离,计算公式如下:
例如,点(0,0)与(1,2)之间的欧式距离计算为:
如果数据集存在4个特征值,则点(1,0,0,1)与(7,6,9,4)之间的欧式距离计算为:
计算完所有点之间的距离后,可以对数据按照从⼩到⼤的次序排序。然后,确定前k个距离最⼩元素所在的主要分类。输⼊k总是正整数;最后,将classCount字典分解为元组列表,然后按照从⼤到⼩的次序进⾏排序,最后返回频率最⾼的元素标签。
运⾏程序后得到如下结果应该是B
算法实战
举两个例⼦,⼀个是约会对象的好感度预测,⼀个是⼿写识别系统。
约会对象好感度预测
故事背景
不喜欢的⼈
魅⼒⼀般的⼈
极具魅⼒的⼈
她还发现当她归类约会对象时主要考虑以下三个特征:
⽉收⼊
颜值
每周跑步的公⾥数
她将这些数据保存在⽂本⽂件中。
准备数据:从⽂本⽂件中解析数据
⾸先要将待处理数据的格式改变为分类器可以接受的格式。创建名为file2matrix()的函数,以此来处理输⼊格式问题。该函数的输⼊为⽂件名字符串,输出为训练样本矩阵和类标签向量。
学python需要什么def file2matrix(filename):
fr = open(filename,encoding = 'utf-8')
arrayOfLines = fr.readlines()  #读取⽂件的每⼀⾏
numberOfLines = len(arrayOfLines) #获得⽂件⾏数
returnMat = zeros((numberOfLines,3))
classLabelVector = []
index = 0
for line in arrayOfLines:
line = line.strip() #去除⾸尾空格和回车
listFromLine = line.split() #按照tab键分割数据
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return  returnMat,classLabelVector
打开⽂件,得到⽂件的⾏数。然后创建以零填充的矩阵。循环处理⽂件中的每⾏数据,⾸先使⽤函数line.strip()截取掉所有的回车字符,然后使⽤tab字符\t将上⼀步得到的整⾏数据分割成⼀个元素列表。接着,选取前3个元素,将它们存到特征矩阵中。利⽤负索引将列表的最后⼀列存储到向量classLabelVector中。
分析数据:使⽤Matplotlib创建散点图
这⼀步不过多解释,创建可视化数据图。
def drawFig(datingDataMat,datingLabels):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(datingDataMat[:, 1], datingDataMat[:, 2],15.0*array(datingLabels), 15.0*array(datingLabels))
plt.show()
准备数据:归⼀化数值
因为⽉收⼊的数值和其他两个特征相⽐⼤很多,因此对于计算距离的影响远⼤于其他两个特征。但是在海伦看来这是三个等权重的特征,⽉收⼊不应该如此严重地影响到计算结果。
因此我们需要进⾏数值归⼀化。采⽤公式newValue = (oldValue-min)/(max-min)可以将任意取值范围的特征值转化为0到1的区间。其中min和max分别是数据集中最⼩特征值和最⼤特征值。
def autoNorm(dataSet):
minVals = dataSet.min(0)    #参数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))
return normDataSet, ranges, minVals
测试算法:作为完整程序验证分类器
在数据集中选取10%的数据作为测试数据。
def datingClassTest():
hoRatio = 0.10  # 10%的数据作为测试集
datingDataMat, datingLabels = file2matrix("")  # 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)))
得到结果如下:
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: 1, the real answer is: 1
...
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
错误率仅为5%左右,基本上可以正确的分类。
使⽤算法:构建完整可⽤的系统
def classifyPerson():
resultList = ["not at all", "in small doses", "in large doses"]
percentTats = float(input("monthly income?"))
ffMiles = float(input("level of appearance?"))
iceCream = float(input("running miles per month?"))
datingDataMat, datingLabels = file2matrix("")  # load data setfrom file
normMat, ranges, minVals = autoNorm(datingDataMat)
inArr = array([ffMiles, percentTats, iceCream])
classifierResult = classify0(inArr, datingDataMat, datingLabels, 3)
print("You will probably like this person:",resultList[classifierResult-1])
海伦可以将她要约会的对象信息输⼊程序,程序会给出她对对⽅的喜欢诚度的预测值。例如输⼊⼀个⽉收⼊为20000、颜值为5、每周运动量为1公⾥的数据,得到的结果是:
monthly income?20000
level of appearance?5
running miles per month?1
You will probably like this person: in small doses
⼿写识别系统
为了简单起见,这⾥只识别数字0-9。数据集分为训练集和测试集分别存放在两个⽂件夹下。
准备数据:将图像转换为测试向量
和之前⼀个例⼦不⼀样的地⽅在于数据的处理上。我们必须将图像格式处理为⼀个向量。我们将32x32的⼆进制图像矩阵转换为1x1024的向量。
编写函数img2vector,将图像转换为向量。
def img2vector(filename):
returnVector = zeros((1,1024))
fr = open(filename)
for i in range(32):
lineStr = fr.readline()
for j in range(32):
returnVector[0,32*i+j] = int(lineStr[j])
return returnVector
测试算法:使⽤k-近邻算法识别⼿写数字
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir("trainingDigits")
mTrain = len(trainingFileList)
trainingMat = zeros((mTrain,1024))
for i in range(mTrain):
filenameStr = trainingFileList[i]
fileStr = filenameStr.split('.')[0]
classNum = int(fileStr.split('_')[0])
hwLabels.append(classNum)
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]
classNum = int(fileStr.split('_')[0])
testVector = img2vector("testDigits/%s"%filenameStr)
classifierResult = classify0(testVector, trainingMat, hwLabels, 4)
print("the classifier came back with: %d, the real answer is: %d" %(classifierResult, classNum))
if(classifierResult != classNum):
errorCount += 1.0
print("\nthe total number of errors is: %d" % errorCount)
print("\nthe total error rate is: %f" % (errorCount / float(mTest)))
得到结果如下: