定义
采用不同特征值之间的距离方法进行分类
优点:精度高、对异常值不敏感、无数据输入假定
缺点:计算复杂度高、空间复杂度高
适用:数值型与标称型数据
算法概述
给定一个训练集(其中的实例类别已定),对新的输入实例(无标签),比较新实例特征与样本集中的特征,在训练数据集中找到与该实例中最邻近的K个实例,这K个实例的多数属于那个类,就把该输入实例分为这个类(K<=20)
输入:实例的特征向量
输出:实例的类别
三要素:K值的选择,距离度量、分类决策规则——对特征空间的划分
1.K值的选择——交叉验证法。较小、较大分别影响,近似误差、估计误差
2.距离度量
3.分类决策规则——多数表决
伪代码
对未知类别属性的数据集中的每个点依次执行以下操作
- 计算已知类别数据集中的点与当前点之间的距离(特征值之间的距离)
- 按照距离递增次序排序
- 选取与当前点距离最小的前K个点
- 确定前K个点所在类别出现的频率
- 返回前K个点出现频率最高的类别作为当前点的预测分类
python代码示例(将每组数据划到某个类中)
场景1:电影分类
通过统计电影中打斗次数与接吻次数来区分动作与爱情片
场景2:改进约会网站
3个特征
场景3:改进手写数字识别系统——在图像上应用KNN
32*32黑白图像转换成1024的向量
'''
Created on Sep 20, 2018
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
import matplotlib
import matplotlib.pyplot as plt
# 创建数据集与标签
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
#kNN分类器
def classify0(inX, dataSet, labels, k):#inX待分类数据集
dataSetSize = dataSet.shape[0] #4行,每行是个样本
#使用欧式距离计算距离
diffMat = tile(inX, (dataSetSize,1)) - dataSet #tile()函数是将待分类数据集重复几行几次,与样本集矩阵一样大小,方便相减
sqDiffMat = diffMat**2 #取平方
sqDistances = sqDiffMat.sum(axis=1) #按列求和
distances = sqDistances**0.5
sortedDistIndicies = distances.argsort() #argsort()将distances 中的元素从小到大排列,并返回其对应的索引
classCount={} #字典,前k个标签及次数
for i in range(k):
voteIlabel = labels[sortedDistIndicies[i]] #返回距离最近的K的标签
classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 #如果当前标签不存在,则创建并设置值为0;存在就加1;// Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值
sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
#items() 函数以列表返回可遍历的(键, 值) 元组数组
#operator模块提供的itemgetter函数用于获取对象的哪些维的数据
#reverse=True降序排列,默认为升序排列
#sortedClassCount是个列表,元素为元组(标签,次数)
return sortedClassCount[0][0] #返回频率最高的元素的标签,第一个元组的第一个元素
#处理数据的输入格式问题
#读取文件,返回训练样本矩阵和类别标签向量
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
#不同特征值取值范围幅度大,数值归一化,将取值范围归一化到0到1或者-1到1之间
#newvalue=(oldvalue-min)/(max-min)
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.10 #hold out 10%
datingDataMat,datingLabels = file2matrix('datingTestSet2.txt') #load data setfrom file
normdatingDataMat, ranges, minVals = autoNorm(datingDataMat)
m = normdatingDataMat.shape[0]
numTestVecs = int(m*hoRatio)
errorCount = 0.0 #错误计数器变量
for i in range(numTestVecs):
classifierResult = classify0(normdatingDataMat[i,:],normdatingDataMat[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 classifyPerson():
resultList=['not at all','in small doses','in large doses']
ffMiles=float(input("frequent flier miles earned per year?"))
percentTats=float(input("percentage of time spent playing video games?"))
iceCream=float(input("liters of ice cream consumed per year?"))
datingDataMat,datingLabels=file2matrix("datingTestSet2.txt")
normMat,ranges,minVals=autoNorm(datingDataMat)
inArr=array([ffMiles,percentTats,iceCream])
classifierResult=classify0((inArr-minVals)/ranges,normMat,datingLabels,3)
print("you will probabaly like this person: ",resultList[classifierResult-1])
#手写数字识别
#将图像格式化处理为一个向量32*32变成1*1024的向量
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
#手写数字识别系统的测试代码
def handwritingClassTest():
hwLabels = []
trainingFileList = listdir(r'I:\study\nlp\机器学习实战源码\MLiA_SourceCode\machinelearninginaction\Ch02\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('I:/study/nlp/机器学习实战源码/MLiA_SourceCode/machinelearninginaction/Ch02/digits/trainingDigits/%s' % fileNameStr)
testFileList = listdir(r'I:\study\nlp\机器学习实战源码\MLiA_SourceCode\machinelearninginaction\Ch02\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('I:/study/nlp/机器学习实战源码/MLiA_SourceCode/machinelearninginaction/Ch02/digits/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("\nthe total number of errors is: %d" % errorCount)
print("\nthe total error rate is: %f" % (errorCount/float(mTest)))
if __name__ == '__main__':
group, labels=createDataSet()
sortedClassCount=classify0([0,0], group, labels, 4)
datingDataMat,datingLabels=file2matrix(r'I:\study\nlp\机器学习实战源码\MLiA_SourceCode\machinelearninginaction\Ch02\datingTestSet2.txt')
#分析约会数据:使用matplotlib创建散点图
fig=plt.figure()
ax=fig.add_subplot(111)
#不同兴趣爱好的人类别也不一样
ax.scatter(datingDataMat[:,0],datingDataMat[:,1],15.0*array(datingLabels),15.0*array(datingLabels)) #使用约会数据的第1列与第2列数据
plt.show()
normdatingDataSet, ranges, minVals=autoNorm(datingDataMat)
datingClassTest() #约会网站性能
classifyPerson() #约会网站测试
testVector=img2vector(r'I:\study\nlp\机器学习实战源码\MLiA_SourceCode\machinelearninginaction\Ch02\digits\trainingDigits\2_0.txt')
#图片转换为向量
handwritingClassTest() #手写数字测试
#总结
1.先将训练集变成矩阵形式,一行代表一个样本(创建0矩阵,再往里填充)
标签变成列表的形式
2.KNN针对大数据集,存储空间大,需计算新样例与所有样本的距离,耗时;另外,无法给出任何数据的基础结构信息(含有什么特征)——概率测量方法可以解决这个问题(决策树)